Skip to main content

teams_cli/
tui.rs

1//! The keyboard-first chat reader.
2//!
3//! A calm two-pane ledger: chats on the left, the open conversation on the
4//! right, a header that always says where you are and a footer that always
5//! says what the keys do. Reads run in the background so the keyboard never
6//! waits on the network, results are cached per chat, and every screen stays
7//! legible without colour (`NO_COLOR`).
8use std::collections::{HashMap, HashSet};
9use std::io::{self, IsTerminal};
10use std::sync::{Arc, mpsc};
11use std::time::{Duration, Instant};
12
13use crossterm::event::{
14    self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
15    Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
16};
17use crossterm::execute;
18use crossterm::terminal::{
19    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
20};
21use jiff::{ToSpan, Zoned, tz::TimeZone};
22use ratatui::Terminal;
23use ratatui::backend::{CrosstermBackend, TestBackend};
24use ratatui::layout::{Alignment, Constraint, Layout, Rect};
25use ratatui::style::{Color, Modifier, Style};
26use ratatui::text::{Line, Span};
27use ratatui::widgets::{
28    Block, Borders, Clear, List, ListItem, ListState, Padding, Paragraph, Wrap,
29};
30use serde_json::{Value, json};
31use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
32
33use crate::backend::TeamsBackend;
34use crate::config;
35use crate::desktop::MAX_BODY;
36use crate::error::AppError;
37use crate::graph::Page;
38use crate::render::{self, ChatRow, Entry, View};
39
40/// Records requested per read; the most both backends accept.
41const PAGE: u16 = 50;
42/// How long a selection must rest before its conversation is fetched, so
43/// scrolling through the ledger does not fire a read per row.
44const DWELL: Duration = Duration::from_millis(250);
45const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
46/// Below this width the ledger and the conversation take turns.
47const SPLIT_WIDTH: u16 = 80;
48const MIN_WIDTH: u16 = 50;
49const MIN_HEIGHT: u16 = 14;
50/// How often a live session re-reads the open chat and the chat list. Desktop reads come
51/// from the local cache, so they can be frequent; Graph is kept within its rate limits.
52const DESKTOP_POLL: (Duration, Duration) = (Duration::from_secs(3), Duration::from_secs(15));
53const GRAPH_POLL: (Duration, Duration) = (Duration::from_secs(15), Duration::from_secs(60));
54/// Rows the composer grows to before its draft scrolls.
55const COMPOSE_ROWS: usize = 5;
56/// Lines one ledger entry takes: title, preview and a blank separator.
57const CHAT_ROW_HEIGHT: u16 = 3;
58/// Conversation lines one mouse-wheel notch scrolls.
59const WHEEL_LINES: usize = 3;
60
61#[derive(Clone, Copy, Debug, Eq, PartialEq)]
62pub enum TuiExit {
63    Quit,
64    Authenticate,
65}
66
67/// Where chats come from: a connected profile or deterministic sample data.
68pub enum Source {
69    Live {
70        backend: Arc<TeamsBackend>,
71        profile: String,
72        /// Whether the profile allowed writes at launch; checked again before every send.
73        can_send: bool,
74    },
75    Demo,
76}
77
78/// Raw mode and the alternate screen for as long as it lives; with `mouse`, the
79/// terminal also reports wheel and clicks instead of turning the wheel into arrow keys.
80struct TerminalGuard {
81    mouse: bool,
82}
83
84impl TerminalGuard {
85    fn enter(mouse: bool) -> Result<Self, AppError> {
86        enable_raw_mode()?;
87        let entered = if mouse {
88            execute!(
89                io::stdout(),
90                EnterAlternateScreen,
91                EnableMouseCapture,
92                EnableBracketedPaste
93            )
94        } else {
95            execute!(io::stdout(), EnterAlternateScreen, EnableBracketedPaste)
96        };
97        if let Err(error) = entered {
98            let _ = execute!(
99                io::stdout(),
100                DisableBracketedPaste,
101                DisableMouseCapture,
102                LeaveAlternateScreen
103            );
104            let _ = disable_raw_mode();
105            return Err(error.into());
106        }
107        Ok(Self { mouse })
108    }
109}
110
111impl Drop for TerminalGuard {
112    fn drop(&mut self) {
113        let _ = disable_raw_mode();
114        if self.mouse {
115            let _ = execute!(io::stdout(), DisableMouseCapture);
116        }
117        let _ = execute!(io::stdout(), DisableBracketedPaste, LeaveAlternateScreen);
118    }
119}
120
121fn require_terminal(hint: &str) -> Result<(), AppError> {
122    if io::stdout().is_terminal() && io::stdin().is_terminal() {
123        Ok(())
124    } else {
125        Err(AppError::NonInteractive(format!(
126            "`teams tui` needs a terminal; {hint}"
127        )))
128    }
129}
130
131/// Opens the chat reader and returns how the person left it.
132pub fn run(source: Source) -> Result<TuiExit, AppError> {
133    run_with_watch(source, None, &mut InboxState::default())
134}
135
136/// Drafts stay in memory while the CLI steps out of the inbox to reauthenticate.
137#[derive(Default)]
138pub struct InboxState {
139    drafts: HashMap<String, String>,
140    pending_sends: HashMap<String, String>,
141}
142
143pub fn run_with_watch(
144    source: Source,
145    mut watch: Option<crate::desktop::ConnectionWatch>,
146    saved: &mut InboxState,
147) -> Result<TuiExit, AppError> {
148    require_terminal("use `teams tui --demo --snapshot` for an inspectable frame")?;
149    let color = std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty());
150    let mut app = App::new(
151        source,
152        Theme { color },
153        Zoned::now().with_time_zone(TimeZone::system()),
154    );
155    app.drafts = std::mem::take(&mut saved.drafts);
156    app.pending_sends = std::mem::take(&mut saved.pending_sends);
157    app.start();
158    let _guard = TerminalGuard::enter(true)?;
159    let mut terminal = Terminal::new(CrosstermBackend::new(io::stdout()))?;
160    loop {
161        app.tick();
162        if let Some(result) = watch
163            .as_ref()
164            .and_then(crate::desktop::ConnectionWatch::result)
165        {
166            if let Err(error) = result {
167                app.startup_failed(&error);
168            }
169            watch = None;
170        }
171        terminal.draw(|frame| app.draw(frame))?;
172        if !event::poll(Duration::from_millis(100))? {
173            continue;
174        }
175        let action = match event::read()? {
176            Event::Key(key) if key.kind == KeyEventKind::Press => app.handle_key(key),
177            Event::Paste(text) => {
178                app.paste(&text);
179                Action::None
180            }
181            Event::Mouse(mouse) => {
182                app.handle_mouse(mouse);
183                Action::None
184            }
185            _ => Action::None,
186        };
187        match action {
188            Action::None => {}
189            Action::Quit => {
190                app.preserve_drafts(saved);
191                return Ok(TuiExit::Quit);
192            }
193            Action::Authenticate => {
194                app.preserve_drafts(saved);
195                return Ok(TuiExit::Authenticate);
196            }
197        }
198    }
199}
200
201/// One ANSI-free frame of the demo, for documentation and tests.
202pub fn snapshot(width: u16, height: u16) -> Result<String, AppError> {
203    let now: Zoned = "2026-10-13T10:15:00+02:00[Europe/Amsterdam]"
204        .parse()
205        .expect("valid demo clock");
206    let mut app = App::new(Source::Demo, Theme { color: false }, now);
207    app.start();
208    app.open_selected();
209    let mut terminal = Terminal::new(TestBackend::new(
210        width.max(MIN_WIDTH),
211        height.max(MIN_HEIGHT),
212    ))
213    .expect("test backend is infallible");
214    terminal
215        .draw(|frame| app.draw(frame))
216        .expect("test backend is infallible");
217    Ok(buffer_text(terminal.backend().buffer()))
218}
219
220fn buffer_text(buffer: &ratatui::buffer::Buffer) -> String {
221    let mut output = String::new();
222    for y in 0..buffer.area.height {
223        let mut line = String::new();
224        for x in 0..buffer.area.width {
225            line.push_str(buffer[(x, y)].symbol());
226        }
227        output.push_str(line.trim_end());
228        output.push('\n');
229    }
230    while output.ends_with("\n\n") {
231        output.pop();
232    }
233    output
234}
235
236enum Action {
237    None,
238    Quit,
239    Authenticate,
240}
241
242enum Outcome {
243    DebuggingRequired,
244    Restarted(Result<(), AppError>),
245    StrayFlags(Vec<String>),
246    FlagsCleared(Result<(), AppError>),
247    Chats {
248        more: bool,
249        result: Result<Page, AppError>,
250    },
251    Messages {
252        chat: String,
253        older: bool,
254        result: Result<Page, AppError>,
255    },
256    Me(Result<Value, AppError>),
257    Delivery {
258        chat: String,
259        id: String,
260        result: Result<Value, AppError>,
261    },
262    Sent {
263        chat: String,
264        result: Result<Value, AppError>,
265    },
266}
267
268#[derive(Clone, Copy, PartialEq, Eq)]
269enum DebuggingRestart {
270    Offered,
271    Confirming,
272    Running,
273}
274
275/// Cleanup of user-wide WebView2 debugging flags that let other apps hold the port.
276#[derive(Clone, PartialEq, Eq)]
277struct FlagCleanup {
278    stage: Cleanup,
279    /// Applications that served the port, to quit and reopen afterwards.
280    apps: Vec<String>,
281}
282
283#[derive(Clone, Copy, PartialEq, Eq)]
284enum Cleanup {
285    Offered,
286    Confirming,
287    Running,
288    Done,
289}
290
291impl FlagCleanup {
292    fn apps(&self) -> String {
293        if self.apps.is_empty() {
294            "the apps that use WebView2".into()
295        } else {
296            self.apps.join(", ")
297        }
298    }
299}
300
301enum Load {
302    Loading,
303    Ready,
304    Failed { message: String, auth: bool },
305}
306
307impl Load {
308    fn failed(error: &AppError) -> Self {
309        Self::Failed {
310            message: error.to_string(),
311            auth: matches!(error, AppError::Auth(_)),
312        }
313    }
314}
315
316struct Thread {
317    items: Vec<Value>,
318    cursor: Option<String>,
319    load: Load,
320    loading_older: bool,
321    /// A newest-page read is in flight, so polls do not stack up.
322    fetching: bool,
323}
324
325#[derive(Clone, Copy, Eq, PartialEq)]
326enum Focus {
327    Chats,
328    Thread,
329}
330
331#[derive(Clone, Copy, Eq, PartialEq)]
332enum Overlay {
333    Help,
334    Filter,
335}
336
337#[derive(Clone, Copy, Eq, PartialEq)]
338enum Stage {
339    Editing,
340    Sending,
341    Unconfirmed,
342    Checking,
343    ConfirmResend,
344}
345
346/// A draft for one chat; `cursor` is a byte offset into `text`.
347struct Compose {
348    chat: String,
349    text: String,
350    cursor: usize,
351    stage: Stage,
352}
353
354impl Compose {
355    fn insert(&mut self, c: char) {
356        self.text.insert(self.cursor, c);
357        self.cursor += c.len_utf8();
358    }
359}
360
361#[derive(Clone, Copy)]
362enum Tone {
363    Quiet,
364    Success,
365    Error,
366}
367
368struct Notice {
369    tone: Tone,
370    text: String,
371}
372
373impl Notice {
374    fn new(tone: Tone, text: impl Into<String>) -> Self {
375        Self {
376            tone,
377            text: text.into(),
378        }
379    }
380}
381
382struct App {
383    theme: Theme,
384    source: Source,
385    outcomes: (mpsc::Sender<Outcome>, mpsc::Receiver<Outcome>),
386    now: Zoned,
387    account: Option<String>,
388    viewer: Option<String>,
389    chats: Vec<Value>,
390    rows: Vec<ChatRow>,
391    chat_cursor: Option<String>,
392    chats_load: Load,
393    startup_auth_error: Option<String>,
394    sending_paused: bool,
395    debugging_restart: Option<DebuggingRestart>,
396    flag_cleanup: Option<FlagCleanup>,
397    loading_more: bool,
398    filter: String,
399    /// Indices into `rows` that pass the filter, in ledger order.
400    visible: Vec<usize>,
401    list: ListState,
402    selected_at: Option<Instant>,
403    threads: HashMap<String, Thread>,
404    focus: Focus,
405    /// Conversation lines hidden below the viewport; 0 follows the newest.
406    scroll: usize,
407    thread_height: usize,
408    /// Conversation lines above the viewport when scrolled to the newest.
409    thread_overflow: usize,
410    /// Where the last frame drew the ledger rows and the conversation pane, for the mouse.
411    ledger_area: Option<Rect>,
412    thread_area: Option<Rect>,
413    overlay: Option<Overlay>,
414    notice: Notice,
415    frame: usize,
416    compose: Option<Compose>,
417    /// Closed, unsent drafts per chat; kept in memory only.
418    drafts: HashMap<String, String>,
419    /// Correlation IDs for possibly-sent drafts; kept across closing the composer.
420    pending_sends: HashMap<String, String>,
421    /// Set by `r` so its result is announced; quiet reloads say nothing.
422    refreshing: bool,
423    fetching_chats: bool,
424    /// When a newest-page read last succeeded, and whether a refresh has failed since.
425    synced_at: Option<Zoned>,
426    stale: bool,
427    thread_polled: Instant,
428    chats_polled: Instant,
429}
430
431impl App {
432    fn preserve_drafts(&mut self, saved: &mut InboxState) {
433        if let Some(compose) = self.compose.take() {
434            self.drafts.insert(compose.chat, compose.text);
435        }
436        saved.drafts = std::mem::take(&mut self.drafts);
437        saved.pending_sends = std::mem::take(&mut self.pending_sends);
438    }
439
440    fn startup_failed(&mut self, error: &AppError) {
441        self.sending_paused |= self.can_send();
442        if let Source::Live { can_send, .. } = &mut self.source {
443            *can_send = false;
444        }
445        if matches!(error, AppError::Auth(_)) {
446            if let Some(compose) = self.compose.take() {
447                self.drafts.insert(compose.chat, compose.text);
448            }
449            self.overlay = None;
450            self.debugging_restart = None;
451            self.flag_cleanup = None;
452            self.startup_auth_error = Some(error.to_string());
453            self.chats_load = Load::failed(error);
454            self.notice = Notice::new(Tone::Error, error.to_string());
455        } else {
456            let message = if self.sending_paused {
457                format!("{error} Sending is paused; reopen the inbox to check it again.")
458            } else {
459                error.to_string()
460            };
461            self.notice = Notice::new(Tone::Error, message);
462        }
463    }
464
465    fn new(source: Source, theme: Theme, now: Zoned) -> Self {
466        Self {
467            theme,
468            source,
469            outcomes: mpsc::channel(),
470            now,
471            account: None,
472            viewer: None,
473            chats: Vec::new(),
474            rows: Vec::new(),
475            chat_cursor: None,
476            chats_load: Load::Loading,
477            startup_auth_error: None,
478            sending_paused: false,
479            debugging_restart: None,
480            flag_cleanup: None,
481            loading_more: false,
482            filter: String::new(),
483            visible: Vec::new(),
484            list: ListState::default(),
485            selected_at: None,
486            threads: HashMap::new(),
487            focus: Focus::Chats,
488            scroll: 0,
489            thread_height: 10,
490            thread_overflow: 0,
491            ledger_area: None,
492            thread_area: None,
493            overlay: None,
494            notice: Notice::new(Tone::Quiet, "Reading your chats…"),
495            frame: 0,
496            compose: None,
497            drafts: HashMap::new(),
498            pending_sends: HashMap::new(),
499            refreshing: false,
500            fetching_chats: false,
501            synced_at: None,
502            stale: false,
503            thread_polled: Instant::now(),
504            chats_polled: Instant::now(),
505        }
506    }
507
508    /// Records the outcome of reading the newest chats or messages for the header.
509    fn synced(&mut self, ok: bool) {
510        if ok {
511            self.synced_at = Some(match self.source {
512                Source::Live { .. } => Zoned::now().with_time_zone(TimeZone::system()),
513                Source::Demo => self.now.clone(),
514            });
515            self.stale = false;
516        } else {
517            self.stale = true;
518        }
519    }
520
521    fn view(&self) -> View {
522        View {
523            now: self.now.clone(),
524            width: 100,
525        }
526    }
527
528    fn backend(&self) -> Option<Arc<TeamsBackend>> {
529        match &self.source {
530            Source::Live { backend, .. } => Some(backend.clone()),
531            Source::Demo => None,
532        }
533    }
534
535    /// Why a chat shows only its latest message, said for where messages come from.
536    fn missing_history_note(&self) -> &'static str {
537        match self.backend().as_deref() {
538            Some(TeamsBackend::Desktop(_)) => {
539                "No messages for this chat were found in the Teams cache on this PC. Latest message:"
540            }
541            _ => "Only the latest message is available.",
542        }
543    }
544
545    fn can_send(&self) -> bool {
546        match &self.source {
547            Source::Live { can_send, .. } => *can_send,
548            Source::Demo => true,
549        }
550    }
551
552    fn profile(&self) -> &str {
553        match &self.source {
554            Source::Live { profile, .. } => profile,
555            Source::Demo => "demo",
556        }
557    }
558
559    /// The second header line as parts, most useful first; whole parts are dropped
560    /// from the end when the terminal is narrow.
561    fn context(&self) -> Vec<Vec<Span<'static>>> {
562        let theme = self.theme;
563        let mut parts = Vec::new();
564        if matches!(self.chats_load, Load::Ready) {
565            let more = if self.chat_cursor.is_some() { "+" } else { "" };
566            parts.push(vec![
567                Span::styled(format!("{}{more}", self.rows.len()), theme.figure()),
568                Span::styled(" chats", theme.muted()),
569            ]);
570            let unread = self.rows.iter().filter(|row| row.unread).count();
571            if unread > 0 {
572                parts.push(vec![
573                    Span::styled(unread.to_string(), theme.unread()),
574                    Span::styled(" unread", theme.unread_label()),
575                ]);
576            }
577        }
578        parts.push(vec![Span::styled(
579            match &self.source {
580                Source::Live { backend, .. } => match backend.as_ref() {
581                    TeamsBackend::Graph(_) => "Microsoft Graph",
582                    TeamsBackend::Desktop(_) => "Teams desktop cache",
583                },
584                Source::Demo => "sample data",
585            },
586            theme.muted(),
587        )]);
588        parts
589    }
590
591    /// How fresh the chats are, as a status dot: live, syncing, or since when a
592    /// refresh keeps failing. Sample data has nothing to be fresh about.
593    fn freshness(&self) -> Option<Vec<Span<'static>>> {
594        let theme = self.theme;
595        let dot = |style: Style, text: String| {
596            vec![
597                Span::styled("● ", style),
598                Span::styled(text, style.remove_modifier(Modifier::BOLD)),
599            ]
600        };
601        if self.busy() {
602            return Some(vec![Span::styled(
603                format!("{} syncing", self.spinner()),
604                theme.accent(),
605            )]);
606        }
607        if let Load::Failed { auth, .. } = self.chats_load {
608            let text = if auth {
609                "sign-in needed"
610            } else {
611                "not connected"
612            };
613            return Some(dot(theme.error(), text.into()));
614        }
615        if matches!(self.source, Source::Demo) {
616            return None;
617        }
618        let at = self.synced_at.as_ref()?.strftime("%H:%M");
619        Some(if self.stale {
620            dot(theme.error(), format!("stale since {at}"))
621        } else {
622            dot(theme.success(), "live".into())
623        })
624    }
625
626    fn start(&mut self) {
627        if let Some(backend) = self.backend()
628            && matches!(backend.as_ref(), TeamsBackend::Graph(_))
629        {
630            let sender = self.outcomes.0.clone();
631            tokio::spawn(async move {
632                let _ = sender.send(Outcome::Me(backend.me().await));
633            });
634        }
635        self.load_chats(false);
636    }
637
638    fn load_chats(&mut self, more: bool) {
639        self.debugging_restart = None;
640        self.flag_cleanup = None;
641        let initial = !more && !matches!(self.chats_load, Load::Ready);
642        let cursor = if more {
643            if self.loading_more || self.chat_cursor.is_none() {
644                return;
645            }
646            self.loading_more = true;
647            self.chat_cursor.clone()
648        } else {
649            if !matches!(self.chats_load, Load::Ready) {
650                self.chats_load = Load::Loading;
651            }
652            self.fetching_chats = true;
653            None
654        };
655        match self.backend() {
656            Some(backend) => {
657                let sender = self.outcomes.0.clone();
658                tokio::spawn(async move {
659                    if initial
660                        && let TeamsBackend::Desktop(client) = backend.as_ref()
661                        && client.needs_debugging_restart().await
662                    {
663                        let _ = sender.send(Outcome::DebuggingRequired);
664                        return;
665                    }
666                    let result = backend.chats(PAGE, cursor.as_deref()).await;
667                    if initial
668                        && result.is_err()
669                        && let TeamsBackend::Desktop(client) = backend.as_ref()
670                        && let Some(apps) = client.stray_debugging_flags().await
671                    {
672                        let _ = sender.send(Outcome::StrayFlags(apps));
673                        return;
674                    }
675                    let _ = sender.send(Outcome::Chats { more, result });
676                });
677            }
678            None => self.apply(Outcome::Chats {
679                more,
680                result: Ok(demo_chats(&self.now)),
681            }),
682        }
683    }
684
685    fn load_messages(&mut self, chat: String, older: bool) {
686        let cursor = match self.threads.get_mut(&chat) {
687            Some(thread) if older => {
688                if thread.loading_older || thread.cursor.is_none() {
689                    return;
690                }
691                thread.loading_older = true;
692                thread.cursor.clone()
693            }
694            Some(thread) => {
695                if !matches!(thread.load, Load::Ready) {
696                    thread.load = Load::Loading;
697                }
698                thread.fetching = true;
699                None
700            }
701            None => {
702                self.threads.insert(
703                    chat.clone(),
704                    Thread {
705                        items: Vec::new(),
706                        cursor: None,
707                        load: Load::Loading,
708                        loading_older: false,
709                        fetching: true,
710                    },
711                );
712                None
713            }
714        };
715        match self.backend() {
716            Some(backend) => {
717                let sender = self.outcomes.0.clone();
718                tokio::spawn(async move {
719                    let result = backend
720                        .messages(Some(&chat), None, None, PAGE, cursor.as_deref())
721                        .await;
722                    let _ = sender.send(Outcome::Messages {
723                        chat,
724                        older,
725                        result,
726                    });
727                });
728            }
729            None => {
730                let result = Ok(demo_messages(&chat, &self.now));
731                self.apply(Outcome::Messages {
732                    chat,
733                    older,
734                    result,
735                });
736            }
737        }
738    }
739
740    fn apply(&mut self, outcome: Outcome) {
741        match outcome {
742            Outcome::DebuggingRequired => {
743                self.fetching_chats = false;
744                self.debugging_restart = Some(DebuggingRestart::Offered);
745                self.notice = Notice::new(Tone::Quiet, "Teams needs debugging enabled to connect");
746            }
747            Outcome::StrayFlags(apps) => {
748                self.fetching_chats = false;
749                self.flag_cleanup = Some(FlagCleanup {
750                    stage: Cleanup::Offered,
751                    apps,
752                });
753                self.notice =
754                    Notice::new(Tone::Quiet, "Another app holds the Teams debugging port");
755            }
756            Outcome::FlagsCleared(result) => match result {
757                Ok(()) => {
758                    if let Some(cleanup) = &mut self.flag_cleanup {
759                        cleanup.stage = Cleanup::Done;
760                    }
761                    self.notice = Notice::new(Tone::Quiet, "Debugging flags removed");
762                }
763                Err(error) => {
764                    self.flag_cleanup = None;
765                    self.chats_load = Load::failed(&error);
766                    self.notice =
767                        Notice::new(Tone::Error, "Flags were not removed; press r to retry");
768                }
769            },
770            Outcome::Restarted(result) => {
771                self.debugging_restart = None;
772                match result {
773                    Ok(()) => self.load_chats(false),
774                    Err(error) => {
775                        self.chats_load = Load::failed(&error);
776                        self.notice =
777                            Notice::new(Tone::Error, "Restart did not connect; press r to retry");
778                    }
779                }
780            }
781            Outcome::Chats { more, result } => {
782                if more {
783                    self.loading_more = false;
784                } else {
785                    self.fetching_chats = false;
786                }
787                match result {
788                    Ok(page) => {
789                        if page.viewer.is_some() {
790                            self.viewer = page.viewer;
791                        }
792                        let keep = self.selected_row().map(|row| row.id.clone());
793                        let cursor = page.next_cursor.filter(|_| page.truncated);
794                        if more {
795                            let known: HashSet<String> =
796                                self.rows.iter().map(|row| row.id.clone()).collect();
797                            self.chats.extend(page.items.into_iter().filter(|chat| {
798                                !chat["id"].as_str().is_some_and(|id| known.contains(id))
799                            }));
800                            self.chat_cursor = cursor;
801                        } else {
802                            if !matches!(self.chats_load, Load::Ready) {
803                                self.notice = Notice::new(
804                                    Tone::Quiet,
805                                    "Enter opens a chat  ·  / filters  ·  ? shows every key",
806                                );
807                            } else if std::mem::take(&mut self.refreshing) {
808                                self.notice = Notice::new(Tone::Success, "Up to date.");
809                            }
810                            let old = std::mem::take(&mut self.chats);
811                            (self.chats, self.chat_cursor) =
812                                merge_newest(page.items, cursor, old, self.chat_cursor.take());
813                        }
814                        self.chats_load = Load::Ready;
815                        self.rebuild(keep.as_deref());
816                        if !more {
817                            self.synced(true);
818                        }
819                    }
820                    Err(error) if more || matches!(self.chats_load, Load::Ready) => {
821                        self.refreshing = false;
822                        self.notice = Notice::new(Tone::Error, error.to_string());
823                        if !more {
824                            self.synced(false);
825                        }
826                    }
827                    Err(error) => {
828                        self.notice = Notice::new(Tone::Error, "Could not read your chats.");
829                        self.chats_load = Load::failed(&error);
830                    }
831                }
832            }
833            Outcome::Messages {
834                chat,
835                older,
836                result,
837            } => {
838                let opened = self.selected_row().is_some_and(|row| row.id == chat);
839                let Some(thread) = self.threads.get_mut(&chat) else {
840                    return;
841                };
842                if older {
843                    thread.loading_older = false;
844                } else {
845                    thread.fetching = false;
846                }
847                match result {
848                    Ok(page) => {
849                        if older {
850                            let known: HashSet<&str> = thread
851                                .items
852                                .iter()
853                                .filter_map(|m| m["id"].as_str())
854                                .collect();
855                            let fresh: Vec<Value> = page
856                                .items
857                                .into_iter()
858                                .filter(|m| !m["id"].as_str().is_some_and(|id| known.contains(id)))
859                                .collect();
860                            let added = fresh.len();
861                            thread.items.extend(fresh);
862                            self.notice = Notice::new(
863                                Tone::Success,
864                                format!(
865                                    "Loaded {added} older message{}.",
866                                    if added == 1 { "" } else { "s" }
867                                ),
868                            );
869                            thread.cursor = page.next_cursor.filter(|_| page.truncated);
870                        } else {
871                            let cursor = page.next_cursor.filter(|_| page.truncated);
872                            let old = std::mem::take(&mut thread.items);
873                            (thread.items, thread.cursor) =
874                                merge_newest(page.items, cursor, old, thread.cursor.take());
875                        }
876                        thread.load = Load::Ready;
877                        if self.viewer.is_none() && page.viewer.is_some() {
878                            self.viewer = page.viewer;
879                            self.rebuild(None);
880                        }
881                        if opened && !older {
882                            self.prefetch_neighbours();
883                            self.synced(true);
884                        }
885                    }
886                    Err(error) if older || matches!(thread.load, Load::Ready) => {
887                        self.notice = Notice::new(Tone::Error, error.to_string());
888                        if opened && !older {
889                            self.synced(false);
890                        }
891                    }
892                    Err(error) => thread.load = Load::failed(&error),
893                }
894            }
895            Outcome::Me(Ok(me)) => {
896                self.account = me["displayName"].as_str().map(String::from);
897                if let Some(id) = me["id"].as_str() {
898                    self.viewer = Some(id.into());
899                    self.rebuild(None);
900                }
901            }
902            // The header simply stays without a name; chats still load.
903            Outcome::Me(Err(_)) => {}
904            Outcome::Delivery { chat, id, result } => {
905                if self.pending_sends.get(&chat) != Some(&id) {
906                    return;
907                }
908                match result {
909                    Ok(value)
910                        if value["found"] == true
911                            && matches!(
912                                value["delivery_state"].as_str(),
913                                Some("delivered" | "queued")
914                            ) =>
915                    {
916                        self.pending_sends.remove(&chat);
917                        self.drafts.remove(&chat);
918                        if self.compose.as_ref().is_some_and(|c| c.chat == chat) {
919                            self.compose = None;
920                        }
921                        self.notice = Notice::new(
922                            Tone::Success,
923                            if value["delivery_state"] == "delivered" {
924                                "Delivered; matched the original client message ID."
925                            } else {
926                                "Found queued in Teams; delivery is not confirmed."
927                            },
928                        );
929                    }
930                    result => {
931                        if let Some(compose) = self.compose.as_mut().filter(|c| c.chat == chat) {
932                            compose.stage = Stage::Unconfirmed;
933                        }
934                        self.notice = Notice::new(Tone::Error, match result {
935                            Err(error) => error.to_string(),
936                            Ok(value) if value["found"] == true => "Found the original message in Teams' cache; delivery is still unconfirmed.".into(),
937                            Ok(_) => "Delivery remains uncertain. Checked the newest 50 cached messages; absence does not prove failure.".into(),
938                        });
939                    }
940                }
941            }
942            Outcome::Sent { chat, result } => {
943                match result {
944                    Ok(value) => {
945                        let state = crate::delivery::State::from_message(&value);
946                        if value["source"] == "desktop"
947                            && matches!(
948                                state,
949                                crate::delivery::State::Failed | crate::delivery::State::Unknown
950                            )
951                        {
952                            if let Some(compose) = self.compose.as_mut().filter(|c| c.chat == chat)
953                            {
954                                compose.stage = Stage::Unconfirmed;
955                            }
956                            self.notice = Notice::new(Tone::Error, state.notice());
957                        } else {
958                            if self.compose.as_ref().is_some_and(|c| c.chat == chat) {
959                                self.compose = None;
960                            }
961                            self.drafts.remove(&chat);
962                            self.pending_sends.remove(&chat);
963                            self.notice = Notice::new(
964                                Tone::Success,
965                                if value["source"] == "desktop" {
966                                    state.notice()
967                                } else {
968                                    "Sent."
969                                },
970                            );
971                        }
972                    }
973                    Err(error) => {
974                        let uncertain = matches!(
975                            error,
976                            AppError::Unconfirmed(_) | AppError::UnconfirmedSend { .. }
977                        );
978                        if let Some(compose) = self.compose.as_mut().filter(|c| c.chat == chat) {
979                            compose.stage = if uncertain {
980                                Stage::Unconfirmed
981                            } else {
982                                Stage::Editing
983                            };
984                        }
985                        if !uncertain {
986                            self.pending_sends.remove(&chat);
987                        }
988                        self.notice = Notice::new(Tone::Error, error.to_string());
989                    }
990                }
991                // Even a failed send may have reached Teams, so show what the chat holds now.
992                if self.backend().is_some() {
993                    self.load_chats(false);
994                    self.load_messages(chat, false);
995                }
996            }
997        }
998    }
999
1000    /// Recomputes rows and the filtered ledger, keeping the selected chat.
1001    fn rebuild(&mut self, keep: Option<&str>) {
1002        let before = self.selected_row().map(|row| row.id.clone());
1003        let keep = keep.map(String::from).or_else(|| before.clone());
1004        let view = self.view();
1005        self.rows = self
1006            .chats
1007            .iter()
1008            .map(|chat| ChatRow::new(chat, &view, self.viewer.as_deref()))
1009            .collect();
1010        let needle = self.filter.to_lowercase();
1011        self.visible = (0..self.rows.len())
1012            .filter(|&i| {
1013                let row = &self.rows[i];
1014                needle.is_empty()
1015                    || row.title.to_lowercase().contains(&needle)
1016                    || row
1017                        .preview
1018                        .as_deref()
1019                        .is_some_and(|p| p.to_lowercase().contains(&needle))
1020            })
1021            .collect();
1022        let position = keep
1023            .and_then(|id| self.visible.iter().position(|&i| self.rows[i].id == id))
1024            .or_else(|| (!self.visible.is_empty()).then_some(0));
1025        self.list.select(position);
1026        // A reload can move the open chat in the ledger; only a different chat starts afresh.
1027        if self.selected_row().map(|row| row.id.clone()) != before {
1028            self.selected_at = Some(Instant::now());
1029            self.scroll = 0;
1030        }
1031    }
1032
1033    fn selected_row(&self) -> Option<&ChatRow> {
1034        self.list
1035            .selected()
1036            .and_then(|i| self.visible.get(i))
1037            .map(|&i| &self.rows[i])
1038    }
1039
1040    fn select(&mut self, index: usize) {
1041        if self.visible.is_empty() {
1042            return;
1043        }
1044        let index = index.min(self.visible.len() - 1);
1045        if self.list.selected() != Some(index) {
1046            self.list.select(Some(index));
1047            self.selected_at = Some(Instant::now());
1048            self.scroll = 0;
1049        }
1050        if index + 3 >= self.visible.len() && self.filter.is_empty() {
1051            self.load_chats(true);
1052        }
1053    }
1054
1055    fn open_selected(&mut self) {
1056        self.selected_at = None;
1057        // A chat that failed while prefetched gets one fresh attempt when opened.
1058        if let Some(id) = self.selected_row().map(|row| row.id.clone())
1059            && self
1060                .threads
1061                .get(&id)
1062                .is_none_or(|thread| matches!(thread.load, Load::Failed { .. }))
1063        {
1064            self.load_messages(id, false);
1065        }
1066    }
1067
1068    /// Loads the chats either side of the open one, so stepping through the ledger
1069    /// shows them without waiting.
1070    fn prefetch_neighbours(&mut self) {
1071        let Some(index) = self.list.selected() else {
1072            return;
1073        };
1074        let neighbours: Vec<String> = [index.checked_sub(1), index.checked_add(1)]
1075            .into_iter()
1076            .flatten()
1077            .filter_map(|i| self.visible.get(i))
1078            .map(|&i| self.rows[i].id.clone())
1079            .filter(|id| !self.threads.contains_key(id))
1080            .collect();
1081        for id in neighbours {
1082            self.load_messages(id, false);
1083        }
1084    }
1085
1086    fn tick(&mut self) {
1087        self.frame = self.frame.wrapping_add(1);
1088        while let Ok(outcome) = self.outcomes.1.try_recv() {
1089            self.apply(outcome);
1090        }
1091        if let Some(message) = &self.startup_auth_error {
1092            self.chats_load = Load::Failed {
1093                message: message.clone(),
1094                auth: true,
1095            };
1096            self.notice = Notice::new(
1097                Tone::Error,
1098                "Sign-in is needed. Reply drafts are kept while you reconnect.",
1099            );
1100            return;
1101        }
1102        if self
1103            .selected_at
1104            .is_some_and(|at| at.elapsed() >= DWELL || self.focus == Focus::Thread)
1105        {
1106            self.open_selected();
1107        }
1108        if let Some(backend) = self.backend() {
1109            let (thread_every, chats_every) = match backend.as_ref() {
1110                TeamsBackend::Desktop(_) => DESKTOP_POLL,
1111                TeamsBackend::Graph(_) => GRAPH_POLL,
1112            };
1113            if self.chats_polled.elapsed() >= chats_every
1114                && matches!(self.chats_load, Load::Ready)
1115                && !self.loading_more
1116                && !self.fetching_chats
1117            {
1118                self.chats_polled = Instant::now();
1119                self.now = Zoned::now().with_time_zone(TimeZone::system());
1120                self.load_chats(false);
1121            }
1122            if self.thread_polled.elapsed() >= thread_every {
1123                self.thread_polled = Instant::now();
1124                if let Some(id) = self.selected_row().map(|row| row.id.clone())
1125                    && self.threads.get(&id).is_some_and(|t| {
1126                        matches!(t.load, Load::Ready) && !t.fetching && !t.loading_older
1127                    })
1128                {
1129                    self.load_messages(id, false);
1130                }
1131            }
1132        }
1133    }
1134
1135    /// Background prefetches stay quiet; only the open chat shows activity.
1136    fn busy(&self) -> bool {
1137        matches!(self.chats_load, Load::Loading)
1138            || self.loading_more
1139            || self.selected_row().is_some_and(|row| {
1140                self.threads
1141                    .get(&row.id)
1142                    .is_some_and(|t| t.loading_older || matches!(t.load, Load::Loading))
1143            })
1144    }
1145
1146    fn sign_in_needed(&self) -> bool {
1147        matches!(self.chats_load, Load::Failed { auth: true, .. })
1148            || self.selected_row().is_some_and(|row| {
1149                matches!(
1150                    self.threads.get(&row.id).map(|t| &t.load),
1151                    Some(Load::Failed { auth: true, .. })
1152                )
1153            })
1154    }
1155
1156    fn refresh(&mut self) {
1157        self.notice = Notice::new(Tone::Quiet, "Refreshing…");
1158        self.refreshing = true;
1159        self.reload();
1160    }
1161
1162    /// Reloads the ledger and the open chat, keeping older pages, selection and scroll.
1163    fn reload(&mut self) {
1164        self.thread_polled = Instant::now();
1165        self.chats_polled = Instant::now();
1166        if matches!(self.source, Source::Live { .. }) {
1167            self.now = Zoned::now().with_time_zone(TimeZone::system());
1168        }
1169        self.load_chats(false);
1170        if let Some(id) = self.selected_row().map(|row| row.id.clone())
1171            && self.threads.get(&id).is_none_or(|t| !t.loading_older)
1172        {
1173            self.load_messages(id, false);
1174        }
1175    }
1176
1177    fn open_compose(&mut self) {
1178        let Some(chat) = self.selected_row().map(|row| row.id.clone()) else {
1179            return;
1180        };
1181        if !self.can_send() {
1182            self.notice = Notice::new(
1183                Tone::Error,
1184                if self.sending_paused {
1185                    "Sending is paused after a startup check failed. Reopen the inbox to check the connection again; your profile's send permission is unchanged."
1186                } else {
1187                    "This profile is read-only; sending needs a profile created with `teams init --backend desktop --allow-send`."
1188                },
1189            );
1190            return;
1191        }
1192        let text = self.drafts.remove(&chat).unwrap_or_default();
1193        self.focus = Focus::Thread;
1194        let stage = if self.pending_sends.contains_key(&chat) {
1195            Stage::Unconfirmed
1196        } else {
1197            Stage::Editing
1198        };
1199        self.compose = Some(Compose {
1200            chat,
1201            cursor: text.len(),
1202            text,
1203            stage,
1204        });
1205    }
1206
1207    /// Every key but ctrl-c belongs to the composer while it is open.
1208    fn compose_key(&mut self, key: KeyEvent) {
1209        let control = key.modifiers.contains(KeyModifiers::CONTROL);
1210        let Some(compose) = self.compose.as_mut() else {
1211            return;
1212        };
1213        match compose.stage {
1214            Stage::Sending | Stage::Checking => {}
1215            Stage::ConfirmResend => {
1216                if key.code == KeyCode::Char('y') {
1217                    self.send();
1218                } else {
1219                    compose.stage = Stage::Unconfirmed;
1220                    self.notice = Notice::new(
1221                        Tone::Quiet,
1222                        "Resend cancelled; delivery is still uncertain.",
1223                    );
1224                }
1225            }
1226            Stage::Unconfirmed => match key.code {
1227                KeyCode::Char('r') => self.check_delivery(),
1228                KeyCode::Char('s') => {
1229                    compose.stage = Stage::ConfirmResend;
1230                    self.notice = Notice::new(
1231                        Tone::Error,
1232                        "The original may still arrive. Send a second copy? Press y to resend; any other key cancels.",
1233                    );
1234                }
1235                KeyCode::Esc => {
1236                    let compose = self.compose.take().expect("composer is open");
1237                    self.drafts.insert(compose.chat, compose.text);
1238                    self.notice = Notice::new(
1239                        Tone::Quiet,
1240                        "Possibly-sent draft kept; c reopens delivery checks.",
1241                    );
1242                }
1243                _ => {
1244                    self.notice = Notice::new(
1245                        Tone::Error,
1246                        "Possibly sent: r checks delivery; s explicitly resends; esc keeps the draft.",
1247                    );
1248                }
1249            },
1250            Stage::Editing => match key.code {
1251                KeyCode::Esc => {
1252                    let compose = self.compose.take().expect("composer is open");
1253                    if !compose.text.trim().is_empty() {
1254                        self.drafts.insert(compose.chat, compose.text);
1255                        self.notice = Notice::new(Tone::Quiet, "Draft kept; c continues it.");
1256                    }
1257                }
1258                KeyCode::Enter if key.modifiers.contains(KeyModifiers::ALT) => compose.insert('\n'),
1259                KeyCode::Char('j') if control => compose.insert('\n'),
1260                KeyCode::Enter => {
1261                    let length = compose.text.chars().count();
1262                    if compose.text.trim().is_empty() {
1263                        self.notice = Notice::new(Tone::Quiet, "Write something first.");
1264                    } else if length > MAX_BODY {
1265                        self.notice = Notice::new(
1266                            Tone::Error,
1267                            format!("Too long to send: {length} of at most {MAX_BODY} characters."),
1268                        );
1269                    } else {
1270                        self.send();
1271                    }
1272                }
1273                KeyCode::Backspace => {
1274                    if let Some(c) = compose.text[..compose.cursor].chars().next_back() {
1275                        compose.cursor -= c.len_utf8();
1276                        compose.text.remove(compose.cursor);
1277                    }
1278                }
1279                KeyCode::Delete if compose.cursor < compose.text.len() => {
1280                    compose.text.remove(compose.cursor);
1281                }
1282                KeyCode::Left => {
1283                    if let Some(c) = compose.text[..compose.cursor].chars().next_back() {
1284                        compose.cursor -= c.len_utf8();
1285                    }
1286                }
1287                KeyCode::Right => {
1288                    if let Some(c) = compose.text[compose.cursor..].chars().next() {
1289                        compose.cursor += c.len_utf8();
1290                    }
1291                }
1292                KeyCode::Home => compose.cursor = 0,
1293                KeyCode::End => compose.cursor = compose.text.len(),
1294                KeyCode::Char(c) if !control && c != '\0' => compose.insert(c),
1295                _ => {}
1296            },
1297        }
1298    }
1299
1300    /// Bracketed paste is text, never a sequence of commands or send keystrokes.
1301    fn paste(&mut self, text: &str) {
1302        if let Some(compose) = self.compose.as_mut().filter(|c| c.stage == Stage::Editing) {
1303            let text = text.replace("\r\n", "\n").replace('\r', "\n");
1304            for c in text
1305                .chars()
1306                .filter(|c| !c.is_control() || matches!(c, '\n' | '\t'))
1307            {
1308                compose.insert(c);
1309            }
1310        }
1311    }
1312
1313    fn send(&mut self) {
1314        if !self.can_send() {
1315            self.notice = Notice::new(
1316                Tone::Error,
1317                "Sending is paused; reconnect Teams before sending this draft",
1318            );
1319            return;
1320        }
1321        let Some(compose) = self.compose.as_mut() else {
1322            return;
1323        };
1324        compose.stage = Stage::Sending;
1325        let (chat, text) = (compose.chat.clone(), compose.text.clone());
1326        let id = crate::delivery::client_message_id();
1327        self.pending_sends.insert(chat.clone(), id.clone());
1328        self.notice = Notice::new(Tone::Quiet, "Sending…");
1329        match &self.source {
1330            Source::Live {
1331                backend, profile, ..
1332            } => {
1333                let (backend, profile) = (backend.clone(), profile.clone());
1334                let sender = self.outcomes.0.clone();
1335                tokio::spawn(async move {
1336                    let result = async {
1337                        config::load(Some(&profile))?.1.require_writable()?;
1338                        backend.send_with_id(&chat, &text, &id).await
1339                    }
1340                    .await;
1341                    let _ = sender.send(Outcome::Sent { chat, result });
1342                });
1343            }
1344            Source::Demo => {
1345                let message = json!({
1346                    "id": format!("{chat}/sent{}", self.frame),
1347                    "messageType": "message",
1348                    "createdDateTime": self.now.timestamp().to_string(),
1349                    "from": {"user": demo_person("me")},
1350                    "body": {"contentType": "text", "content": text},
1351                });
1352                if let Some(thread) = self.threads.get_mut(&chat) {
1353                    thread.items.insert(0, message.clone());
1354                }
1355                self.apply(Outcome::Sent {
1356                    chat,
1357                    result: Ok(message),
1358                });
1359            }
1360        }
1361    }
1362
1363    fn check_delivery(&mut self) {
1364        let Some(compose) = self.compose.as_mut() else {
1365            return;
1366        };
1367        let chat = compose.chat.clone();
1368        let Some(id) = self.pending_sends.get(&chat).cloned() else {
1369            self.notice = Notice::new(
1370                Tone::Error,
1371                "No correlation ID is available; inspect the chat before explicitly resending.",
1372            );
1373            return;
1374        };
1375        compose.stage = Stage::Checking;
1376        self.notice = Notice::new(Tone::Quiet, "Checking the original client message ID…");
1377        if let Some(backend) = self.backend() {
1378            let sender = self.outcomes.0.clone();
1379            tokio::spawn(async move {
1380                let result = backend.delivery(&chat, &id).await;
1381                let _ = sender.send(Outcome::Delivery { chat, id, result });
1382            });
1383        } else {
1384            let messages = self
1385                .threads
1386                .get(&chat)
1387                .map(|t| t.items.as_slice())
1388                .unwrap_or_default();
1389            let result = Ok(crate::delivery::reconcile(&chat, &id, messages));
1390            self.apply(Outcome::Delivery { chat, id, result });
1391        }
1392    }
1393
1394    fn restart_teams(&mut self) {
1395        let Some(backend) = self.backend() else {
1396            return;
1397        };
1398        self.debugging_restart = Some(DebuggingRestart::Running);
1399        self.notice = Notice::new(
1400            Tone::Quiet,
1401            "Restarting Teams and waiting for the connection…",
1402        );
1403        let sender = self.outcomes.0.clone();
1404        tokio::spawn(async move {
1405            if let TeamsBackend::Desktop(client) = backend.as_ref() {
1406                let _ = sender.send(Outcome::Restarted(client.restart_with_debugging().await));
1407            }
1408        });
1409    }
1410
1411    fn clear_flags(&mut self) {
1412        let Some(backend) = self.backend() else {
1413            return;
1414        };
1415        if let Some(cleanup) = &mut self.flag_cleanup {
1416            cleanup.stage = Cleanup::Running;
1417        }
1418        self.notice = Notice::new(Tone::Quiet, "Removing debugging flags…");
1419        let sender = self.outcomes.0.clone();
1420        tokio::spawn(async move {
1421            if let TeamsBackend::Desktop(client) = backend.as_ref() {
1422                let _ = sender.send(Outcome::FlagsCleared(client.clear_debugging_flags().await));
1423            }
1424        });
1425    }
1426
1427    fn handle_key(&mut self, key: KeyEvent) -> Action {
1428        let control = key.modifiers.contains(KeyModifiers::CONTROL);
1429        if control && key.code == KeyCode::Char('c') {
1430            return Action::Quit;
1431        }
1432        if self.startup_auth_error.is_some() {
1433            return match key.code {
1434                KeyCode::Enter | KeyCode::Char('a') => Action::Authenticate,
1435                KeyCode::Char('q') | KeyCode::Esc => Action::Quit,
1436                _ => Action::None,
1437            };
1438        }
1439        if let Some(restart) = self.debugging_restart {
1440            match (restart, key.code) {
1441                (_, KeyCode::Char('q')) => return Action::Quit,
1442                (DebuggingRestart::Offered, KeyCode::Enter) => {
1443                    self.debugging_restart = Some(DebuggingRestart::Confirming);
1444                }
1445                (DebuggingRestart::Confirming, KeyCode::Char('y')) => self.restart_teams(),
1446                (DebuggingRestart::Confirming, _) => {
1447                    self.debugging_restart = Some(DebuggingRestart::Offered);
1448                }
1449                (DebuggingRestart::Offered, KeyCode::Char('r')) => self.load_chats(false),
1450                (DebuggingRestart::Offered, KeyCode::Esc) => return Action::Quit,
1451                _ => {}
1452            }
1453            return Action::None;
1454        }
1455        if let Some(stage) = self.flag_cleanup.as_ref().map(|cleanup| cleanup.stage) {
1456            match (stage, key.code) {
1457                (_, KeyCode::Char('q')) => return Action::Quit,
1458                (Cleanup::Offered, KeyCode::Enter) => {
1459                    if let Some(cleanup) = &mut self.flag_cleanup {
1460                        cleanup.stage = Cleanup::Confirming;
1461                    }
1462                }
1463                (Cleanup::Confirming, KeyCode::Char('y')) => self.clear_flags(),
1464                (Cleanup::Confirming, _) => {
1465                    if let Some(cleanup) = &mut self.flag_cleanup {
1466                        cleanup.stage = Cleanup::Offered;
1467                    }
1468                }
1469                (Cleanup::Offered | Cleanup::Done, KeyCode::Char('r')) => self.load_chats(false),
1470                (Cleanup::Offered | Cleanup::Done, KeyCode::Esc) => return Action::Quit,
1471                _ => {}
1472            }
1473            return Action::None;
1474        }
1475        if self.compose.is_some() {
1476            self.compose_key(key);
1477            return Action::None;
1478        }
1479        match self.overlay {
1480            Some(Overlay::Help) => {
1481                if matches!(
1482                    key.code,
1483                    KeyCode::Char('?' | 'q') | KeyCode::Esc | KeyCode::Enter
1484                ) {
1485                    self.overlay = None;
1486                }
1487                return Action::None;
1488            }
1489            Some(Overlay::Filter) => {
1490                match key.code {
1491                    KeyCode::Esc => {
1492                        self.filter.clear();
1493                        self.overlay = None;
1494                        self.rebuild(None);
1495                    }
1496                    KeyCode::Enter => self.overlay = None,
1497                    KeyCode::Backspace => {
1498                        self.filter.pop();
1499                        self.rebuild(None);
1500                    }
1501                    KeyCode::Down => self.select(self.list.selected().map_or(0, |i| i + 1)),
1502                    KeyCode::Up => self.select(self.list.selected().unwrap_or(0).saturating_sub(1)),
1503                    KeyCode::Char(c) if !control => {
1504                        self.filter.push(c);
1505                        self.rebuild(None);
1506                    }
1507                    _ => {}
1508                }
1509                return Action::None;
1510            }
1511            None => {}
1512        }
1513        let half = (self.thread_height / 2).max(1);
1514        let in_thread = self.focus == Focus::Thread;
1515        match key.code {
1516            KeyCode::Char('q') => return Action::Quit,
1517            KeyCode::Char('?') => self.overlay = Some(Overlay::Help),
1518            KeyCode::Char('/') => {
1519                self.focus = Focus::Chats;
1520                self.overlay = Some(Overlay::Filter);
1521            }
1522            KeyCode::Char('r') => self.refresh(),
1523            KeyCode::Char('c') => self.open_compose(),
1524            KeyCode::Enter | KeyCode::Char('a') if self.sign_in_needed() => {
1525                return Action::Authenticate;
1526            }
1527            KeyCode::Tab | KeyCode::BackTab => {
1528                self.focus = if in_thread || self.selected_row().is_none() {
1529                    Focus::Chats
1530                } else {
1531                    Focus::Thread
1532                };
1533            }
1534            KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') => {
1535                if self.selected_row().is_some() {
1536                    self.focus = Focus::Thread;
1537                    self.open_selected();
1538                }
1539            }
1540            KeyCode::Esc | KeyCode::Left | KeyCode::Char('h') => {
1541                if in_thread {
1542                    self.focus = Focus::Chats;
1543                } else if !self.filter.is_empty() && key.code == KeyCode::Esc {
1544                    self.filter.clear();
1545                    self.rebuild(None);
1546                }
1547            }
1548            KeyCode::Char('d') if control => self.scroll = self.scroll.saturating_sub(half),
1549            KeyCode::Char('u') if control => self.scroll += half,
1550            KeyCode::PageDown => self.scroll = self.scroll.saturating_sub(half),
1551            KeyCode::PageUp => self.scroll += half,
1552            KeyCode::Down | KeyCode::Char('j') if in_thread => {
1553                self.scroll = self.scroll.saturating_sub(1)
1554            }
1555            KeyCode::Up | KeyCode::Char('k') if in_thread => self.scroll += 1,
1556            KeyCode::Down | KeyCode::Char('j') => {
1557                self.select(self.list.selected().map_or(0, |i| i + 1))
1558            }
1559            KeyCode::Up | KeyCode::Char('k') => {
1560                self.select(self.list.selected().unwrap_or(0).saturating_sub(1))
1561            }
1562            KeyCode::Home | KeyCode::Char('g') if in_thread => self.scroll = usize::MAX,
1563            KeyCode::End | KeyCode::Char('G') if in_thread => self.scroll = 0,
1564            KeyCode::Home | KeyCode::Char('g') => self.select(0),
1565            KeyCode::End | KeyCode::Char('G') => self.select(usize::MAX),
1566            KeyCode::Char('o') => self.load_older(true),
1567            _ => {}
1568        }
1569        Action::None
1570    }
1571
1572    /// Reads the page before the oldest loaded message; `announce` also says when
1573    /// there is none, which the wheel stays quiet about.
1574    fn load_older(&mut self, announce: bool) {
1575        let Some(id) = self.selected_row().map(|row| row.id.clone()) else {
1576            return;
1577        };
1578        match self.threads.get(&id) {
1579            Some(thread) if thread.loading_older => {}
1580            Some(thread) if thread.cursor.is_some() => {
1581                self.notice = Notice::new(Tone::Quiet, "Reading older messages…");
1582                self.load_messages(id, true);
1583            }
1584            _ if announce => {
1585                self.notice = Notice::new(Tone::Quiet, "No older messages to load.");
1586            }
1587            _ => {}
1588        }
1589    }
1590
1591    /// The wheel scrolls whichever pane is under the pointer, and a click picks a
1592    /// chat or focuses the conversation. The composer keeps its chat, so clicks on
1593    /// the ledger wait until it is closed.
1594    fn handle_mouse(&mut self, mouse: MouseEvent) {
1595        let over = |area: Option<Rect>| {
1596            area.is_some_and(|a| {
1597                a.contains(ratatui::layout::Position::new(mouse.column, mouse.row))
1598            })
1599        };
1600        if self.overlay == Some(Overlay::Help) {
1601            if matches!(mouse.kind, MouseEventKind::Down(_)) {
1602                self.overlay = None;
1603            }
1604            return;
1605        }
1606        let in_thread = over(self.thread_area);
1607        let in_ledger = over(self.ledger_area);
1608        match mouse.kind {
1609            MouseEventKind::ScrollUp if in_thread => {
1610                if self.scroll >= self.thread_overflow {
1611                    self.load_older(false);
1612                } else {
1613                    self.scroll = (self.scroll + WHEEL_LINES).min(self.thread_overflow);
1614                }
1615            }
1616            MouseEventKind::ScrollDown if in_thread => {
1617                self.scroll = self.scroll.saturating_sub(WHEEL_LINES);
1618            }
1619            MouseEventKind::ScrollUp if in_ledger && self.compose.is_none() => {
1620                self.select(self.list.selected().unwrap_or(0).saturating_sub(1));
1621            }
1622            MouseEventKind::ScrollDown if in_ledger && self.compose.is_none() => {
1623                self.select(self.list.selected().map_or(0, |i| i + 1));
1624            }
1625            MouseEventKind::Down(MouseButton::Left) if in_thread => {
1626                if self.selected_row().is_some() {
1627                    self.focus = Focus::Thread;
1628                }
1629            }
1630            MouseEventKind::Down(MouseButton::Left) if in_ledger && self.compose.is_none() => {
1631                let Some(area) = self.ledger_area else {
1632                    return;
1633                };
1634                let row = usize::from((mouse.row - area.y) / CHAT_ROW_HEIGHT);
1635                let index = self.list.offset() + row;
1636                if index < self.visible.len() {
1637                    self.select(index);
1638                    self.focus = Focus::Thread;
1639                    self.open_selected();
1640                }
1641            }
1642            _ => {}
1643        }
1644    }
1645
1646    fn draw(&mut self, frame: &mut ratatui::Frame<'_>) {
1647        let area = frame.area();
1648        let theme = self.theme;
1649        self.ledger_area = None;
1650        self.thread_area = None;
1651        frame.render_widget(Block::default().style(theme.canvas()), area);
1652        if area.width < MIN_WIDTH || area.height < MIN_HEIGHT {
1653            let message = Paragraph::new(vec![
1654                Line::styled("NEEDS MORE ROOM", theme.title()),
1655                Line::styled(
1656                    format!("Make the terminal at least {MIN_WIDTH}×{MIN_HEIGHT}."),
1657                    theme.muted(),
1658                ),
1659            ])
1660            .alignment(Alignment::Center)
1661            .wrap(Wrap { trim: true });
1662            frame.render_widget(message, centered(area, area.width, 2));
1663            return;
1664        }
1665        let [header, body, footer] = Layout::vertical([
1666            Constraint::Length(3),
1667            Constraint::Min(4),
1668            Constraint::Length(3),
1669        ])
1670        .areas(area);
1671        self.draw_header(frame, header);
1672        if let Some(restart) = self.debugging_restart {
1673            let (title, copy) = match restart {
1674                DebuggingRestart::Offered => (
1675                    "CONNECT TEAMS",
1676                    "Restart Teams with debugging enabled to read your chats.",
1677                ),
1678                DebuggingRestart::Confirming => (
1679                    "RESTART TEAMS?",
1680                    "This ends any call in progress. Restart now?",
1681                ),
1682                DebuggingRestart::Running => (
1683                    "RESTARTING TEAMS",
1684                    "Waiting for Teams to open its debugging port…",
1685                ),
1686            };
1687            state_panel(
1688                frame,
1689                body,
1690                theme,
1691                title,
1692                vec![
1693                    Line::styled(copy, theme.body()),
1694                    Line::styled(
1695                        "While enabled, programs running as you can read chats and send as you.",
1696                        theme.muted(),
1697                    ),
1698                ],
1699                theme.active_rule(),
1700            );
1701        } else if let Some(cleanup) = &self.flag_cleanup {
1702            let apps = cleanup.apps();
1703            let (title, copy) = match cleanup.stage {
1704                Cleanup::Offered => (
1705                    "DEBUGGING LEFT ON",
1706                    format!("{apps} holds the Teams port through a user-wide WebView2 debugging setting. Remove just those flags?"),
1707                ),
1708                Cleanup::Confirming => (
1709                    "REMOVE DEBUGGING FLAGS?",
1710                    "Edits the user-wide WebView2 arguments and keeps its other arguments. Remove now?".into(),
1711                ),
1712                Cleanup::Running => ("REMOVING FLAGS", "Updating the user-wide setting…".into()),
1713                Cleanup::Done => (
1714                    "FLAGS REMOVED",
1715                    format!("Quit {apps} completely and reopen, then press r."),
1716                ),
1717            };
1718            state_panel(
1719                frame,
1720                body,
1721                theme,
1722                title,
1723                vec![
1724                    Line::styled(copy, theme.body()),
1725                    Line::styled("Apps keep the port until fully quit.", theme.muted()),
1726                ],
1727                theme.active_rule(),
1728            );
1729        } else {
1730            match &self.chats_load {
1731                Load::Ready => {
1732                    if body.width >= SPLIT_WIDTH {
1733                        let ledger = (body.width * 38 / 100).clamp(34, 48);
1734                        let [left, right] =
1735                            Layout::horizontal([Constraint::Length(ledger), Constraint::Min(30)])
1736                                .areas(body);
1737                        self.draw_ledger(frame, left, true);
1738                        self.draw_thread(frame, right);
1739                    } else if self.focus == Focus::Thread {
1740                        self.draw_thread(frame, body);
1741                    } else {
1742                        self.draw_ledger(frame, body, false);
1743                    }
1744                }
1745                Load::Loading => state_panel(
1746                    frame,
1747                    body,
1748                    theme,
1749                    "READING CHATS",
1750                    vec![Line::styled(
1751                        format!("{}  Asking Teams for your recent chats", self.spinner()),
1752                        theme.muted(),
1753                    )],
1754                    theme.rule(),
1755                ),
1756                Load::Failed { message, auth } => {
1757                    let (title, lines) = failure_copy(theme, message, *auth);
1758                    state_panel(frame, body, theme, title, lines, theme.active_rule());
1759                }
1760            }
1761        }
1762        self.draw_footer(frame, footer);
1763        if self.overlay == Some(Overlay::Help) {
1764            self.draw_help(frame);
1765        }
1766    }
1767
1768    fn spinner(&self) -> &'static str {
1769        SPINNER[self.frame % SPINNER.len()]
1770    }
1771
1772    fn draw_header(&self, frame: &mut ratatui::Frame<'_>, area: Rect) {
1773        let theme = self.theme;
1774        let width = usize::from(area.width);
1775        let spans_width = |spans: &[Span]| spans.iter().map(Span::width).sum::<usize>();
1776        let separator = || Span::styled("  ·  ", theme.rule());
1777
1778        // Right: the send mode always shows, with a one-column margin like the left.
1779        let mut right = if self.can_send() {
1780            vec![Span::styled("✎ can send", theme.badge_send())]
1781        } else if self.sending_paused {
1782            vec![Span::styled("sending paused", theme.error())]
1783        } else {
1784            vec![Span::styled("read-only", theme.muted())]
1785        };
1786        right.push(Span::raw(" "));
1787        let brand = Span::styled(" TEAMS ", theme.brand());
1788        let fixed = brand.width() + 2 + spans_width(&right) + 2;
1789        let profile_width = self.profile().width();
1790        // Then freshness, as long as some of the profile name still fits beside it.
1791        if let Some(mut freshness) = self.freshness() {
1792            let needed = spans_width(&freshness) + 3;
1793            if fixed + needed + profile_width.min(10) <= width {
1794                freshness.push(Span::raw("   "));
1795                freshness.extend(right);
1796                right = freshness;
1797            }
1798        }
1799        let used = brand.width() + 2 + spans_width(&right) + 2;
1800        let mut left = vec![
1801            brand,
1802            Span::raw("  "),
1803            Span::styled(
1804                render::truncate(self.profile(), width.saturating_sub(used)),
1805                theme.title(),
1806            ),
1807        ];
1808        // Last, the signed-in account next to the profile when there is room.
1809        if let Some(account) = &self.account
1810            && used + profile_width + 5 + account.width() <= width
1811        {
1812            left.push(separator());
1813            left.push(Span::styled(account.clone(), theme.muted()));
1814        }
1815        let gap = width.saturating_sub(spans_width(&left) + spans_width(&right));
1816        let mut title = left;
1817        title.push(Span::raw(" ".repeat(gap)));
1818        title.extend(right);
1819
1820        let mut context = vec![Span::raw(" ")];
1821        for (index, part) in self.context().into_iter().enumerate() {
1822            let extra = if index == 0 { 0 } else { 5 };
1823            if spans_width(&context) + extra + spans_width(&part) + 1 > width {
1824                break;
1825            }
1826            if index > 0 {
1827                context.push(separator());
1828            }
1829            context.extend(part);
1830        }
1831        let header = Paragraph::new(vec![Line::from(title), Line::from(context)]).block(
1832            Block::default()
1833                .borders(Borders::BOTTOM)
1834                .border_style(theme.rule()),
1835        );
1836        frame.render_widget(header, area);
1837    }
1838
1839    fn draw_ledger(&mut self, frame: &mut ratatui::Frame<'_>, area: Rect, split: bool) {
1840        let theme = self.theme;
1841        let active = self.focus == Focus::Chats || !split;
1842        let block = Block::default()
1843            .borders(if split { Borders::RIGHT } else { Borders::NONE })
1844            .border_style(if active {
1845                theme.active_rule()
1846            } else {
1847                theme.rule()
1848            });
1849        let inner = block.inner(area);
1850        frame.render_widget(block, area);
1851        let [heading, list_area] =
1852            Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).areas(inner);
1853        let label = if self.filter.is_empty() {
1854            " RECENT".to_string()
1855        } else {
1856            format!(" MATCHING “{}”", self.filter)
1857        };
1858        let count = format!("{} ", self.visible.len());
1859        let gap = usize::from(heading.width).saturating_sub(label.width() + count.width());
1860        frame.render_widget(
1861            Paragraph::new(Line::from(vec![
1862                Span::styled(label, theme.column_header()),
1863                Span::styled(" ".repeat(gap), theme.column_header()),
1864                Span::styled(count, theme.column_header()),
1865            ])),
1866            heading,
1867        );
1868        if self.visible.is_empty() {
1869            let text = if self.filter.is_empty() {
1870                vec![
1871                    Line::styled("No chats yet", theme.title()),
1872                    Line::styled("Teams has nothing cached for this profile.", theme.muted()),
1873                ]
1874            } else {
1875                vec![
1876                    Line::styled("Nothing matches", theme.title()),
1877                    Line::styled("esc clears the filter", theme.muted()),
1878                ]
1879            };
1880            frame.render_widget(
1881                Paragraph::new(text)
1882                    .alignment(Alignment::Center)
1883                    .wrap(Wrap { trim: true }),
1884                centered(list_area, list_area.width, 2),
1885            );
1886            return;
1887        }
1888        let width = usize::from(list_area.width);
1889        let selected = self.list.selected();
1890        let mut items: Vec<ListItem> = self
1891            .visible
1892            .iter()
1893            .enumerate()
1894            .map(|(position, &i)| {
1895                chat_item(
1896                    &self.rows[i],
1897                    width,
1898                    selected == Some(position),
1899                    active,
1900                    theme,
1901                )
1902            })
1903            .collect();
1904        if self.chat_cursor.is_some() {
1905            items.push(ListItem::new(Line::styled(
1906                if self.loading_more {
1907                    format!("   {} reading more chats", self.spinner())
1908                } else {
1909                    "   more chats load as you reach the end".into()
1910                },
1911                theme.muted(),
1912            )));
1913        }
1914        frame.render_stateful_widget(List::new(items), list_area, &mut self.list);
1915        self.ledger_area = Some(list_area);
1916    }
1917
1918    fn draw_thread(&mut self, frame: &mut ratatui::Frame<'_>, area: Rect) {
1919        let theme = self.theme;
1920        self.thread_area = Some(area);
1921        self.thread_overflow = 0;
1922        let area = Rect {
1923            x: area.x + 2,
1924            width: area.width.saturating_sub(3),
1925            ..area
1926        };
1927        let Some(row) = self.selected_row() else {
1928            frame.render_widget(
1929                Paragraph::new(vec![
1930                    Line::styled("No chat selected", theme.title()),
1931                    Line::styled("Pick a chat on the left to read it here.", theme.muted()),
1932                ])
1933                .alignment(Alignment::Center),
1934                centered(area, area.width, 2),
1935            );
1936            return;
1937        };
1938        let [heading, body] =
1939            Layout::vertical([Constraint::Length(3), Constraint::Min(1)]).areas(area);
1940        let width = usize::from(heading.width);
1941        let kind = match (row.kind, row.members) {
1942            (Some(kind), n) if n > 0 => format!("{kind} chat  ·  {n} people"),
1943            (Some(kind), _) => format!("{kind} chat"),
1944            (None, _) => "one-to-one chat".into(),
1945        };
1946        let mut meta = vec![Span::styled(kind, theme.muted())];
1947        if self.scroll > 0 {
1948            meta.push(Span::styled("  ·  ", theme.muted()));
1949            meta.push(Span::styled("G", theme.key()));
1950            meta.push(Span::styled(" newest", theme.muted()));
1951        }
1952        frame.render_widget(
1953            Paragraph::new(vec![
1954                Line::styled(render::truncate(&row.title, width), theme.detail_title()),
1955                Line::from(meta),
1956            ])
1957            .block(Block::default().borders(Borders::BOTTOM).border_style(
1958                if self.focus == Focus::Thread {
1959                    theme.active_rule()
1960                } else {
1961                    theme.rule()
1962                },
1963            )),
1964            heading,
1965        );
1966        let mut body = Rect {
1967            y: body.y + 1,
1968            height: body.height.saturating_sub(1),
1969            ..body
1970        };
1971        if let Some(compose) = self.compose.as_ref().filter(|c| c.chat == row.id) {
1972            let (rows, (line, column)) =
1973                layout_draft(&compose.text, compose.cursor, usize::from(body.width));
1974            let shown = rows.len().min(COMPOSE_ROWS);
1975            let [conversation, editor] =
1976                Layout::vertical([Constraint::Min(1), Constraint::Length(shown as u16 + 1)])
1977                    .areas(body);
1978            body = conversation;
1979            let title = match compose.stage {
1980                Stage::Editing => " MESSAGE ",
1981                Stage::Sending => " SENDING ",
1982                Stage::Unconfirmed => " POSSIBLY SENT ",
1983                Stage::Checking => " CHECKING DELIVERY ",
1984                Stage::ConfirmResend => " RESEND? ",
1985            };
1986            let block = Block::default()
1987                .borders(Borders::TOP)
1988                .border_style(theme.active_rule())
1989                .title(Span::styled(title, theme.column_header()));
1990            let inner = block.inner(editor);
1991            frame.render_widget(block, editor);
1992            let start = (line + 1).saturating_sub(COMPOSE_ROWS);
1993            let lines: Vec<Line> = if compose.text.is_empty() {
1994                vec![Line::styled("Write a message…", theme.muted())]
1995            } else {
1996                rows.into_iter()
1997                    .skip(start)
1998                    .take(COMPOSE_ROWS)
1999                    .map(|row| Line::styled(row, theme.body()))
2000                    .collect()
2001            };
2002            frame.render_widget(Paragraph::new(lines), inner);
2003            if compose.stage == Stage::Editing {
2004                let x = inner.x + (column as u16).min(inner.width.saturating_sub(1));
2005                frame.set_cursor_position((x, inner.y + (line - start) as u16));
2006            }
2007        }
2008        let id = row.id.clone();
2009        self.thread_height = usize::from(body.height);
2010        let Some(thread) = self.threads.get(&id) else {
2011            frame.render_widget(
2012                Paragraph::new(Line::styled("…", theme.muted())).alignment(Alignment::Center),
2013                centered(body, body.width, 1),
2014            );
2015            return;
2016        };
2017        match &thread.load {
2018            Load::Loading => {
2019                frame.render_widget(
2020                    Paragraph::new(Line::styled(
2021                        format!("{}  Reading messages", self.spinner()),
2022                        theme.muted(),
2023                    ))
2024                    .alignment(Alignment::Center),
2025                    centered(body, body.width, 1),
2026                );
2027                return;
2028            }
2029            Load::Failed { message, auth } => {
2030                let (title, lines) = failure_copy(theme, message, *auth);
2031                let mut text = vec![Line::styled(title, theme.error()), Line::raw("")];
2032                text.extend(lines);
2033                frame.render_widget(
2034                    Paragraph::new(text)
2035                        .alignment(Alignment::Center)
2036                        .wrap(Wrap { trim: true }),
2037                    centered(body, body.width, 6),
2038                );
2039                return;
2040            }
2041            Load::Ready => {}
2042        }
2043        let mut entries = render::conversation(&thread.items, &self.view(), self.viewer.as_deref());
2044        // The chat list can carry a latest message whose history was never read.
2045        let mut missing = false;
2046        if entries.is_empty()
2047            && thread.cursor.is_none()
2048            && let Some(chat) = self.chats.iter().find(|chat| chat["id"] == id.as_str())
2049            && chat["lastMessagePreview"].is_object()
2050        {
2051            entries = render::conversation(
2052                std::slice::from_ref(&chat["lastMessagePreview"]),
2053                &self.view(),
2054                self.viewer.as_deref(),
2055            );
2056            missing = !entries.is_empty();
2057        }
2058        let mut lines = Vec::new();
2059        if thread.loading_older {
2060            lines.push(
2061                Line::styled(
2062                    format!("{}  reading older messages", self.spinner()),
2063                    theme.muted(),
2064                )
2065                .alignment(Alignment::Center),
2066            );
2067        } else if thread.cursor.is_some() {
2068            lines.push(
2069                Line::from(vec![
2070                    Span::styled("older messages  ·  ", theme.muted()),
2071                    Span::styled("o", theme.key()),
2072                    Span::styled(" load", theme.muted()),
2073                ])
2074                .alignment(Alignment::Center),
2075            );
2076        }
2077        if missing {
2078            lines.push(Line::raw(""));
2079            for note in render::wrap(self.missing_history_note(), usize::from(body.width)) {
2080                lines.push(Line::styled(note, theme.muted()).centered());
2081            }
2082        } else if entries.is_empty() {
2083            lines.push(Line::raw(""));
2084            lines.push(Line::styled("No messages in this chat yet.", theme.muted()).centered());
2085        }
2086        lines.extend(conversation_lines(&entries, usize::from(body.width), theme));
2087        let height = usize::from(body.height);
2088        let overflow = lines.len().saturating_sub(height);
2089        self.thread_overflow = overflow;
2090        self.scroll = self.scroll.min(overflow);
2091        let start = overflow - self.scroll;
2092        let mut shown: Vec<Line> = lines.into_iter().skip(start).take(height).collect();
2093        // Short conversations sit at the bottom, next to where new messages arrive.
2094        let pad = height.saturating_sub(shown.len());
2095        shown.splice(0..0, std::iter::repeat_n(Line::raw(""), pad));
2096        frame.render_widget(Paragraph::new(shown), body);
2097    }
2098
2099    fn draw_footer(&self, frame: &mut ratatui::Frame<'_>, area: Rect) {
2100        let theme = self.theme;
2101        let block = Block::default()
2102            .borders(Borders::TOP)
2103            .border_style(theme.rule());
2104        let inner = block.inner(area);
2105        frame.render_widget(block, area);
2106        let [status, keys] =
2107            Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(inner);
2108        if self.overlay == Some(Overlay::Filter) {
2109            let prompt = Line::from(vec![
2110                Span::styled("› filter ", theme.key()),
2111                Span::styled(self.filter.clone(), theme.body()),
2112            ]);
2113            frame.render_widget(Paragraph::new(prompt), status);
2114            let x = status.x + 9 + self.filter.width() as u16;
2115            frame.set_cursor_position((x.min(status.right().saturating_sub(1)), status.y));
2116        } else {
2117            let style = match self.notice.tone {
2118                Tone::Quiet => theme.muted(),
2119                Tone::Success => theme.success(),
2120                Tone::Error => theme.error(),
2121            };
2122            frame.render_widget(
2123                Paragraph::new(Line::styled(
2124                    render::truncate(&self.notice.text, usize::from(status.width)),
2125                    style,
2126                )),
2127                status,
2128            );
2129        }
2130        frame.render_widget(Paragraph::new(self.hints(usize::from(keys.width))), keys);
2131    }
2132
2133    /// Key hints for the current context, dropping the least important ones
2134    /// first when the terminal is narrow. Lower rank means more important.
2135    fn hints(&self, width: usize) -> Line<'static> {
2136        let mut all: Vec<(&str, &str, u8)> = if let Some(restart) = self.debugging_restart {
2137            match restart {
2138                DebuggingRestart::Offered => vec![
2139                    ("enter", "restart Teams", 0),
2140                    ("r", "retry", 1),
2141                    ("q", "quit", 0),
2142                ],
2143                DebuggingRestart::Confirming => vec![
2144                    ("y", "restart Teams", 0),
2145                    ("esc", "cancel", 0),
2146                    ("q", "quit", 1),
2147                ],
2148                DebuggingRestart::Running => vec![("q", "quit", 0)],
2149            }
2150        } else if let Some(cleanup) = &self.flag_cleanup {
2151            match cleanup.stage {
2152                Cleanup::Offered => vec![
2153                    ("enter", "remove flags", 0),
2154                    ("r", "retry", 1),
2155                    ("q", "quit", 0),
2156                ],
2157                Cleanup::Confirming => vec![
2158                    ("y", "remove flags", 0),
2159                    ("esc", "cancel", 0),
2160                    ("q", "quit", 1),
2161                ],
2162                Cleanup::Running => vec![("q", "quit", 0)],
2163                Cleanup::Done => vec![("r", "retry", 0), ("q", "quit", 0)],
2164            }
2165        } else if let Some(compose) = &self.compose {
2166            match compose.stage {
2167                Stage::Editing => vec![
2168                    ("enter", "send", 0),
2169                    ("ctrl-j", "new line", 1),
2170                    ("esc", "close, keep draft", 0),
2171                ],
2172                Stage::Sending | Stage::Checking => vec![("ctrl-c", "quit", 1)],
2173                Stage::Unconfirmed => vec![
2174                    ("r", "check", 0),
2175                    ("s", "resend…", 0),
2176                    ("esc", "keep draft", 1),
2177                ],
2178                Stage::ConfirmResend => vec![("y", "send second copy", 0), ("esc", "cancel", 0)],
2179            }
2180        } else if self.overlay == Some(Overlay::Filter) {
2181            vec![("enter", "keep", 0), ("esc", "clear", 0), ("↑↓", "move", 1)]
2182        } else if self.sign_in_needed() {
2183            vec![
2184                ("enter / a", "sign in", 0),
2185                ("r", "retry", 1),
2186                ("q", "quit", 0),
2187            ]
2188        } else if self.focus == Focus::Thread {
2189            vec![
2190                ("↑↓", "scroll", 1),
2191                ("pgup/pgdn", "page", 2),
2192                ("o", "older", 1),
2193                ("esc", "chats", 0),
2194                ("r", "refresh", 2),
2195                ("?", "help", 1),
2196                ("q", "quit", 0),
2197            ]
2198        } else {
2199            vec![
2200                ("↑↓", "move", 1),
2201                ("enter", "read", 0),
2202                ("/", "filter", 1),
2203                ("tab", "switch pane", 3),
2204                ("r", "refresh", 2),
2205                ("?", "help", 1),
2206                ("q", "quit", 0),
2207            ]
2208        };
2209        if self.debugging_restart.is_none()
2210            && self.flag_cleanup.is_none()
2211            && self.compose.is_none()
2212            && self.overlay.is_none()
2213            && !self.sign_in_needed()
2214            && self.can_send()
2215        {
2216            let rank = if self.focus == Focus::Thread { 0 } else { 2 };
2217            all.insert(all.len() - 3, ("c", "reply", rank));
2218        }
2219        let mut chosen = vec![false; all.len()];
2220        let mut used = 0;
2221        for rank in 0..=3 {
2222            for (i, (key, description, r)) in all.iter().enumerate() {
2223                let need = key.width() + 1 + description.width() + 3;
2224                if *r == rank && used + need <= width {
2225                    chosen[i] = true;
2226                    used += need;
2227                }
2228            }
2229        }
2230        let mut spans = Vec::new();
2231        for (i, (key, description, _)) in all.into_iter().enumerate() {
2232            if chosen[i] {
2233                if !spans.is_empty() {
2234                    spans.push(Span::raw("   "));
2235                }
2236                spans.push(Span::styled(key.to_string(), self.theme.key()));
2237                spans.push(Span::styled(format!(" {description}"), self.theme.muted()));
2238            }
2239        }
2240        Line::from(spans)
2241    }
2242
2243    fn draw_help(&self, frame: &mut ratatui::Frame<'_>) {
2244        let theme = self.theme;
2245        let rows = [
2246            (
2247                "↑ / k, ↓ / j",
2248                "Move through chats, or scroll a conversation",
2249            ),
2250            ("enter / → / l", "Read the selected chat"),
2251            ("esc / ← / h", "Back to the chat list"),
2252            ("tab", "Switch between the list and the conversation"),
2253            ("pgup / pgdn", "Scroll the conversation by half a screen"),
2254            ("g / G", "First / last chat, or oldest / newest message"),
2255            ("o", "Load older messages in this chat"),
2256            (
2257                "wheel",
2258                "Scroll the pane under the pointer; older messages load at the top",
2259            ),
2260            ("click", "Open a chat, or focus the conversation"),
2261            (
2262                "shift-drag",
2263                "Select text to copy, while the mouse is in use here",
2264            ),
2265            ("/", "Filter chats by name or last message"),
2266            ("c", "Write a message in the open chat"),
2267            ("r", "Refresh now; chats also refresh on their own"),
2268            ("enter / a", "Sign in when the session needs attention"),
2269            ("q / ctrl-c", "Return to the shell"),
2270        ];
2271        let mut lines = vec![
2272            Line::styled(
2273                "Read your Teams chats without leaving the terminal",
2274                theme.muted(),
2275            ),
2276            Line::raw(""),
2277        ];
2278        for (key, description) in rows {
2279            lines.push(Line::from(vec![
2280                Span::styled(format!("{key:<16}"), theme.key()),
2281                Span::styled(description, theme.body()),
2282            ]));
2283        }
2284        lines.push(Line::raw(""));
2285        lines.push(Line::styled(
2286            if self.can_send() {
2287                "Enter sends · Ctrl-J adds a line · Esc keeps your draft."
2288            } else {
2289                "Read-only: nothing here sends, edits or marks messages as read."
2290            },
2291            theme.success(),
2292        ));
2293        let height = lines.len() as u16 + 2;
2294        let area = centered(frame.area(), 70, height);
2295        frame.render_widget(Clear, area);
2296        frame.render_widget(
2297            Paragraph::new(lines).wrap(Wrap { trim: false }).block(
2298                Block::default()
2299                    .title(" KEYBOARD MAP  ·  ? OR ESC TO CLOSE ")
2300                    .title_style(theme.title())
2301                    .borders(Borders::ALL)
2302                    .border_style(theme.active_rule())
2303                    .padding(Padding::horizontal(1))
2304                    .style(theme.canvas()),
2305            ),
2306            area,
2307        );
2308    }
2309}
2310
2311fn chat_item(
2312    row: &ChatRow,
2313    width: usize,
2314    selected: bool,
2315    active: bool,
2316    theme: Theme,
2317) -> ListItem<'static> {
2318    let marker = if selected {
2319        Span::styled(
2320            "▌",
2321            if active {
2322                theme.active_rule()
2323            } else {
2324                theme.muted()
2325            },
2326        )
2327    } else {
2328        Span::raw(" ")
2329    };
2330    let dot = if row.unread {
2331        Span::styled("● ", theme.unread())
2332    } else {
2333        Span::raw("  ")
2334    };
2335    let kind = row
2336        .kind
2337        .map(|kind| format!(" · {kind}"))
2338        .unwrap_or_default();
2339    let time = format!("{} ", row.time);
2340    let room = width.saturating_sub(4 + time.width() + 1);
2341    // The kind is a hint; when space is short the name wins.
2342    let kind = if row.title.width() + kind.width() <= room {
2343        kind
2344    } else {
2345        String::new()
2346    };
2347    let title = render::truncate(&row.title, room);
2348    let gap = width.saturating_sub(4 + title.width() + kind.width() + time.width());
2349    let title_style = if selected && active {
2350        theme.accent()
2351    } else if row.unread {
2352        theme.title()
2353    } else {
2354        theme.body()
2355    };
2356    let first = Line::from(vec![
2357        marker.clone(),
2358        Span::raw(" "),
2359        dot,
2360        Span::styled(title, title_style),
2361        Span::styled(kind, theme.muted()),
2362        Span::raw(" ".repeat(gap)),
2363        Span::styled(
2364            time,
2365            if row.unread {
2366                theme.unread()
2367            } else {
2368                theme.muted()
2369            },
2370        ),
2371    ]);
2372    let preview = row.preview.as_deref().unwrap_or("");
2373    let second = Line::from(vec![
2374        marker,
2375        Span::raw("   "),
2376        Span::styled(
2377            render::truncate(preview, width.saturating_sub(5)),
2378            if row.unread {
2379                theme.body()
2380            } else {
2381                theme.muted()
2382            },
2383        ),
2384    ]);
2385    let item = ListItem::new(vec![first, second, Line::raw("")]);
2386    if selected {
2387        item.style(theme.selection())
2388    } else {
2389        item
2390    }
2391}
2392
2393/// Wraps a draft to `width` columns, honouring line breaks, and finds the row and
2394/// column of the byte offset `cursor`.
2395fn layout_draft(text: &str, cursor: usize, width: usize) -> (Vec<String>, (usize, usize)) {
2396    let width = width.max(1);
2397    let mut rows = vec![String::new()];
2398    let mut column = 0;
2399    let mut at = None;
2400    for (i, c) in text.char_indices() {
2401        if c == '\n' {
2402            if i == cursor {
2403                at = Some((rows.len() - 1, column));
2404            }
2405            rows.push(String::new());
2406            column = 0;
2407            continue;
2408        }
2409        let w = c.width().unwrap_or(0);
2410        if column + w > width {
2411            rows.push(String::new());
2412            column = 0;
2413        }
2414        if i == cursor {
2415            at = Some((rows.len() - 1, column));
2416        }
2417        rows.last_mut().expect("never empty").push(c);
2418        column += w;
2419    }
2420    let at = at.unwrap_or((rows.len() - 1, column));
2421    (rows, at)
2422}
2423
2424/// Puts a fresh first page ahead of what was loaded before. Older pages are kept, with
2425/// their cursor, only when the fresh page overlaps them, so a burst of new items never
2426/// leaves a silent gap.
2427fn merge_newest(
2428    fresh: Vec<Value>,
2429    cursor: Option<String>,
2430    old: Vec<Value>,
2431    old_cursor: Option<String>,
2432) -> (Vec<Value>, Option<String>) {
2433    let ids: HashSet<&str> = fresh.iter().filter_map(|v| v["id"].as_str()).collect();
2434    let overlaps = old
2435        .iter()
2436        .any(|v| v["id"].as_str().is_some_and(|id| ids.contains(id)));
2437    if cursor.is_none() || !overlaps {
2438        return (fresh, cursor);
2439    }
2440    let rest: Vec<Value> = old
2441        .into_iter()
2442        .filter(|v| !v["id"].as_str().is_some_and(|id| ids.contains(id)))
2443        .collect();
2444    let cursor = if rest.is_empty() { cursor } else { old_cursor };
2445    let mut items = fresh;
2446    items.extend(rest);
2447    (items, cursor)
2448}
2449
2450/// Lays a conversation out for a pane: centred day rules, coloured senders,
2451/// indented and wrapped bodies, quotes dimmed.
2452fn conversation_lines(entries: &[Entry], width: usize, theme: Theme) -> Vec<Line<'static>> {
2453    let mut lines: Vec<Line> = Vec::new();
2454    let mut after_day = false;
2455    for entry in entries {
2456        match entry {
2457            Entry::Day(day) => {
2458                if !lines.is_empty() {
2459                    lines.push(Line::raw(""));
2460                }
2461                let label = format!(" {day} ");
2462                let side = width.saturating_sub(label.width()) / 2;
2463                let rest = width.saturating_sub(label.width() + side);
2464                lines.push(
2465                    Line::from(vec![
2466                        Span::styled("─".repeat(side.min(24)), theme.rule()),
2467                        Span::styled(label, theme.muted()),
2468                        Span::styled("─".repeat(rest.min(24)), theme.rule()),
2469                    ])
2470                    .centered(),
2471                );
2472                after_day = true;
2473            }
2474            Entry::Sender { name, time, own } => {
2475                if !after_day {
2476                    lines.push(Line::raw(""));
2477                }
2478                after_day = false;
2479                let mut spans = vec![Span::styled(
2480                    render::truncate(name, width.saturating_sub(8)),
2481                    theme.sender(name, *own),
2482                )];
2483                if let Some(time) = time {
2484                    spans.push(Span::styled(format!("  {time}"), theme.muted()));
2485                }
2486                lines.push(Line::from(spans));
2487            }
2488            Entry::Text(text) if text.is_empty() => lines.push(Line::raw("")),
2489            Entry::Text(text) => {
2490                let style = if text.starts_with('>') {
2491                    theme.quote()
2492                } else {
2493                    theme.body()
2494                };
2495                lines.extend(
2496                    render::wrap(text, width.saturating_sub(2))
2497                        .into_iter()
2498                        .map(|line| Line::from(vec![Span::raw("  "), Span::styled(line, style)])),
2499                );
2500            }
2501        }
2502    }
2503    lines
2504}
2505
2506fn failure_copy(theme: Theme, message: &str, auth: bool) -> (&'static str, Vec<Line<'static>>) {
2507    if auth {
2508        (
2509            "SIGN-IN REQUIRED",
2510            vec![
2511                Line::styled("Your Teams session needs attention.", theme.body()),
2512                Line::styled(message.to_string(), theme.muted()),
2513                Line::raw(""),
2514                Line::from(vec![
2515                    Span::styled("enter / a", theme.key()),
2516                    Span::styled("  sign in   ", theme.muted()),
2517                    Span::styled("q", theme.key()),
2518                    Span::styled("  quit", theme.muted()),
2519                ]),
2520            ],
2521        )
2522    } else {
2523        (
2524            "COULD NOT READ TEAMS",
2525            vec![
2526                Line::styled(message.to_string(), theme.body()),
2527                Line::raw(""),
2528                Line::from(vec![
2529                    Span::styled("r", theme.key()),
2530                    Span::styled("  try again   ", theme.muted()),
2531                    Span::styled("q", theme.key()),
2532                    Span::styled("  quit", theme.muted()),
2533                ]),
2534            ],
2535        )
2536    }
2537}
2538
2539fn state_panel(
2540    frame: &mut ratatui::Frame<'_>,
2541    area: Rect,
2542    theme: Theme,
2543    title: &str,
2544    lines: Vec<Line<'static>>,
2545    border: Style,
2546) {
2547    let width = area.width.saturating_sub(4).min(72);
2548    let room = usize::from(width.saturating_sub(4)).max(1);
2549    let rows: usize = lines
2550        .iter()
2551        .map(|line| line.width().div_ceil(room).max(1))
2552        .sum();
2553    let panel = centered(area, width, rows as u16 + 4);
2554    frame.render_widget(
2555        Paragraph::new(lines)
2556            .alignment(Alignment::Center)
2557            .wrap(Wrap { trim: true })
2558            .block(
2559                Block::default()
2560                    .title(format!(" {title} "))
2561                    .title_style(theme.title())
2562                    .borders(Borders::ALL)
2563                    .border_style(border)
2564                    .padding(Padding::uniform(1)),
2565            ),
2566        panel,
2567    );
2568}
2569
2570fn centered(area: Rect, width: u16, height: u16) -> Rect {
2571    let width = width.min(area.width);
2572    let height = height.min(area.height);
2573    Rect {
2574        x: area.x + (area.width - width) / 2,
2575        y: area.y + (area.height - height) / 2,
2576        width,
2577        height,
2578    }
2579}
2580
2581/// A Teams-like indigo palette. Every style collapses to the terminal
2582/// default when colour is off, so structure carries the meaning.
2583#[derive(Clone, Copy)]
2584struct Theme {
2585    color: bool,
2586}
2587
2588impl Theme {
2589    fn style(self, foreground: Color, background: Color) -> Style {
2590        if self.color {
2591            Style::default().fg(foreground).bg(background)
2592        } else {
2593            Style::default()
2594        }
2595    }
2596
2597    /// Text colour only: the cell keeps the canvas, selection or header behind it. A
2598    /// `Color::Reset` background here would show the terminal's own colour through the text.
2599    fn fg(self, foreground: Color) -> Style {
2600        if self.color {
2601            Style::default().fg(foreground)
2602        } else {
2603            Style::default()
2604        }
2605    }
2606
2607    fn canvas(self) -> Style {
2608        self.style(Color::Rgb(222, 225, 240), Color::Rgb(15, 16, 28))
2609    }
2610
2611    fn body(self) -> Style {
2612        self.fg(Color::Rgb(222, 225, 240))
2613    }
2614
2615    fn muted(self) -> Style {
2616        self.fg(Color::Rgb(128, 134, 168))
2617    }
2618
2619    fn quote(self) -> Style {
2620        self.muted().add_modifier(Modifier::ITALIC)
2621    }
2622
2623    fn brand(self) -> Style {
2624        self.style(Color::Rgb(15, 16, 28), Color::Rgb(123, 131, 235))
2625            .add_modifier(Modifier::BOLD)
2626    }
2627
2628    fn title(self) -> Style {
2629        self.fg(Color::Rgb(242, 243, 252))
2630            .add_modifier(Modifier::BOLD)
2631    }
2632
2633    fn detail_title(self) -> Style {
2634        self.fg(Color::Rgb(170, 177, 255))
2635            .add_modifier(Modifier::BOLD)
2636    }
2637
2638    fn accent(self) -> Style {
2639        self.fg(Color::Rgb(155, 162, 255))
2640            .add_modifier(Modifier::BOLD)
2641    }
2642
2643    fn column_header(self) -> Style {
2644        self.style(Color::Rgb(150, 156, 190), Color::Rgb(24, 26, 44))
2645            .add_modifier(Modifier::BOLD)
2646    }
2647
2648    fn key(self) -> Style {
2649        self.fg(Color::Rgb(246, 183, 82))
2650            .add_modifier(Modifier::BOLD)
2651    }
2652
2653    fn rule(self) -> Style {
2654        self.fg(Color::Rgb(50, 54, 86))
2655    }
2656
2657    fn active_rule(self) -> Style {
2658        self.fg(Color::Rgb(123, 131, 235))
2659    }
2660
2661    fn selection(self) -> Style {
2662        if self.color {
2663            Style::default().bg(Color::Rgb(30, 33, 60))
2664        } else {
2665            Style::default().add_modifier(Modifier::BOLD)
2666        }
2667    }
2668
2669    fn unread(self) -> Style {
2670        self.fg(Color::Rgb(255, 128, 112))
2671            .add_modifier(Modifier::BOLD)
2672    }
2673
2674    fn success(self) -> Style {
2675        self.fg(Color::Rgb(110, 220, 170))
2676    }
2677
2678    /// Writing is possible on this profile: warm, so it is noticed without alarm.
2679    fn badge_send(self) -> Style {
2680        self.fg(Color::Rgb(246, 183, 82))
2681            .add_modifier(Modifier::BOLD)
2682    }
2683
2684    /// A number worth scanning for in otherwise quiet text.
2685    fn figure(self) -> Style {
2686        self.body().add_modifier(Modifier::BOLD)
2687    }
2688
2689    fn unread_label(self) -> Style {
2690        self.fg(Color::Rgb(255, 128, 112))
2691    }
2692
2693    fn error(self) -> Style {
2694        self.fg(Color::Rgb(255, 126, 119))
2695            .add_modifier(Modifier::BOLD)
2696    }
2697
2698    /// The same person always gets the same colour; you get the accent.
2699    fn sender(self, name: &str, own: bool) -> Style {
2700        const PALETTE: [Color; 6] = [
2701            Color::Rgb(122, 200, 255),
2702            Color::Rgb(240, 160, 220),
2703            Color::Rgb(130, 220, 160),
2704            Color::Rgb(250, 200, 110),
2705            Color::Rgb(190, 160, 255),
2706            Color::Rgb(110, 215, 210),
2707        ];
2708        let color = if own {
2709            Color::Rgb(155, 162, 255)
2710        } else {
2711            let hash = name.bytes().fold(0usize, |h, b| {
2712                h.wrapping_mul(31).wrapping_add(usize::from(b))
2713            });
2714            PALETTE[hash % PALETTE.len()]
2715        };
2716        self.fg(color).add_modifier(Modifier::BOLD)
2717    }
2718}
2719
2720fn demo_time(now: &Zoned, minutes_ago: i64) -> String {
2721    now.checked_sub(minutes_ago.minutes())
2722        .unwrap_or_else(|_| now.clone())
2723        .timestamp()
2724        .to_string()
2725}
2726
2727const DEMO_PEOPLE: [(&str, &str); 7] = [
2728    ("me", "Alex Morgan"),
2729    ("mina", "Mina Okafor"),
2730    ("jon", "Jon Bakker"),
2731    ("ari", "Ari Chen"),
2732    ("priya", "Priya Raman"),
2733    ("sam", "Sam Rivera"),
2734    ("lee", "Lee Novak"),
2735];
2736
2737fn demo_person(id: &str) -> Value {
2738    let name = DEMO_PEOPLE
2739        .iter()
2740        .find(|(person, _)| *person == id)
2741        .map_or(id, |(_, name)| name);
2742    json!({"id": id, "displayName": name})
2743}
2744
2745/// (id, topic, type, members, unread) for each sample chat.
2746type DemoChat = (
2747    &'static str,
2748    Option<&'static str>,
2749    &'static str,
2750    &'static [&'static str],
2751    bool,
2752);
2753
2754const DEMO_CHATS: [DemoChat; 6] = [
2755    (
2756        "19:launch@thread.v2",
2757        Some("Launch room"),
2758        "group",
2759        &["me", "mina", "jon", "priya"],
2760        true,
2761    ),
2762    (
2763        "19:ari@unq.gbl.spaces",
2764        None,
2765        "oneOnOne",
2766        &["me", "ari"],
2767        true,
2768    ),
2769    (
2770        "19:design@thread.v2",
2771        Some("Design crit"),
2772        "group",
2773        &["me", "lee", "ari"],
2774        false,
2775    ),
2776    (
2777        "19:oncall@thread.v2",
2778        Some("Platform on-call"),
2779        "group",
2780        &["me", "priya", "jon", "sam", "lee"],
2781        false,
2782    ),
2783    (
2784        "19:weekly@thread.v2",
2785        Some("Weekly sync"),
2786        "meeting",
2787        &["me", "mina", "jon", "ari"],
2788        false,
2789    ),
2790    (
2791        "19:sam@unq.gbl.spaces",
2792        None,
2793        "oneOnOne",
2794        &["me", "sam"],
2795        false,
2796    ),
2797];
2798
2799/// (minutes ago, sender, html) per sample chat, newest last.
2800fn demo_script(chat: &str) -> &'static [(i64, &'static str, &'static str)] {
2801    match chat {
2802        "19:launch@thread.v2" => &[
2803            (
2804                1460,
2805                "priya",
2806                "<p>Staging is frozen for the launch. Ping me before any deploy.</p>",
2807            ),
2808            (1452, "me", "<p>Noted, thanks <at>Priya</at>.</p>"),
2809            (
2810                43,
2811                "jon",
2812                "<p>Docs are ready. One broken link remains in the migration guide.</p>",
2813            ),
2814            (
2815                41,
2816                "me",
2817                "<p>I’ll take it. Hold the announcement until I clear the link check.</p>",
2818            ),
2819            (
2820                40,
2821                "me",
2822                "<p>Fixed in <code>docs#412</code>, the checker is green.</p>",
2823            ),
2824            (
2825                23,
2826                "mina",
2827                "<ul><li>notes reviewed</li><li>rollback tested</li><li>status page drafted</li></ul>",
2828            ),
2829            (
2830                22,
2831                "mina",
2832                "<p>The release candidate is green. I pinned the final checklist.</p>",
2833            ),
2834        ],
2835        "19:ari@unq.gbl.spaces" => &[
2836            (180, "me", "<p>Thanks for the review yesterday!</p>"),
2837            (
2838                31,
2839                "ari",
2840                "<p>Can you look at the migration guide before lunch? Two screenshots are outdated.</p>",
2841            ),
2842        ],
2843        "19:design@thread.v2" => &[
2844            (300, "lee", "<p>New onboarding flow is in Figma 🎨</p>"),
2845            (95, "me", "<p>Love the empty states. Uploaded my notes.</p>"),
2846        ],
2847        "19:oncall@thread.v2" => &[
2848            (
2849                1600,
2850                "sam",
2851                "<blockquote><p>Is the queue backlog back to normal?</p></blockquote><p>Yes, drained overnight.</p>",
2852            ),
2853            (
2854                1500,
2855                "priya",
2856                "<p>Paging is quiet. Handing over at 18:00.</p>",
2857            ),
2858        ],
2859        "19:weekly@thread.v2" => &[(
2860            4400,
2861            "mina",
2862            "<p>Agenda for Monday is in the meeting notes.</p>",
2863        )],
2864        _ => &[(16000, "sam", "<p>Here are the slides from the offsite.</p>")],
2865    }
2866}
2867
2868fn demo_message(
2869    chat: &str,
2870    index: usize,
2871    now: &Zoned,
2872    (ago, from, html): (i64, &str, &str),
2873) -> Value {
2874    json!({
2875        "id": format!("{chat}/{index}"),
2876        "messageType": "message",
2877        "createdDateTime": demo_time(now, ago),
2878        "from": {"user": demo_person(from)},
2879        "body": {"contentType": "html", "content": html},
2880    })
2881}
2882
2883fn demo_chats(now: &Zoned) -> Page {
2884    let items = DEMO_CHATS
2885        .iter()
2886        .map(|(id, topic, kind, members, unread)| {
2887            let script = demo_script(id);
2888            let last = script[script.len() - 1];
2889            let mut preview = demo_message(id, script.len() - 1, now, last);
2890            preview.as_object_mut().map(|p| p.remove("id"));
2891            let read = if *unread { last.0 + 5 } else { 0 };
2892            json!({
2893                "id": id,
2894                "topic": topic,
2895                "chatType": kind,
2896                "lastUpdatedDateTime": demo_time(now, last.0),
2897                "viewpoint": {"lastMessageReadDateTime": demo_time(now, read)},
2898                "members": members.iter().map(|m| {
2899                    let person = demo_person(m);
2900                    json!({"userId": person["id"], "displayName": person["displayName"]})
2901                }).collect::<Vec<_>>(),
2902                "lastMessagePreview": preview,
2903            })
2904        })
2905        .collect();
2906    demo_page(items)
2907}
2908
2909fn demo_messages(chat: &str, now: &Zoned) -> Page {
2910    demo_page(
2911        demo_script(chat)
2912            .iter()
2913            .enumerate()
2914            .rev()
2915            .map(|(index, line)| demo_message(chat, index, now, *line))
2916            .collect(),
2917    )
2918}
2919
2920fn demo_page(items: Vec<Value>) -> Page {
2921    Page {
2922        items,
2923        next_cursor: None,
2924        next_offset: None,
2925        truncated: false,
2926        source: None,
2927        viewer: Some("me".into()),
2928    }
2929}
2930
2931/// Present an actionable connection state inside the same terminal experience.
2932/// Returning first restores the alternate screen before the caller opens a
2933/// browser or prints device-code instructions.
2934pub fn request_authentication(
2935    profile: &str,
2936    configured: bool,
2937    reason: &str,
2938) -> Result<TuiExit, AppError> {
2939    require_terminal("run `teams auth login --device-code` for headless sign-in")?;
2940    let theme = Theme {
2941        color: std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty()),
2942    };
2943    let _guard = TerminalGuard::enter(false)?;
2944    let mut terminal = Terminal::new(CrosstermBackend::new(io::stdout()))?;
2945    loop {
2946        terminal.draw(|frame| draw_connection(frame, theme, profile, configured, reason))?;
2947        if event::poll(Duration::from_millis(150))?
2948            && let Event::Key(key) = event::read()?
2949            && key.kind == KeyEventKind::Press
2950        {
2951            match key.code {
2952                KeyCode::Enter | KeyCode::Char('a') => return Ok(TuiExit::Authenticate),
2953                KeyCode::Char('q') | KeyCode::Esc => return Ok(TuiExit::Quit),
2954                KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
2955                    return Ok(TuiExit::Quit);
2956                }
2957                _ => {}
2958            }
2959        }
2960    }
2961}
2962
2963pub fn connection_snapshot(
2964    width: u16,
2965    height: u16,
2966    profile: &str,
2967    configured: bool,
2968    reason: &str,
2969) -> Result<String, AppError> {
2970    let mut terminal = Terminal::new(TestBackend::new(
2971        width.max(MIN_WIDTH),
2972        height.max(MIN_HEIGHT),
2973    ))
2974    .expect("test backend is infallible");
2975    terminal
2976        .draw(|frame| draw_connection(frame, Theme { color: false }, profile, configured, reason))
2977        .expect("test backend is infallible");
2978    Ok(buffer_text(terminal.backend().buffer()))
2979}
2980
2981fn draw_connection(
2982    frame: &mut ratatui::Frame<'_>,
2983    theme: Theme,
2984    profile: &str,
2985    configured: bool,
2986    reason: &str,
2987) {
2988    let area = frame.area();
2989    frame.render_widget(Block::default().style(theme.canvas()), area);
2990    frame.render_widget(
2991        Paragraph::new(Line::from(vec![
2992            Span::styled(" TEAMS ", theme.brand()),
2993            Span::styled("  CONNECTION", theme.title()),
2994        ])),
2995        Rect { height: 1, ..area },
2996    );
2997    let (title, heading, action) = if configured {
2998        (
2999            "SIGN-IN REQUIRED",
3000            "Your Teams session needs attention",
3001            "Continue with Microsoft sign-in. Your password is never shared with teams-cli.",
3002        )
3003    } else {
3004        (
3005            "CONNECT MICROSOFT TEAMS",
3006            "Bring your Teams chats into the terminal",
3007            "Set up this profile and continue with secure Microsoft sign-in.",
3008        )
3009    };
3010    let lines = vec![
3011        Line::styled(heading, theme.title()),
3012        Line::styled(format!("Profile: {profile}"), theme.muted()),
3013        Line::raw(""),
3014        Line::styled(reason.to_string(), theme.body()),
3015        Line::styled(action, theme.muted()),
3016        Line::raw(""),
3017        Line::from(vec![
3018            Span::styled("enter / a", theme.key()),
3019            Span::styled(
3020                if configured {
3021                    "  sign in   "
3022                } else {
3023                    "  set up   "
3024                },
3025                theme.muted(),
3026            ),
3027            Span::styled("q", theme.key()),
3028            Span::styled(" quit", theme.muted()),
3029        ]),
3030    ];
3031    state_panel(frame, area, theme, title, lines, theme.active_rule());
3032}
3033
3034#[cfg(test)]
3035mod tests {
3036    use super::*;
3037
3038    #[test]
3039    fn debugging_restart_requires_confirmation_and_can_be_cancelled() {
3040        let mut app = demo_app();
3041        app.apply(Outcome::DebuggingRequired);
3042        press(&mut app, KeyCode::Char('y'));
3043        assert!(app.debugging_restart == Some(DebuggingRestart::Offered));
3044        press(&mut app, KeyCode::Enter);
3045        assert!(app.debugging_restart == Some(DebuggingRestart::Confirming));
3046        press(&mut app, KeyCode::Esc);
3047        assert!(app.debugging_restart == Some(DebuggingRestart::Offered));
3048        assert!(matches!(press(&mut app, KeyCode::Char('q')), Action::Quit));
3049        press(&mut app, KeyCode::Char('r'));
3050        assert!(app.debugging_restart.is_none());
3051        assert!(matches!(app.chats_load, Load::Ready));
3052    }
3053
3054    #[test]
3055    fn debugging_restart_completion_recovers_or_shows_retry() {
3056        let mut app = demo_app();
3057        app.debugging_restart = Some(DebuggingRestart::Running);
3058        app.apply(Outcome::Restarted(Err(AppError::Desktop(
3059            "Restart failed".into(),
3060        ))));
3061        assert!(app.debugging_restart.is_none());
3062        assert!(matches!(app.chats_load, Load::Failed { auth: false, .. }));
3063        app.apply(Outcome::Restarted(Ok(())));
3064        assert!(matches!(app.chats_load, Load::Ready));
3065    }
3066
3067    #[test]
3068    fn debugging_restart_panels_show_actions_and_consequences() {
3069        for (width, height) in [(50, 14), (80, 24), (120, 30)] {
3070            for state in [
3071                DebuggingRestart::Offered,
3072                DebuggingRestart::Confirming,
3073                DebuggingRestart::Running,
3074            ] {
3075                let mut app = demo_app();
3076                app.chats_load = Load::Loading;
3077                app.debugging_restart = Some(state);
3078                let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
3079                terminal.draw(|frame| app.draw(frame)).unwrap();
3080                let text = buffer_text(terminal.backend().buffer());
3081                assert!(!text.contains("teams doctor"));
3082                let words = text
3083                    .replace('│', " ")
3084                    .split_whitespace()
3085                    .collect::<Vec<_>>()
3086                    .join(" ");
3087                assert!(words.contains("send as you"), "{text}");
3088                assert!(text.contains("quit"), "{text}");
3089                if state == DebuggingRestart::Confirming {
3090                    assert!(text.contains("ends any call"), "{text}");
3091                    assert!(text.contains("cancel"), "{text}");
3092                }
3093            }
3094        }
3095    }
3096
3097    #[test]
3098    fn flag_cleanup_requires_confirmation_and_ends_with_a_retry() {
3099        let mut app = demo_app();
3100        app.apply(Outcome::StrayFlags(vec!["OUTLOOK.EXE".into()]));
3101        let stage = |app: &App| app.flag_cleanup.as_ref().map(|cleanup| cleanup.stage);
3102        press(&mut app, KeyCode::Char('y'));
3103        assert!(stage(&app) == Some(Cleanup::Offered));
3104        press(&mut app, KeyCode::Enter);
3105        assert!(stage(&app) == Some(Cleanup::Confirming));
3106        press(&mut app, KeyCode::Esc);
3107        assert!(stage(&app) == Some(Cleanup::Offered));
3108        press(&mut app, KeyCode::Enter);
3109        // The demo app has no desktop client, so nothing is changed.
3110        press(&mut app, KeyCode::Char('y'));
3111        assert!(stage(&app) == Some(Cleanup::Confirming));
3112        app.apply(Outcome::FlagsCleared(Ok(())));
3113        assert!(stage(&app) == Some(Cleanup::Done));
3114        assert!(matches!(press(&mut app, KeyCode::Char('q')), Action::Quit));
3115        press(&mut app, KeyCode::Char('r'));
3116        assert!(app.flag_cleanup.is_none());
3117        assert!(matches!(app.chats_load, Load::Ready));
3118
3119        app.apply(Outcome::StrayFlags(vec![]));
3120        app.apply(Outcome::FlagsCleared(Err(AppError::Desktop(
3121            "Clearing failed".into(),
3122        ))));
3123        assert!(app.flag_cleanup.is_none());
3124        assert!(matches!(app.chats_load, Load::Failed { auth: false, .. }));
3125    }
3126
3127    #[test]
3128    fn flag_cleanup_panels_name_the_apps_and_the_consequences() {
3129        for (width, height) in [(50, 14), (80, 24), (120, 30)] {
3130            for stage in [
3131                Cleanup::Offered,
3132                Cleanup::Confirming,
3133                Cleanup::Running,
3134                Cleanup::Done,
3135            ] {
3136                let mut app = demo_app();
3137                app.chats_load = Load::Loading;
3138                app.flag_cleanup = Some(FlagCleanup {
3139                    stage,
3140                    apps: vec!["OUTLOOK.EXE".into()],
3141                });
3142                let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
3143                terminal.draw(|frame| app.draw(frame)).unwrap();
3144                let text = buffer_text(terminal.backend().buffer());
3145                let words = text
3146                    .replace('│', " ")
3147                    .split_whitespace()
3148                    .collect::<Vec<_>>()
3149                    .join(" ");
3150                assert!(words.contains("until fully quit"), "{text}");
3151                assert!(text.contains("quit"), "{text}");
3152                match stage {
3153                    Cleanup::Offered | Cleanup::Done => {
3154                        assert!(words.contains("OUTLOOK.EXE"), "{text}")
3155                    }
3156                    Cleanup::Confirming => {
3157                        assert!(words.contains("keeps its other"), "{text}");
3158                        assert!(text.contains("cancel"), "{text}");
3159                    }
3160                    Cleanup::Running => {}
3161                }
3162            }
3163        }
3164    }
3165
3166    fn demo_app() -> App {
3167        let now: Zoned = "2026-10-13T10:15:00+02:00[Europe/Amsterdam]"
3168            .parse()
3169            .unwrap();
3170        let mut app = App::new(Source::Demo, Theme { color: false }, now);
3171        app.start();
3172        app
3173    }
3174
3175    fn press(app: &mut App, code: KeyCode) -> Action {
3176        app.handle_key(KeyEvent::new(code, KeyModifiers::NONE))
3177    }
3178
3179    #[test]
3180    fn snapshot_shows_the_ledger_and_the_open_conversation() {
3181        let frame = snapshot(90, 26).unwrap();
3182        assert!(frame.contains("TEAMS"));
3183        assert!(frame.contains("Launch room · group"));
3184        assert!(frame.contains("Ari Chen"));
3185        assert!(frame.contains("release candidate is green"));
3186        assert!(frame.contains("── Today ──"));
3187        assert!(frame.contains("You  09:34"));
3188        assert!(frame.contains("q quit"));
3189    }
3190
3191    #[test]
3192    fn colour_paints_every_cell_so_the_terminal_background_never_shows() {
3193        let now: Zoned = "2026-10-13T10:15:00+02:00[Europe/Amsterdam]"
3194            .parse()
3195            .unwrap();
3196        let mut app = App::new(Source::Demo, Theme { color: true }, now);
3197        app.start();
3198        let unpainted = |buffer: &ratatui::buffer::Buffer| {
3199            buffer
3200                .content()
3201                .iter()
3202                .filter(|cell| cell.bg == Color::Reset)
3203                .count()
3204        };
3205        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
3206        terminal.draw(|frame| app.draw(frame)).unwrap();
3207        assert_eq!(unpainted(terminal.backend().buffer()), 0);
3208        press(&mut app, KeyCode::Enter);
3209        terminal.draw(|frame| app.draw(frame)).unwrap();
3210        assert_eq!(unpainted(terminal.backend().buffer()), 0);
3211        terminal
3212            .draw(|frame| draw_connection(frame, Theme { color: true }, "default", true, "x"))
3213            .unwrap();
3214        assert_eq!(unpainted(terminal.backend().buffer()), 0);
3215    }
3216
3217    #[test]
3218    fn narrow_terminals_take_turns_and_tiny_ones_ask_for_room() {
3219        let frame = snapshot(60, 24).unwrap();
3220        assert!(frame.contains("Launch room"));
3221        assert!(!frame.contains("rollback tested"));
3222        let mut app = demo_app();
3223        press(&mut app, KeyCode::Enter);
3224        let mut terminal = Terminal::new(TestBackend::new(60, 24)).unwrap();
3225        terminal.draw(|frame| app.draw(frame)).unwrap();
3226        let text = buffer_text(terminal.backend().buffer());
3227        assert!(text.contains("rollback tested"));
3228        assert!(text.contains("esc chats"));
3229        let mut terminal = Terminal::new(TestBackend::new(40, 10)).unwrap();
3230        terminal.draw(|frame| app.draw(frame)).unwrap();
3231        assert!(buffer_text(terminal.backend().buffer()).contains("NEEDS MORE ROOM"));
3232    }
3233
3234    #[test]
3235    fn filtering_narrows_the_ledger_and_esc_restores_it() {
3236        let mut app = demo_app();
3237        assert_eq!(app.visible.len(), DEMO_CHATS.len());
3238        press(&mut app, KeyCode::Char('/'));
3239        for c in "on-call".chars() {
3240            press(&mut app, KeyCode::Char(c));
3241        }
3242        assert_eq!(app.visible.len(), 1);
3243        assert_eq!(app.selected_row().unwrap().title, "Platform on-call");
3244        press(&mut app, KeyCode::Enter);
3245        assert!(app.overlay.is_none());
3246        press(&mut app, KeyCode::Esc);
3247        assert_eq!(app.visible.len(), DEMO_CHATS.len());
3248        assert_eq!(app.selected_row().unwrap().title, "Platform on-call");
3249    }
3250
3251    #[test]
3252    fn opening_a_chat_loads_it_once_and_scroll_is_bounded() {
3253        let mut app = demo_app();
3254        press(&mut app, KeyCode::Char('j'));
3255        press(&mut app, KeyCode::Enter);
3256        assert!(app.focus == Focus::Thread);
3257        assert!(app.threads.contains_key("19:ari@unq.gbl.spaces"));
3258        for _ in 0..50 {
3259            press(&mut app, KeyCode::Char('k'));
3260        }
3261        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
3262        terminal.draw(|frame| app.draw(frame)).unwrap();
3263        assert_eq!(app.scroll, 0, "a short chat cannot scroll");
3264        press(&mut app, KeyCode::Esc);
3265        assert!(app.focus == Focus::Chats);
3266        press(&mut app, KeyCode::Char('?'));
3267        terminal.draw(|frame| app.draw(frame)).unwrap();
3268        assert!(buffer_text(terminal.backend().buffer()).contains("KEYBOARD MAP"));
3269        assert!(matches!(press(&mut app, KeyCode::Char('q')), Action::None));
3270        assert!(matches!(press(&mut app, KeyCode::Char('q')), Action::Quit));
3271    }
3272
3273    fn mouse(app: &mut App, kind: MouseEventKind, column: u16, row: u16) {
3274        app.handle_mouse(MouseEvent {
3275            kind,
3276            column,
3277            row,
3278            modifiers: KeyModifiers::NONE,
3279        });
3280    }
3281
3282    #[test]
3283    fn the_wheel_scrolls_the_pane_under_the_pointer_and_clicks_open_chats() {
3284        let mut app = demo_app();
3285        app.open_selected();
3286        let mut terminal = Terminal::new(TestBackend::new(100, 16)).unwrap();
3287        terminal.draw(|frame| app.draw(frame)).unwrap();
3288        let ledger = app.ledger_area.expect("ledger drawn");
3289        let thread = app.thread_area.expect("conversation drawn");
3290        assert!(
3291            app.thread_overflow > WHEEL_LINES,
3292            "the demo chat overflows 16 rows"
3293        );
3294
3295        // The wheel over the conversation scrolls it even while the ledger has focus.
3296        assert!(app.focus == Focus::Chats);
3297        mouse(
3298            &mut app,
3299            MouseEventKind::ScrollUp,
3300            thread.x + 5,
3301            thread.y + 5,
3302        );
3303        assert_eq!(app.scroll, WHEEL_LINES);
3304        assert_eq!(app.list.selected(), Some(0), "the ledger did not move");
3305        for _ in 0..50 {
3306            mouse(
3307                &mut app,
3308                MouseEventKind::ScrollUp,
3309                thread.x + 5,
3310                thread.y + 5,
3311            );
3312        }
3313        assert_eq!(
3314            app.scroll, app.thread_overflow,
3315            "scrolling stops at the oldest line"
3316        );
3317        mouse(
3318            &mut app,
3319            MouseEventKind::ScrollDown,
3320            thread.x + 5,
3321            thread.y + 5,
3322        );
3323        assert_eq!(app.scroll, app.thread_overflow - WHEEL_LINES);
3324
3325        // The wheel over the ledger moves the selection, which resets the conversation.
3326        mouse(&mut app, MouseEventKind::ScrollDown, ledger.x + 2, ledger.y);
3327        assert_eq!(app.list.selected(), Some(1));
3328        assert_eq!(app.scroll, 0);
3329        mouse(&mut app, MouseEventKind::ScrollUp, ledger.x + 2, ledger.y);
3330        assert_eq!(app.list.selected(), Some(0));
3331
3332        // A click on the second entry opens it; a click in the conversation focuses it.
3333        let left = MouseEventKind::Down(MouseButton::Left);
3334        mouse(&mut app, left, ledger.x + 2, ledger.y + CHAT_ROW_HEIGHT + 1);
3335        assert_eq!(app.list.selected(), Some(1));
3336        assert!(app.focus == Focus::Thread);
3337        let id = app.selected_row().unwrap().id.clone();
3338        assert!(app.threads.contains_key(&id));
3339        press(&mut app, KeyCode::Tab);
3340        assert!(app.focus == Focus::Chats);
3341        mouse(&mut app, left, thread.x + 5, thread.y + 5);
3342        assert!(app.focus == Focus::Thread);
3343
3344        // Outside both panes, and while the help is open, the mouse does nothing else.
3345        mouse(&mut app, MouseEventKind::ScrollDown, 0, 0);
3346        assert_eq!(app.list.selected(), Some(1));
3347        press(&mut app, KeyCode::Char('?'));
3348        mouse(&mut app, MouseEventKind::ScrollDown, ledger.x + 2, ledger.y);
3349        assert_eq!(app.list.selected(), Some(1));
3350        mouse(&mut app, left, 0, 0);
3351        assert!(app.overlay.is_none(), "a click closes the help");
3352    }
3353
3354    #[test]
3355    fn the_composer_keeps_its_chat_when_the_ledger_is_clicked() {
3356        let mut app = demo_app();
3357        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
3358        press(&mut app, KeyCode::Enter);
3359        press(&mut app, KeyCode::Char('c'));
3360        assert!(app.compose.is_some());
3361        terminal.draw(|frame| app.draw(frame)).unwrap();
3362        let ledger = app.ledger_area.expect("ledger drawn");
3363        let left = MouseEventKind::Down(MouseButton::Left);
3364        mouse(&mut app, left, ledger.x + 2, ledger.y + CHAT_ROW_HEIGHT + 1);
3365        mouse(&mut app, MouseEventKind::ScrollDown, ledger.x + 2, ledger.y);
3366        assert_eq!(app.list.selected(), Some(0));
3367    }
3368
3369    #[test]
3370    fn opening_a_chat_prefetches_its_neighbours_and_retries_failures() {
3371        let mut app = demo_app();
3372        press(&mut app, KeyCode::Char('j'));
3373        press(&mut app, KeyCode::Enter);
3374        let ids: Vec<String> = app
3375            .visible
3376            .iter()
3377            .map(|&i| app.rows[i].id.clone())
3378            .collect();
3379        let below = ids[2].clone();
3380        assert!(app.threads.contains_key(&ids[0]) && app.threads.contains_key(&below));
3381        assert!(!app.threads.contains_key(&ids[3]));
3382        app.threads.get_mut(&below).unwrap().load =
3383            Load::failed(&AppError::Desktop("read failed".into()));
3384        press(&mut app, KeyCode::Esc);
3385        press(&mut app, KeyCode::Char('j'));
3386        app.open_selected();
3387        assert!(matches!(app.threads[&below].load, Load::Ready));
3388        assert!(app.threads.contains_key(&ids[3]));
3389    }
3390
3391    #[test]
3392    fn auth_failures_offer_sign_in_from_inside_the_tui() {
3393        let mut app = demo_app();
3394        app.chats_load = Load::failed(&AppError::Auth("session expired".into()));
3395        let mut terminal = Terminal::new(TestBackend::new(90, 24)).unwrap();
3396        terminal.draw(|frame| app.draw(frame)).unwrap();
3397        let text = buffer_text(terminal.backend().buffer());
3398        assert!(text.contains("SIGN-IN REQUIRED"));
3399        assert!(text.contains("enter / a"));
3400        assert!(matches!(
3401            press(&mut app, KeyCode::Enter),
3402            Action::Authenticate
3403        ));
3404    }
3405
3406    #[test]
3407    fn background_sign_in_loss_preserves_the_draft_and_disables_sending() {
3408        let mut app = live_app(true, "synthetic-work");
3409        app.compose = Some(Compose {
3410            chat: "synthetic-chat".into(),
3411            text: "Keep this draft".into(),
3412            cursor: 15,
3413            stage: Stage::Editing,
3414        });
3415        app.startup_failed(&AppError::Auth("Teams needs its browser window".into()));
3416        assert!(!app.can_send());
3417        assert!(app.sign_in_needed());
3418        assert!(app.compose.is_none());
3419        assert_eq!(app.drafts["synthetic-chat"], "Keep this draft");
3420        assert!(matches!(
3421            press(&mut app, KeyCode::Char('a')),
3422            Action::Authenticate
3423        ));
3424        assert!(matches!(press(&mut app, KeyCode::Char('q')), Action::Quit));
3425        app.send();
3426        assert!(app.pending_sends.is_empty());
3427        assert_eq!(app.drafts["synthetic-chat"], "Keep this draft");
3428        app.apply(Outcome::Chats {
3429            more: false,
3430            result: Ok(demo_chats(&app.now)),
3431        });
3432        app.tick();
3433        assert!(app.sign_in_needed());
3434        assert!(!app.notice.text.contains("Enter opens a chat"));
3435        let mut saved = InboxState::default();
3436        app.preserve_drafts(&mut saved);
3437        assert_eq!(saved.drafts["synthetic-chat"], "Keep this draft");
3438    }
3439
3440    #[test]
3441    fn a_non_auth_startup_failure_keeps_chats_readable_and_refresh_can_succeed() {
3442        let mut app = live_app(true, "synthetic-work");
3443        app.apply(Outcome::Chats {
3444            more: false,
3445            result: Ok(demo_chats(&app.now)),
3446        });
3447        app.startup_failed(&AppError::Desktop("Temporary verification failure".into()));
3448        assert!(matches!(app.chats_load, Load::Ready));
3449        assert!(!app.can_send());
3450        assert!(app.notice.text.contains("Sending is paused"));
3451        app.chats_load = Load::Loading;
3452        app.apply(Outcome::Chats {
3453            more: false,
3454            result: Ok(demo_chats(&app.now)),
3455        });
3456        app.tick();
3457        assert!(matches!(app.chats_load, Load::Ready));
3458        assert!(!app.sign_in_needed());
3459        assert!(!app.can_send());
3460        press(&mut app, KeyCode::Char('c'));
3461        assert!(app.notice.text.contains("Sending is paused"));
3462        assert!(!app.notice.text.contains("profile is read-only"));
3463        assert!(frame_text(&mut app).contains("sending paused"));
3464    }
3465
3466    #[test]
3467    fn a_read_only_profile_does_not_claim_sending_was_paused() {
3468        let mut app = live_app(false, "synthetic-profile");
3469        app.apply(Outcome::Chats {
3470            more: false,
3471            result: Ok(demo_chats(&app.now)),
3472        });
3473        app.startup_failed(&AppError::Desktop("Temporary verification failure".into()));
3474        assert_eq!(app.notice.text, "Temporary verification failure");
3475        press(&mut app, KeyCode::Char('c'));
3476        assert!(app.notice.text.contains("profile is read-only"));
3477        assert!(!app.notice.text.contains("Sending is paused"));
3478        let text = frame_text(&mut app);
3479        assert!(text.lines().next().unwrap().contains("read-only"));
3480        assert!(!text.contains("sending paused"));
3481    }
3482
3483    fn frame_text(app: &mut App) -> String {
3484        let mut terminal = Terminal::new(TestBackend::new(100, 28)).unwrap();
3485        terminal.draw(|frame| app.draw(frame)).unwrap();
3486        buffer_text(terminal.backend().buffer())
3487    }
3488
3489    fn type_text(app: &mut App, text: &str) {
3490        for c in text.chars() {
3491            press(app, KeyCode::Char(c));
3492        }
3493    }
3494
3495    #[test]
3496    fn enter_sends_the_draft_and_the_message_appears() {
3497        let mut app = demo_app();
3498        app.open_selected();
3499        press(&mut app, KeyCode::Char('c'));
3500        assert!(app.focus == Focus::Thread);
3501        // List keys are text while composing.
3502        type_text(&mut app, "on it q r /");
3503        app.handle_key(KeyEvent::new(KeyCode::Char('j'), KeyModifiers::CONTROL));
3504        type_text(&mut app, "shipping");
3505        assert!(app.overlay.is_none());
3506        let compose = app.compose.as_ref().unwrap();
3507        assert_eq!(compose.text, "on it q r /\nshipping");
3508        assert!(frame_text(&mut app).contains("MESSAGE"));
3509
3510        press(&mut app, KeyCode::Enter);
3511        assert!(app.compose.is_none());
3512        assert_eq!(app.notice.text, "Sent.");
3513        let thread = &app.threads["19:launch@thread.v2"];
3514        assert_eq!(thread.items.len(), 8);
3515        assert_eq!(thread.items[0]["body"]["content"], "on it q r /\nshipping");
3516        assert!(frame_text(&mut app).contains("shipping"));
3517    }
3518
3519    #[test]
3520    fn paste_keeps_multiline_text_in_the_draft_until_enter() {
3521        let mut app = demo_app();
3522        app.open_selected();
3523        app.paste("c accidental commands\n");
3524        assert!(app.compose.is_none());
3525        press(&mut app, KeyCode::Char('c'));
3526        type_text(&mut app, "ab");
3527        press(&mut app, KeyCode::Left);
3528        app.paste("é\r\nsecond\rthird\n");
3529        let compose = app.compose.as_ref().unwrap();
3530        assert_eq!(compose.text, "aé\nsecond\nthird\nb");
3531        assert_eq!(&compose.text[..compose.cursor], "aé\nsecond\nthird\n");
3532        assert_eq!(app.threads["19:launch@thread.v2"].items.len(), 7);
3533        press(&mut app, KeyCode::Enter);
3534        assert!(app.compose.is_none());
3535        assert_eq!(app.threads["19:launch@thread.v2"].items.len(), 8);
3536    }
3537
3538    #[test]
3539    fn sending_ignores_extra_keys_and_paste_and_failure_keeps_the_draft() {
3540        let mut app = demo_app();
3541        app.open_selected();
3542        press(&mut app, KeyCode::Char('c'));
3543        type_text(&mut app, "keep this");
3544        app.compose.as_mut().unwrap().stage = Stage::Sending;
3545        for key in [KeyCode::Enter, KeyCode::Char('y'), KeyCode::Esc] {
3546            press(&mut app, key);
3547        }
3548        app.paste("more\n");
3549        assert_eq!(app.compose.as_ref().unwrap().text, "keep this");
3550        assert_eq!(app.threads["19:launch@thread.v2"].items.len(), 7);
3551        app.apply(Outcome::Sent {
3552            chat: "19:launch@thread.v2".into(),
3553            result: Err(AppError::Unconfirmed(
3554                "Check the conversation before sending again".into(),
3555            )),
3556        });
3557        assert!(app.compose.as_ref().unwrap().stage == Stage::Unconfirmed);
3558        assert_eq!(app.compose.as_ref().unwrap().text, "keep this");
3559        assert!(app.notice.text.contains("Check the conversation"));
3560        assert_eq!(app.threads["19:launch@thread.v2"].items.len(), 7);
3561        press(&mut app, KeyCode::Esc);
3562        press(&mut app, KeyCode::Char('c'));
3563        assert_eq!(app.compose.as_ref().unwrap().text, "keep this");
3564    }
3565
3566    #[test]
3567    fn uncertain_send_blocks_enter_paste_and_reopening_until_explicit_resend() {
3568        let mut app = demo_app();
3569        app.open_selected();
3570        press(&mut app, KeyCode::Char('c'));
3571        type_text(&mut app, "one copy");
3572        let chat = app.compose.as_ref().unwrap().chat.clone();
3573        let before = app.threads[&chat].items.len();
3574        app.pending_sends
3575            .insert(chat.clone(), "100000000000000001".into());
3576        app.apply(Outcome::Sent {
3577            chat: chat.clone(),
3578            result: Err(AppError::Unconfirmed("may arrive".into())),
3579        });
3580        for _ in 0..3 {
3581            press(&mut app, KeyCode::Enter);
3582        }
3583        app.paste("another copy\n");
3584        assert_eq!(app.compose.as_ref().unwrap().text, "one copy");
3585        assert_eq!(app.threads[&chat].items.len(), before);
3586        press(&mut app, KeyCode::Esc);
3587        press(&mut app, KeyCode::Char('c'));
3588        assert!(app.compose.as_ref().unwrap().stage == Stage::Unconfirmed);
3589        press(&mut app, KeyCode::Char('r'));
3590        assert!(app.compose.as_ref().unwrap().stage == Stage::Unconfirmed);
3591        assert!(app.notice.text.contains("absence does not prove failure"));
3592        press(&mut app, KeyCode::Char('s'));
3593        press(&mut app, KeyCode::Enter); // Enter is not confirmation.
3594        assert_eq!(app.threads[&chat].items.len(), before);
3595        press(&mut app, KeyCode::Char('s'));
3596        press(&mut app, KeyCode::Char('y'));
3597        assert_eq!(app.threads[&chat].items.len(), before + 1);
3598        assert!(app.compose.is_none());
3599        assert!(!app.pending_sends.contains_key(&chat));
3600    }
3601
3602    #[test]
3603    fn delivery_check_uses_original_id_and_queued_success_is_not_labelled_sent() {
3604        let mut app = demo_app();
3605        app.open_selected();
3606        press(&mut app, KeyCode::Char('c'));
3607        type_text(&mut app, "once");
3608        let chat = app.compose.as_ref().unwrap().chat.clone();
3609        let id = "100000000000000001".to_string();
3610        app.pending_sends.insert(chat.clone(), id.clone());
3611        app.apply(Outcome::Sent {
3612            chat: chat.clone(),
3613            result: Err(AppError::Unconfirmed("uncertain".into())),
3614        });
3615        app.apply(Outcome::Delivery {
3616            chat: chat.clone(),
3617            id: "100000000000000002".into(),
3618            result: Ok(json!({"found":true,"delivery_state":"delivered"})),
3619        });
3620        assert!(app.compose.is_some());
3621        app.apply(Outcome::Delivery {
3622            chat: chat.clone(),
3623            id: id.clone(),
3624            result: Ok(json!({"found":true,"delivery_state":"unknown"})),
3625        });
3626        assert!(app.compose.as_ref().unwrap().stage == Stage::Unconfirmed);
3627        assert!(app.notice.text.contains("Found the original message"));
3628        app.apply(Outcome::Delivery {
3629            chat: chat.clone(),
3630            id,
3631            result: Ok(json!({"found":true,"delivery_state":"delivered"})),
3632        });
3633        assert!(app.compose.is_none());
3634        assert!(app.notice.text.contains("original client message ID"));
3635        press(&mut app, KeyCode::Char('c'));
3636        app.apply(Outcome::Sent {
3637            chat,
3638            result: Ok(json!({"id":"queued","source":"desktop","status":"Queued"})),
3639        });
3640        assert!(app.notice.text.starts_with("Queued in Teams"));
3641        assert!(!app.notice.text.starts_with("Sent"));
3642    }
3643
3644    #[test]
3645    fn composer_rejects_oversized_drafts_and_alt_enter_inserts_a_line() {
3646        let mut app = demo_app();
3647        press(&mut app, KeyCode::Char('c'));
3648        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT));
3649        assert_eq!(app.compose.as_ref().unwrap().text, "\n");
3650        app.paste(&"é".repeat(MAX_BODY));
3651        press(&mut app, KeyCode::Enter);
3652        assert!(app.compose.as_ref().unwrap().stage == Stage::Editing);
3653        assert!(app.notice.text.contains("Too long to send"));
3654    }
3655
3656    #[test]
3657    fn composer_hints_fit_narrow_and_wide_terminals() {
3658        for width in [50, 100] {
3659            let mut app = demo_app();
3660            app.open_selected();
3661            press(&mut app, KeyCode::Char('c'));
3662            let mut terminal = Terminal::new(TestBackend::new(width, 28)).unwrap();
3663            terminal.draw(|frame| app.draw(frame)).unwrap();
3664            let text = buffer_text(terminal.backend().buffer());
3665            assert!(text.contains("enter send"), "{text}");
3666            assert!(text.contains("esc close, keep draft"), "{text}");
3667            assert!(!text.contains("SEND THIS?"));
3668        }
3669    }
3670
3671    #[test]
3672    fn drafts_survive_closing_and_blank_ones_are_not_offered() {
3673        let mut app = demo_app();
3674        press(&mut app, KeyCode::Char('c'));
3675        press(&mut app, KeyCode::Char(' '));
3676        press(&mut app, KeyCode::Enter);
3677        assert!(app.compose.as_ref().unwrap().stage == Stage::Editing);
3678        type_text(&mut app, "draft");
3679        press(&mut app, KeyCode::Left);
3680        press(&mut app, KeyCode::Backspace);
3681        press(&mut app, KeyCode::Esc);
3682        assert!(app.compose.is_none());
3683        press(&mut app, KeyCode::Char('j'));
3684        press(&mut app, KeyCode::Char('k'));
3685        press(&mut app, KeyCode::Char('c'));
3686        let compose = app.compose.as_ref().unwrap();
3687        assert_eq!(compose.text, " drat");
3688        assert_eq!(compose.cursor, compose.text.len());
3689    }
3690
3691    #[test]
3692    fn read_only_profiles_only_explain_how_to_send() {
3693        let now: Zoned = "2026-10-13T10:15:00+02:00[Europe/Amsterdam]"
3694            .parse()
3695            .unwrap();
3696        let source = Source::Live {
3697            backend: Arc::new(TeamsBackend::Graph(crate::graph::GraphClient::new(
3698                "fixture".into(),
3699            ))),
3700            profile: "fixture".into(),
3701            can_send: false,
3702        };
3703        let mut app = App::new(source, Theme { color: false }, now.clone());
3704        app.apply(Outcome::Chats {
3705            more: false,
3706            result: Ok(demo_chats(&now)),
3707        });
3708        press(&mut app, KeyCode::Char('c'));
3709        assert!(app.compose.is_none());
3710        assert!(app.notice.text.contains("read-only"));
3711        assert!(!frame_text(&mut app).contains("c reply"));
3712    }
3713
3714    fn header(app: &mut App, width: u16) -> Vec<String> {
3715        let mut terminal = Terminal::new(TestBackend::new(width, 24)).unwrap();
3716        terminal.draw(|frame| app.draw(frame)).unwrap();
3717        buffer_text(terminal.backend().buffer())
3718            .lines()
3719            .take(2)
3720            .map(String::from)
3721            .collect()
3722    }
3723
3724    fn live_app(can_send: bool, profile: &str) -> App {
3725        let now: Zoned = "2026-10-13T10:15:00+02:00[Europe/Amsterdam]"
3726            .parse()
3727            .unwrap();
3728        let source = Source::Live {
3729            backend: Arc::new(TeamsBackend::Graph(crate::graph::GraphClient::new(
3730                "fixture".into(),
3731            ))),
3732            profile: profile.into(),
3733            can_send,
3734        };
3735        App::new(source, Theme { color: false }, now)
3736    }
3737
3738    #[test]
3739    fn a_chat_without_history_shows_its_latest_message_and_why() {
3740        let empty = |app: &mut App| {
3741            let id = app.selected_row().unwrap().id.clone();
3742            app.threads.insert(
3743                id,
3744                Thread {
3745                    items: Vec::new(),
3746                    cursor: None,
3747                    load: Load::Ready,
3748                    loading_older: false,
3749                    fetching: false,
3750                },
3751            );
3752            frame_text(app)
3753        };
3754        let mut app = demo_app();
3755        let text = empty(&mut app);
3756        assert!(
3757            text.contains("Only the latest message is available."),
3758            "{text}"
3759        );
3760        assert!(text.contains("release candidate is green"), "{text}");
3761        assert!(!text.contains("No messages in this chat yet."), "{text}");
3762
3763        let now = app.now.clone();
3764        let mut app = live_app(false, "work");
3765        app.source = Source::Live {
3766            backend: Arc::new(TeamsBackend::Desktop(Box::new(
3767                crate::desktop::DesktopClient::new(19224).unwrap(),
3768            ))),
3769            profile: "work".into(),
3770            can_send: false,
3771        };
3772        app.apply(Outcome::Chats {
3773            more: false,
3774            result: Ok(demo_chats(&now)),
3775        });
3776        let text = empty(&mut app);
3777        assert!(text.contains("were found in the Teams cache"), "{text}");
3778        // The note wraps with the pane rather than being cut off.
3779        let mut terminal = Terminal::new(TestBackend::new(60, 24)).unwrap();
3780        app.focus = Focus::Thread;
3781        terminal.draw(|frame| app.draw(frame)).unwrap();
3782        let narrow = buffer_text(terminal.backend().buffer());
3783        assert!(narrow.contains("Latest message:"), "{narrow}");
3784        assert!(text.contains("release candidate is green"), "{text}");
3785
3786        // Older pages may still hold messages, so nothing is claimed missing.
3787        let id = app.selected_row().unwrap().id.clone();
3788        app.threads.get_mut(&id).unwrap().cursor = Some("older".into());
3789        let text = frame_text(&mut app);
3790        assert!(text.contains("No messages in this chat yet."), "{text}");
3791
3792        // Without a preview there is nothing to show.
3793        app.chats[0]["lastMessagePreview"] = Value::Null;
3794        let text = empty(&mut app);
3795        assert!(text.contains("No messages in this chat yet."), "{text}");
3796    }
3797
3798    #[test]
3799    fn the_header_shows_the_profile_send_mode_freshness_and_counts() {
3800        let mut app = demo_app();
3801        let [title, context] = header(&mut app, 100).try_into().unwrap();
3802        assert!(title.starts_with(" TEAMS   demo "));
3803        assert!(
3804            title.ends_with("  ✎ can send"),
3805            "sample data has no freshness: {title}"
3806        );
3807        assert_eq!(context, " 6 chats  ·  2 unread  ·  sample data");
3808
3809        let mut app = live_app(false, "work");
3810        let [title, context] = header(&mut app, 100).try_into().unwrap();
3811        assert!(title.ends_with(" syncing   read-only"), "{title}");
3812        assert_eq!(context.trim(), "Microsoft Graph");
3813        app.apply(Outcome::Chats {
3814            more: false,
3815            result: Ok(demo_chats(&app.now.clone())),
3816        });
3817        app.account = Some("Ari Chen".into());
3818        let [title, _] = header(&mut app, 100).try_into().unwrap();
3819        assert!(title.starts_with(" TEAMS   work  ·  Ari Chen "), "{title}");
3820        assert!(title.ends_with(" ● live   read-only"), "{title}");
3821    }
3822
3823    #[test]
3824    fn narrow_headers_keep_the_send_mode_and_drop_the_rest_in_order() {
3825        let mut app = live_app(true, "a-rather-long-profile-name-for-work");
3826        app.apply(Outcome::Chats {
3827            more: false,
3828            result: Ok(demo_chats(&app.now.clone())),
3829        });
3830        app.account = Some("Someone With A Long Display Name".into());
3831        let [title, _] = header(&mut app, 110).try_into().unwrap();
3832        assert!(title.contains("for-work  ·  Someone With"), "{title}");
3833        let [title, _] = header(&mut app, 100).try_into().unwrap();
3834        assert!(
3835            !title.contains("Someone"),
3836            "the account goes first: {title}"
3837        );
3838        assert!(title.contains("for-work "), "{title}");
3839        let [title, context] = header(&mut app, 50).try_into().unwrap();
3840        // The one-column right margin is trimmed from the frame text.
3841        assert_eq!(title.chars().count(), 49, "{title}");
3842        assert!(title.ends_with("● live   ✎ can send"), "{title}");
3843        assert!(title.contains("a-rather-long-pro"), "{title}");
3844        assert!(title.contains('…'), "the profile is shortened: {title}");
3845        assert_eq!(context, " 6 chats  ·  2 unread  ·  Microsoft Graph");
3846    }
3847
3848    #[test]
3849    fn failed_refreshes_mark_the_chats_stale_until_one_succeeds() {
3850        let mut app = live_app(false, "work");
3851        let chats = || Outcome::Chats {
3852            more: false,
3853            result: Ok(demo_chats(
3854                &"2026-10-13T10:15:00+02:00[Europe/Amsterdam]"
3855                    .parse()
3856                    .unwrap(),
3857            )),
3858        };
3859        app.apply(chats());
3860        let at = app
3861            .synced_at
3862            .clone()
3863            .expect("a successful read is recorded");
3864        assert!(!app.stale);
3865        app.fetching_chats = true;
3866        app.apply(Outcome::Chats {
3867            more: false,
3868            result: Err(AppError::Api("unavailable".into())),
3869        });
3870        assert!(app.stale);
3871        let [title, _] = header(&mut app, 100).try_into().unwrap();
3872        assert!(
3873            title.contains(&format!("stale since {}", at.strftime("%H:%M"))),
3874            "{title}"
3875        );
3876        app.apply(chats());
3877        assert!(!app.stale);
3878        let [title, _] = header(&mut app, 100).try_into().unwrap();
3879        assert!(title.contains("● live"), "{title}");
3880    }
3881
3882    #[test]
3883    fn reloads_keep_older_pages_only_when_the_fresh_page_overlaps() {
3884        let ids = |items: &[Value]| -> Vec<String> {
3885            items
3886                .iter()
3887                .map(|v| v["id"].as_str().unwrap().to_string())
3888                .collect()
3889        };
3890        let page =
3891            |names: &[&str]| -> Vec<Value> { names.iter().map(|id| json!({"id": id})).collect() };
3892        let old = page(&["c", "b", "a"]);
3893        let (items, cursor) = merge_newest(
3894            page(&["d", "c"]),
3895            Some("new".into()),
3896            old.clone(),
3897            Some("old".into()),
3898        );
3899        assert_eq!(ids(&items), ["d", "c", "b", "a"]);
3900        assert_eq!(cursor.as_deref(), Some("old"));
3901        let (items, cursor) =
3902            merge_newest(page(&["f", "e"]), Some("new".into()), old.clone(), None);
3903        assert_eq!(ids(&items), ["f", "e"], "no overlap means a possible gap");
3904        assert_eq!(cursor.as_deref(), Some("new"));
3905        let (items, cursor) = merge_newest(page(&["d", "c"]), None, old, Some("old".into()));
3906        assert_eq!(
3907            ids(&items),
3908            ["d", "c"],
3909            "a complete page replaces everything"
3910        );
3911        assert!(cursor.is_none());
3912    }
3913
3914    #[test]
3915    fn drafts_wrap_and_track_the_cursor() {
3916        assert_eq!(layout_draft("", 0, 10), (vec![String::new()], (0, 0)));
3917        let (rows, at) = layout_draft("abcdef\ngh", 8, 4);
3918        assert_eq!(rows, ["abcd", "ef", "gh"]);
3919        assert_eq!(at, (2, 1));
3920        assert_eq!(layout_draft("abcd", 4, 4).1, (0, 4));
3921        assert_eq!(layout_draft("ab\n", 3, 4).1, (1, 0));
3922        let (rows, at) = layout_draft("你好你", "你好".len(), 4);
3923        assert_eq!(rows, ["你好", "你"]);
3924        assert_eq!(at, (1, 0));
3925    }
3926
3927    #[test]
3928    fn connection_snapshot_has_a_clear_recovery_action() {
3929        let frame =
3930            connection_snapshot(80, 22, "work", true, "Your saved session has expired.").unwrap();
3931        assert!(frame.contains("SIGN-IN REQUIRED"));
3932        assert!(frame.contains("Profile: work"));
3933        assert!(frame.contains("enter / a"));
3934        assert!(frame.contains("sign in"));
3935        assert!(frame.contains("q quit"));
3936    }
3937}