Skip to main content

taimux_cli/
tui.rs

1//! The picker, drawn here instead of by fzf.
2//!
3//! Step 1 answered the questions this depends on, inside a real `tmux
4//! display-popup -E`, and the answers are worth keeping written down:
5//!
6//! - **The alternate screen nests inside a popup** and unwinds cleanly. That was
7//!   the one genuine unknown, since fzf runs `--height=100%` here and so says
8//!   nothing about it.
9//! - **Bracketed paste arrives as `Event::Paste`**, one event carrying its own
10//!   text, embedded line break included. This is the structural fix for the bug
11//!   that put `~/.tmux.conf.local` into live agent sessions: fzf reads a pasted
12//!   line break as Enter, and every guard against that is a heuristic. Here there
13//!   is nothing left to defeat. A pasted line break arrives as CR, not LF.
14//! - **Resize is an event**, not a reload.
15//! - **The window is sized by the POPUP**, 126x34 inside an 80% popup of a 160x45
16//!   terminal, so the rows are fitted to what they are actually drawn in rather
17//!   than to `tput cols` less a guess at fzf's chrome.
18//!
19//! Drawing goes to `/dev/tty` and input comes from there too (crossterm's
20//! use-dev-tty), which leaves stdout carrying exactly one line, the chosen pane
21//! id. atuin swaps file descriptors in its shell widget to get the same effect.
22//!
23//! Owning the state is most of what this buys. fzf has no state store, so the
24//! bash picker keeps its mode in the BORDER LABEL and reads it back out by
25//! matching words in it, carries the mode and the search flag through every
26//! reload as quoted arguments because a child spawned by a reload cannot be
27//! relied on to see the new label yet, and needs `--track --id-nth=2` so a reload
28//! does not drop the cursor. All of that is a field here.
29
30use std::cmp::Reverse;
31use std::collections::{HashMap, HashSet};
32use std::fs::{File, OpenOptions};
33use std::io::Write;
34use std::process::Command;
35use std::sync::mpsc::{Receiver, TryRecvError};
36use std::sync::Arc;
37use std::time::{Duration, Instant};
38
39use crossterm::event::{
40    self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
41    Event, KeyCode, KeyEventKind, KeyModifiers, KeyboardEnhancementFlags, MouseButton, MouseEvent,
42    MouseEventKind, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
43};
44use crossterm::{execute, terminal};
45use fuzzy_matcher::skim::SkimMatcherV2;
46use fuzzy_matcher::FuzzyMatcher;
47use ratatui::backend::CrosstermBackend;
48use ratatui::layout::{Constraint, Layout};
49use ratatui::style::{Color, Modifier, Style};
50use ratatui::text::{Line, Span};
51use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Wrap};
52use ratatui::Terminal;
53
54use crate::{ansi, rows};
55use taimux_core::{env, index};
56
57/// How close two clicks on one row have to be to read as a double-click, which
58/// is what accepts it. Long enough to be reachable without hurrying, short
59/// enough that two deliberate single clicks on the same row do not switch panes
60/// by accident. Claude Code's own stray-click guard sits in the same range.
61const DOUBLE_CLICK: Duration = Duration::from_millis(400);
62
63/// Which list is on screen. Tab steps round the cycle.
64///
65/// The first four are the same question asked of the same list, and the last
66/// three are not states at all: Background and Outdated ask different questions
67/// of it (what did this session leave RUNNING, what code is it running, rather
68/// than what is it doing), and Dead changes what the list IS. So they sit at the
69/// far end, in that order, rather than between two states of a running session.
70/// Background comes first of them because it is nearest to idle, where most of
71/// its rows are.
72#[derive(Clone, Copy, PartialEq, Eq, Debug)]
73pub enum Mode {
74    All,
75    Input,
76    Run,
77    Idle,
78    Background,
79    Outdated,
80    Dead,
81}
82
83impl Mode {
84    /// The state filter this mode passes to the layout; empty means every row.
85    ///
86    /// Outdated is empty because being behind is not a state: a session waiting,
87    /// working or idle can each be running code a self-update has replaced, and
88    /// that filter rides on `Input::outdated` instead. Background is empty for
89    /// the same reason, and rides on `Input::background`: a turn that left a
90    /// shell running is idle, and one started since can be working with that
91    /// shell still going.
92    fn filter(self) -> &'static str {
93        match self {
94            Mode::All => "",
95            Mode::Input => "input",
96            Mode::Run => "run",
97            Mode::Idle => "idle",
98            Mode::Background => "",
99            Mode::Outdated => "",
100            Mode::Dead => "dead",
101        }
102    }
103
104    fn label(self) -> &'static str {
105        match self {
106            Mode::All => "agent sessions",
107            Mode::Input => "waiting for an answer",
108            Mode::Run => "working",
109            Mode::Idle => "idle at the prompt",
110            Mode::Background => "running background work",
111            Mode::Outdated => "running outdated code",
112            Mode::Dead => "past sessions",
113        }
114    }
115
116    /// The name this mode is carried across a reopen by. Its own word rather
117    /// than the state filter, since Background, Outdated and All share that.
118    pub fn key(self) -> &'static str {
119        match self {
120            Mode::All => "all",
121            Mode::Input => "input",
122            Mode::Run => "run",
123            Mode::Idle => "idle",
124            Mode::Background => "background",
125            Mode::Outdated => "outdated",
126            Mode::Dead => "dead",
127        }
128    }
129
130    pub fn from_key(k: &str) -> Mode {
131        match k {
132            "input" => Mode::Input,
133            "run" => Mode::Run,
134            "idle" => Mode::Idle,
135            "background" => Mode::Background,
136            "outdated" => Mode::Outdated,
137            "dead" => Mode::Dead,
138            _ => Mode::All,
139        }
140    }
141
142    /// The ring Tab walks, and which stops are worth landing on.
143    ///
144    /// A stop with nothing that could ever be in it is left OUT rather than
145    /// reached and found empty: no cache of past sessions, no past stop, and
146    /// nothing installed to compare a version against, no outdated stop. An
147    /// empty list you can still land on is one you have to press Tab past every
148    /// time round.
149    ///
150    /// The background stop is always on, as the states are: it can be empty
151    /// right now, but nothing about the machine says it always will be.
152    fn cycle(ended: bool, outdated: bool) -> [(Mode, bool); 7] {
153        [
154            (Mode::All, true),
155            (Mode::Input, true),
156            (Mode::Run, true),
157            (Mode::Idle, true),
158            (Mode::Background, true),
159            (Mode::Outdated, outdated),
160            (Mode::Dead, ended),
161        ]
162    }
163
164    /// One step round the ring, forwards or back, skipping the stops that are
165    /// not on.
166    fn step(self, back: bool, ended: bool, outdated: bool) -> Mode {
167        let cycle = Mode::cycle(ended, outdated);
168        let n = cycle.len();
169        let at = cycle.iter().position(|(m, _)| *m == self).unwrap_or(0);
170        // `at + n - k` rather than `at - k`, so going backwards past the first
171        // stop stays in usize and wraps on the modulo like every other step.
172        (1..=n)
173            .map(|k| if back { at + n - k } else { at + k })
174            .map(|i| cycle[i % n])
175            .find(|(_, on)| *on)
176            .map(|(m, _)| m)
177            .unwrap_or(Mode::All)
178    }
179
180    /// One step round: all, waiting, working, idle, background, outdated,
181    /// ended, all.
182    fn next(self, ended: bool, outdated: bool) -> Mode {
183        self.step(false, ended, outdated)
184    }
185
186    /// The same ring the other way, which is what shift-tab walks.
187    ///
188    /// Worth binding because the ring is short and the stop you want is as
189    /// often the one behind you as the one ahead: overshooting "waiting for an
190    /// answer" by one used to cost four more presses to come back to.
191    fn prev(self, ended: bool, outdated: bool) -> Mode {
192        self.step(true, ended, outdated)
193    }
194
195    /// Whether this list has a date worth sorting it by, which is what binds
196    /// ctrl-s on it: when each session last said something.
197    ///
198    /// Two lists. The past one, whose rows are nothing BUT history, and the idle
199    /// one, where it answers "which of these did I leave waiting most recently".
200    /// On the others it would be noise: a session working or holding a question
201    /// is there because of what it is doing now, and all sessions at once is
202    /// several questions at the same time.
203    fn has_dates(self) -> bool {
204        matches!(self, Mode::Idle | Mode::Dead)
205    }
206}
207
208/// Where rows come from, and what does not change while the picker is open.
209///
210/// `fetch` is a closure rather than a string so ctrl-r and the refresh timer can
211/// ask again. `ended` is separate because the ended list is not the pane list
212/// filtered: it comes off the sessions cache and nothing in it has a pane at all.
213pub struct Source {
214    /// Shared and thread-safe because a refresh runs OFF the input loop: see
215    /// `start_refresh`. It was a plain closure until a sweep froze the picker
216    /// for the 85 seconds its restarts took, with no key accepted and nothing
217    /// on screen to say why.
218    pub fetch: Arc<dyn Fn() -> String + Send + Sync>,
219    /// The panes with a restart in flight, for the marker column, asked on the
220    /// same thread and just before `fetch`. The rows already come back held at
221    /// what they were (see `restarting` in core), so this only says WHICH rows
222    /// are held, which nothing in a row can.
223    pub restarting: Arc<dyn Fn() -> HashSet<String> + Send + Sync>,
224    /// The ended list stays synchronous: it is a read of one cache file, with no
225    /// fork in it, and it is what Tab's last stop shows the instant you land on
226    /// it. Nothing here has ever been slow, and making it async would mean
227    /// showing pane rows under the "past sessions" label while it arrived.
228    pub ended: Option<Box<dyn Fn() -> String>>,
229    pub cur: String,
230    /// Where the pane the picker was opened from IS, for the case where that
231    /// pane is not an agent session: `cur` then matches no row at all and these
232    /// are what the cursor is placed by instead. See `nearest`.
233    ///
234    /// Empty means "not known", which is what every entry point but `pick` hands
235    /// over, and the cursor then opens at the top of the list as it always did.
236    pub cur_cwd: String,
237    pub cur_target: String,
238    pub home: String,
239    pub newver: String,
240    /// The taimux script, for the two keys that act rather than navigate. Unset
241    /// means they are not bound, and the header then does not advertise them:
242    /// the header only ever says what is really there.
243    pub script: Option<String>,
244    /// Set only when the binding said so with `-e TAIMUX_POPUP=1`. It is what
245    /// allows the picker to close and reopen itself at a new size, which would
246    /// be wrong for a picker running inline in a pane: tmux resizes a PANE with
247    /// the client already, so there is nothing to do there and everything to
248    /// lose by guessing.
249    pub popup: bool,
250    /// What a previous instance was doing when the terminal grew under it.
251    pub state: State,
252}
253
254/// Which row to open on when the pane the picker was opened from is not an agent
255/// session, and so is not in the list at all.
256///
257/// Pressed from a shell, `cur` matches nothing, and the cursor used to land on
258/// the top of the list: a row chosen by whichever session tmux happens to list
259/// first, which is to say by nothing. The question it should answer is "which of
260/// these sessions is the one I am working on", and the best evidence for that is
261/// the DIRECTORY. A shell in `~/projects/web` and an agent in `~/projects/web`
262/// are the same piece of work; one in `~/projects/web/docs` very nearly is; one
263/// in `~/notes` is not.
264///
265/// So the working directory is the primary key and the tmux list only breaks its
266/// ties, which is the case where two sessions are equally close to the directory
267/// and the nearer pane is the likelier one. Ties in BOTH keep the list's own
268/// order, since `min_by_key` takes the first of equal minimums.
269fn nearest(rows: &[&rows::Row], cwd: &str, target: &str) -> Option<usize> {
270    rows.iter()
271        .enumerate()
272        .min_by_key(|(_, r)| {
273            let (shared, apart) = cwd_near(cwd, &r.cwd);
274            (Reverse(shared), apart, tmux_near(target, r))
275        })
276        .map(|(i, _)| i)
277}
278
279/// Path components, ignoring the empties a leading, doubled or trailing slash
280/// leaves, so `/a/b`, `/a/b/` and `//a/b` are one directory rather than three.
281fn comps(p: &str) -> Vec<&str> {
282    p.split('/').filter(|c| !c.is_empty()).collect()
283}
284
285/// How near two directories are: how much of the path they share from the root,
286/// then how many steps apart they are through the deepest directory they have in
287/// common. The same directory is `(n, 0)`, a subdirectory of it `(n, 1)`, a
288/// sibling `(n-1, 2)`.
289///
290/// Both halves are load-bearing, and in that order. Shared components first, so
291/// a session one level DOWN from the directory you are in beats one a level up:
292/// the deeper of the two is the more specific answer, and the parent is often
293/// just where several unrelated projects happen to live. Then the distance, so
294/// the directory itself beats a subdirectory of it.
295///
296/// Nothing in common answers `(0, 0)` rather than `(0, distance)`: the paths
297/// diverge at their first component, so the directory says nothing about which
298/// row is nearer, and ranking on the distance alone would put whichever session
299/// sits closest to the root in front for a reason nobody could read off the
300/// screen. The tie then falls through to the tmux list, which is the honest
301/// answer. Same for an unknown directory on either side, which is empty and so
302/// shares nothing with anything.
303fn cwd_near(cur: &str, row: &str) -> (usize, usize) {
304    let (a, b) = (comps(cur), comps(row));
305    let shared = a.iter().zip(b.iter()).take_while(|(x, y)| x == y).count();
306    if shared == 0 {
307        return (0, 0);
308    }
309    (shared, (a.len() - shared) + (b.len() - shared))
310}
311
312/// How near a row's pane is to the pane the picker was opened from, in the list
313/// tmux itself keeps: the same session first, nearest window and then nearest
314/// pane inside it, then anything else on this server, then another host, whose
315/// panes are not in this server's list at all and whose window numbers mean
316/// nothing here.
317fn tmux_near(cur: &str, r: &rows::Row) -> (u8, usize, usize) {
318    /// Somewhere on this server, but not near anything: a different session, or
319    /// a row that names no pane (an ended session's label is its age).
320    const ELSEWHERE: (u8, usize, usize) = (1, 0, 0);
321    if !r.host.is_empty() {
322        return (2, 0, 0);
323    }
324    let (Some((sess, win, pane)), Some((rsess, rwin, rpane))) =
325        (target_parts(cur), target_parts(&r.target))
326    else {
327        return ELSEWHERE;
328    };
329    if sess != rsess {
330        return ELSEWHERE;
331    }
332    (0, win.abs_diff(rwin), pane.abs_diff(rpane))
333}
334
335/// `session:window.pane`, split into the three things it names, or `None` for
336/// anything that is not one.
337fn target_parts(t: &str) -> Option<(&str, usize, usize)> {
338    let (sess, rest) = t.split_once(':')?;
339    let (win, pane) = rest.split_once('.')?;
340    Some((sess, win.parse().ok()?, pane.parse().ok()?))
341}
342
343/// Throw away what ratatui thinks is on the terminal, so the next draw repaints
344/// in full.
345///
346/// `resize` and NOT `Terminal::clear`, which is the obvious call and is a trap
347/// here: clear snapshots the cursor first, and the crossterm backend does that
348/// with `crossterm::cursor::position()`, which writes ESC[6n to the PROCESS's
349/// stdout rather than to the backend's writer. Stdout carries exactly one thing
350/// in this program, the chosen pane id, so anything using clear puts `[6n` where
351/// the caller reads the answer.
352///
353/// This was fixed once for ctrl-l and left in place for the two keys that hand
354/// the terminal to a child, which need it MORE: they always repaint, so they
355/// always leaked, and the list came back blank after every restart.
356fn repaint<B: ratatui::backend::Backend>(term: &mut Terminal<B>) {
357    if let Ok(size) = term.size() {
358        let _ = term.resize(size.into());
359    }
360}
361
362/// Run one of the two keys that act, with the terminal handed over.
363///
364/// Its output goes to **/dev/tty**, not to the picker's stdout. Inherited, the
365/// child's whole screen ends up in the one thing this program writes to stdout,
366/// the chosen pane id: measured, the caller of `taimux tui` got the sweep's
367/// plan, its prompt and its closing message, and then the pane id on the end.
368/// In a popup stdout happens to BE the tty, which is why it looked right there
369/// and was wrong everywhere else.
370/// Run a child that owns the terminal while it runs.
371///
372/// All THREE streams are pointed at the terminal, stdin included. The picker's
373/// own stdin is not the terminal (its stdout carries the chosen pane id, and it
374/// draws to /dev/tty for exactly that reason), so a child left to inherit it
375/// gets a stdin that is not where the person is typing, while its output goes
376/// somewhere else entirely. The child then reads its own /dev/tty to get around
377/// that, which works but means the parent hands over a terminal it has only
378/// half set up.
379fn act_child(script: &str, args: &[&str]) -> std::io::Result<std::process::ExitStatus> {
380    let mut c = Command::new(script);
381    c.args(args);
382    if let Ok(tty) = OpenOptions::new().write(true).open("/dev/tty") {
383        if let Ok(err) = tty.try_clone() {
384            c.stdout(tty).stderr(err);
385        }
386    }
387    if let Ok(inp) = OpenOptions::new().read(true).open("/dev/tty") {
388        c.stdin(inp);
389    }
390    c.status()
391}
392
393/// Raw mode, the alternate screen and bracketed paste, undone on the way out.
394///
395/// A guard rather than a pair of calls because every early return, `?` and panic
396/// has to restore the terminal: the failure mode is a shell left in raw mode with
397/// no echo, which is indistinguishable from a hung machine to whoever is looking
398/// at it. This is the part bash could never do properly, since a trap does not
399/// survive a kill.
400struct Guard {
401    out: File,
402    kitty: bool,
403    mouse: bool,
404}
405
406impl Guard {
407    fn new(kitty: bool) -> std::io::Result<Guard> {
408        let mut out = OpenOptions::new().write(true).open("/dev/tty")?;
409        terminal::enable_raw_mode()?;
410        // Mouse capture goes everywhere bracketed paste goes, including the
411        // suspend/resume pair below, or handing the terminal to a child would
412        // leave the picker with a dead wheel when it came back.
413        //
414        // fzf had this on by default and the port never asked for it, which is
415        // the same way Page Up and Page Down went missing: nothing referenced
416        // the behaviour, so nothing pointed at its absence. TAIMUX_MOUSE=0
417        // turns it off, for a terminal where capture costs more than it gives
418        // (it takes over drag-to-select, and tmux's own copy mode with it).
419        execute!(out, terminal::EnterAlternateScreen, EnableBracketedPaste)?;
420        let mouse = env::var("TAIMUX_MOUSE").is_none_or(|v| v != "0");
421        if mouse {
422            let _ = execute!(out, EnableMouseCapture);
423        }
424        if kitty {
425            // Makes a bare ESC arrive on its own rather than as the head of a
426            // possible chord. Only some terminals answer; the flags are harmless
427            // where they are ignored, and they also turn on key-release events,
428            // which is why the loop filters on KeyEventKind::Press.
429            let _ = execute!(
430                out,
431                PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
432            );
433        }
434        Ok(Guard { out, kitty, mouse })
435    }
436
437    /// Hand the terminal back so a child can own it, as fzf's `execute()` does.
438    fn suspend(&mut self) {
439        if self.mouse {
440            let _ = execute!(self.out, DisableMouseCapture);
441        }
442        let _ = execute!(
443            self.out,
444            DisableBracketedPaste,
445            terminal::LeaveAlternateScreen
446        );
447        let _ = terminal::disable_raw_mode();
448    }
449
450    fn resume(&mut self) {
451        let _ = terminal::enable_raw_mode();
452        // Wipe what the child drew, BEFORE going back to the alternate screen.
453        //
454        // The child owned the NORMAL screen while it had the terminal, so its
455        // last frame is still sitting there under the picker. Leaving the
456        // alternate screen on the way out then reveals it, and what you get,
457        // seconds after picking a row, is the sweep's "restart every outdated
458        // session" screen back on your terminal as if it had run again.
459        // Reported that way, and it is only ever a leftover.
460        //
461        // Nothing of the caller's is lost: this runs only after a child that
462        // cleared the screen for itself.
463        let _ = execute!(
464            self.out,
465            terminal::Clear(terminal::ClearType::All),
466            crossterm::cursor::MoveTo(0, 0),
467            terminal::EnterAlternateScreen,
468            EnableBracketedPaste
469        );
470        if self.mouse {
471            let _ = execute!(self.out, EnableMouseCapture);
472        }
473    }
474}
475
476impl Drop for Guard {
477    fn drop(&mut self) {
478        if self.kitty {
479            let _ = execute!(self.out, PopKeyboardEnhancementFlags);
480        }
481        self.suspend();
482    }
483}
484
485/// The columns a row is laid out for: the drawn area less the border and less the
486/// two the pointer takes. fzf reserves the same two and reports the rest in
487/// FZF_COLUMNS, a figure that only exists once fzf is already up, which is why
488/// the bash picker has to guess a width for its first render.
489fn row_width(area_width: u16) -> usize {
490    (area_width as usize).saturating_sub(4)
491}
492
493/// Under this many characters a term is in every transcript and a match would
494/// say nothing, so a short query filters on the row alone.
495fn search_min() -> usize {
496    env::var("TAIMUX_SEARCH_MIN")
497        .and_then(|v| v.parse().ok())
498        .unwrap_or(3)
499}
500
501/// Text search is on unless it is turned off, the same knob the bash picker
502/// reads. Note that it still starts OFF at the ctrl-t toggle; this only says
503/// whether the key does anything.
504fn search_enabled() -> bool {
505    env::on("TAIMUX_SEARCH")
506}
507
508fn sessions_enabled() -> bool {
509    env::on("TAIMUX_SESSIONS")
510}
511
512/// Following the terminal is on unless it is turned off. `0` leaves a popup at
513/// whatever size it opened with, which is what every version before this did.
514fn resize_enabled() -> bool {
515    env::on("TAIMUX_RESIZE")
516}
517
518/// The ended-sessions list, or nothing where the sessions cache is turned off.
519/// `Source.ended` being None is what takes that mode out of the Tab cycle, so
520/// the decision is made once, here.
521pub fn ended_source() -> Option<Box<dyn Fn() -> String>> {
522    sessions_enabled().then(|| Box::new(|| index::dead_rows(now())) as Box<dyn Fn() -> String>)
523}
524
525fn now() -> i64 {
526    std::time::SystemTime::now()
527        .duration_since(std::time::UNIX_EPOCH)
528        .map(|d| d.as_secs() as i64)
529        .unwrap_or(0)
530}
531
532/// The rows the query keeps: best match first, or `by_date` newest first by
533/// when each session last said something.
534///
535/// Terms are ANDed and their scores summed, which is fzf's extended-search
536/// default rather than one fuzzy match over the whole query. With no query the
537/// list keeps its own order; the sort is stable, so ties do too.
538///
539/// By date sorts on each row's `since`, so it holds with no query as well: the
540/// idle list comes in tmux order and the past list newest first already. A row
541/// that cannot say when it last spoke (an agent that reports nothing, a host
542/// whose taimux predates the field) goes after every row that can, keeping the
543/// order it came in.
544///
545/// Under a query, by date is NOT fzf's `--no-sort`, which leaves every match
546/// where it stands. That was tried against the real history and is the version
547/// nobody wants: the letters of `ha-bert`, in order but scattered, are in a dozen
548/// rows that have nothing to do with it, and the ranking was all that kept those
549/// under the rows that actually SAY it. With it gone, the top of the list was all
550/// noise. So the rows holding every term as typed come first, newest first, and
551/// the loose matches follow, newest first too. The rows are the same either way;
552/// only their order changes.
553///
554/// The haystack is the row's PLAIN text: fzf is handed `--ansi` and has to parse
555/// our own colours back out to match on them, which is work this does not do.
556fn filter(list: &[rows::Row], query: &str, matcher: &SkimMatcherV2, by_date: bool) -> Vec<usize> {
557    // Newest first, and `None` after every date, since it is the smallest.
558    let newest = |i: usize| Reverse(list[i].since);
559    let terms: Vec<&str> = query.split_whitespace().collect();
560    if terms.is_empty() {
561        let mut all: Vec<usize> = (0..list.len()).collect();
562        if by_date {
563            all.sort_by_key(|&i| newest(i));
564        }
565        return all;
566    }
567    // Folded, as the matcher ignores case too.
568    let folded: Vec<String> = terms.iter().map(|t| t.to_lowercase()).collect();
569    let mut kept: Vec<(i64, bool, usize)> = Vec::new();
570    for (i, r) in list.iter().enumerate() {
571        let hay = r.plain();
572        let mut total = 0i64;
573        let mut all = true;
574        for t in &terms {
575            match matcher.fuzzy_match(&hay, t) {
576                Some(s) => total += s,
577                None => {
578                    all = false;
579                    break;
580                }
581            }
582        }
583        if all {
584            let loose = by_date && {
585                let low = hay.to_lowercase();
586                !folded.iter().all(|t| low.contains(t.as_str()))
587            };
588            kept.push((total, loose, i));
589        }
590    }
591    if by_date {
592        kept.sort_by_key(|&(_, loose, i)| (loose, newest(i)));
593    } else {
594        kept.sort_by_key(|&(score, _, _)| Reverse(score));
595    }
596    kept.into_iter().map(|(_, _, i)| i).collect()
597}
598
599/// What the picker says it can do. Only what is really bound: a header promising
600/// a key that does nothing is worse than a shorter one.
601///
602/// `by_date` is None on every list but the idle and past ones, the two with a
603/// date to sort by and so the only ones ctrl-s is bound on.
604fn header(
605    script: bool,
606    ended: bool,
607    search_key: bool,
608    search_on: bool,
609    by_date: Option<bool>,
610) -> String {
611    let mut h = String::from("enter: switch");
612    if ended {
613        h.push_str("/resume");
614    }
615    h.push_str("   tab: filter   ctrl-r: refresh   ctrl-/: preview");
616    if search_key {
617        h.push_str(if search_on {
618            "   ctrl-t: search text (on)"
619        } else {
620            "   ctrl-t: search text"
621        });
622    }
623    match by_date {
624        Some(true) => h.push_str("   ctrl-s: sort by date (on)"),
625        Some(false) => h.push_str("   ctrl-s: sort by date"),
626        None => {}
627    }
628    if script {
629        // "outdated" and not "stale", which it said until the list of those rows
630        // got a Tab stop of its own: two words for one thing on the same screen
631        // reads as two different things.
632        h.push_str("   ctrl-x: restart   ctrl-o: hand off   f8: restart all outdated");
633    }
634    h
635}
636
637/// The bottom-right stamp: which taimux drew this list.
638///
639/// Worth a permanent corner of the chrome because the answer is not obvious from
640/// anywhere else. The picker is a popup launched by a tmux binding, one binary
641/// per host, and a self-update swaps the launcher under a running tmux server
642/// without touching the panes: the same keypress can therefore draw a different
643/// version tomorrow, and until now nothing on screen said which. It is the crate
644/// version, the same string `taimux version` prints, so a row's `claude 2.1.229`
645/// and this cannot be confused for each other: this one is named.
646fn version_tag() -> String {
647    format!(" taimux {} ", env!("CARGO_PKG_VERSION"))
648}
649
650/// …but only where the bottom border can carry it AND the count.
651///
652/// ratatui gives a right-aligned title precedence over a left-aligned one, so
653/// without this the stamp eats the count on a narrow window: measured at 20
654/// columns it left ` 5/`, and at 16 the count was gone altogether. That is the
655/// priority backwards. The count is live and read constantly, the stamp is
656/// reference read once after an update, so the stamp is what gives way.
657///
658/// `+ 2` is the two corner characters the border spends whatever else happens.
659fn room_for_tag(width: u16, count: &str) -> bool {
660    width as usize >= count.chars().count() + version_tag().chars().count() + 2
661}
662
663/// What to say where the rows would be, when there are none.
664///
665/// Four different silences, and they mean different things: nothing running at
666/// all, nothing in the state you are filtering on, nothing matching what you
667/// typed, and no ended sessions recorded yet. Saying which is the whole point,
668/// since the picker used to say nothing and simply close.
669///
670/// `search_hint` is whether ctrl-t would search what was said and is not doing
671/// so here, which is when a query that matches no row may still be in a
672/// transcript. A URL pasted into the past list with its search off found nothing
673/// and said nothing about why, which is exactly the moment to name the key.
674///
675/// `live_hits` is how many sessions still open in a pane the same query matches,
676/// counted only where the past list has nothing of its own (see `App::live_hits`).
677/// A claude session open in a pane is left out of the past list, so the session a
678/// pasted merge request URL came from sat one Tab away while this list said
679/// "Nothing matches" and no more, and the search was given up as a miss.
680fn empty_note(
681    mode: Mode,
682    query: &str,
683    scanning: bool,
684    nothing_scanned: bool,
685    ended: bool,
686    search_hint: bool,
687    live_hits: usize,
688) -> Vec<Line<'static>> {
689    let mut lines: Vec<String> = Vec::new();
690    if scanning {
691        // The first scan is off the loop like every other, so this is what a
692        // popup shows for the ~90ms it usually takes, and what it keeps showing
693        // instead of going blank when something makes it slow.
694        lines.push("Looking for agent sessions…".into());
695        lines.push(String::new());
696        lines.push("Esc closes this.".into());
697        return lines
698            .into_iter()
699            .map(|l| Line::from(format!("  {}", l)))
700            .collect();
701    }
702    if !query.is_empty() {
703        lines.push(format!("Nothing matches {}", query));
704        if search_hint {
705            lines.push("ctrl-t searches what was said in them too.".into());
706        }
707        // Tab, because the past list is the last stop on the ring and the next
708        // stop round lists every live session.
709        match live_hits {
710            0 => {}
711            1 => lines.push("A session still open in a pane matches it: Tab shows it.".into()),
712            n => lines.push(format!(
713                "{} sessions still open in panes match it: Tab shows them.",
714                n
715            )),
716        }
717        lines.push("ctrl-u clears it.".into());
718    } else if mode == Mode::Dead {
719        lines.push("No past conversations have been found here yet.".into());
720        lines.push("They are remembered as sessions come and go.".into());
721    } else if nothing_scanned {
722        lines.push("No agent sessions on this machine.".into());
723        lines.push(
724            if ended {
725                "Nothing is running one. Tab reaches the conversations that ended."
726            } else {
727                "Nothing is running one."
728            }
729            .into(),
730        );
731    } else {
732        lines.push(format!("Nothing is {} right now.", mode.label()));
733        lines.push("Tab moves on to the next list.".into());
734    }
735    lines.push(String::new());
736    lines.push("Esc closes this.".into());
737    lines
738        .into_iter()
739        .map(|l| Line::from(format!("  {}", l)))
740        .collect()
741}
742
743/// The border label: which list and in what order, whether the timer and text
744/// search are on, and whether a refresh is taking long enough to be worth
745/// mentioning.
746fn label(mode: Mode, by_date: bool, live: bool, search: bool, refreshing: bool) -> String {
747    let mut s = format!(" {}", mode.label());
748    // Straight after the name, since it says what order that list is in. It is
749    // a setting, like ⌕, so it shows whether a query is typed or not: a label
750    // that came and went as you typed would read as the order changing under you.
751    if by_date {
752        s.push_str(" · by date");
753    }
754    if live {
755        s.push_str(" · live");
756    }
757    if search {
758        s.push_str(" · ⌕");
759    }
760    // Last, and only after a second: on a healthy machine the answer is back
761    // before the next draw, so a label that flashed on every tick would be noise
762    // about nothing. It is here for the case where the list is NOT arriving, so
763    // that a picker waiting on a slow scan reads as busy rather than as dead.
764    if refreshing {
765        s.push_str(" · refreshing");
766    }
767    s.push(' ');
768    s
769}
770
771/// A captured screen and when it was taken.
772///
773/// The preview is redrawn on every tick and every keypress, and capturing a pane
774/// per redraw would be a fork per keystroke. Cached by pane, so it costs one
775/// capture per row the cursor lands on, per TTL. Short on purpose: a preview is
776/// read to see what a session is doing NOW, and a stale screen is worse than a
777/// slow one.
778const PREVIEW_TTL: Duration = Duration::from_millis(750);
779
780/// …and longer for one that costs an ssh. The remote screen is no fresher for
781/// being asked more often, since the fetch itself is the slow part.
782const REMOTE_TTL: Duration = Duration::from_secs(3);
783
784struct App {
785    src: Source,
786    matcher: SkimMatcherV2,
787    mode: Mode,
788    /// Typing searches what sessions SAID, not only what their rows show, in the
789    /// lists of live sessions. On by default since 2026-09-24, Patrick's call,
790    /// after it was off for as long as the bash picker existed. The reason it
791    /// HAD to be off (a paste read as Enter) went with fzf, see the module
792    /// comment, and what was left was a default that made the one search people
793    /// reach for, a link or an error string, find nothing until ctrl-t.
794    search: bool,
795    /// The same, for the past list, which is where it went on first: a pasted
796    /// URL matched nothing there while rses, which always searched content,
797    /// found the very sessions it came from. Each list keeps its own switch, so
798    /// ctrl-t to jump by name among the live sessions leaves the history
799    /// searching what was said.
800    search_past: bool,
801    /// Order the idle and past lists by when each session last said something,
802    /// newest first, rather than in their own order or ranked best match first
803    /// (loose matches still go last, see `filter`). Only those two lists read
804    /// it, being the ones with a date to go by, and it holds across Tab as
805    /// `search` does.
806    by_date: bool,
807    preview: bool,
808    query: String,
809    width: usize,
810    /// The pane rows, as the last scan brought them back.
811    tsv: String,
812    /// The past list's rows, as the sessions cache last gave them.
813    ///
814    /// Its own buffer because it is its own list, not the panes filtered. The
815    /// two used to share one, and that is how a scan still out when Tab reached
816    /// this list landed on top of it: "past sessions" showed live panes until
817    /// the next tick, and going back the other way drew the past rows under the
818    /// live label until a scan came back.
819    past: String,
820    all: Vec<rows::Row>,
821    view: Vec<usize>,
822    sel: usize,
823    shot: Option<(String, Instant, String)>,
824    /// How far the preview is scrolled from its default view, in rows, negative
825    /// towards the start of the body.
826    poff: i32,
827    /// The row `poff` was measured against. Comparing it in `preview()` resets
828    /// the offset on every way the cursor can move (a key, the wheel, a click, a
829    /// rebuild, the refresh timer) from ONE place, rather than needing each of
830    /// those to remember to do it. An offset carried onto another row is a lie:
831    /// it was measured against a different session's screen.
832    poff_for: String,
833    /// A refresh running on a worker thread, and when it started.
834    ///
835    /// The picker used to call the row source straight from the input loop, so
836    /// for as long as that took there was no draw and no key: a refresh that
837    /// normally costs 90ms froze the whole picker for 85 SECONDS after an F8
838    /// sweep, showing the sweep's last screen the entire time, with Esc, ctrl-c
839    /// and even tmux's own F1 all apparently dead. Nothing about that told its
840    /// owner it was alive.
841    ///
842    /// One at a time: the timer must not stack refreshes on a machine where they
843    /// take longer than the interval, which is exactly the machine this matters
844    /// on.
845    pending: Option<Receiver<Refresh>>,
846    pending_since: Instant,
847    /// The client as of the last refresh, for the resize check.
848    client: Option<(String, (u16, u16))>,
849    /// Panes with a restart in flight, as of the last refresh.
850    ///
851    /// Only the marker column reads it. Holding the ROW is the scan's job: a
852    /// restart takes the session away for a second or so, and the pane used to
853    /// drop out of the list for it and come back, with every row below it
854    /// moving up and down again. This picker held the one row ctrl-x was
855    /// pressed on, from what it had on screen, and nothing else held anything:
856    /// an F8 sweep blinked out every row it touched. The restart now writes the
857    /// row down itself and the scan lists it from there, for every list.
858    restarting: HashSet<String>,
859    /// How many live sessions the query matches, while the past list is on
860    /// screen and matches none: what its empty note points at. Counted when the
861    /// query is applied rather than when the note is drawn, since a draw runs on
862    /// every tick and this lays out the live rows and reads their index files.
863    live_hits: usize,
864}
865
866impl App {
867    /// The preview for the row under the cursor, in two parts: a header saying
868    /// exactly where the session is, and the body to show under it.
869    ///
870    /// Split rather than concatenated so the header can be PINNED while the body
871    /// scrolls. The third value says where the body's default view sits: a live
872    /// pane is anchored at the BOTTOM, because what a session is doing is the
873    /// last thing on its screen, while an ended conversation reads from the top.
874    /// One offset then means the same thing for both, "rows towards the start",
875    /// and the clamp does the rest.
876    ///
877    /// The header comes off the row rather than out of a `tmux display-message`,
878    /// which is a fork the bash preview pays every time the cursor moves.
879    fn preview(&mut self) -> (Vec<Line<'static>>, Vec<Line<'static>>, bool) {
880        let Some(r) = self.view.get(self.sel).map(|&i| &self.all[i]) else {
881            return (Vec::new(), Vec::new(), false);
882        };
883        let (id, target, cwd, host) = (
884            r.pane_id.clone(),
885            r.target.clone(),
886            r.cwd.clone(),
887            r.host.clone(),
888        );
889        if self.poff_for != id {
890            self.poff = 0;
891            self.poff_for = id.clone();
892        }
893        // Where the words you typed turn up in what this session actually SAID.
894        // The row has room for one window of context; this has room for several,
895        // so the preview is where you find out whether the hit is the one you
896        // were after before jumping to it.
897        let mut out: Vec<Line<'static>> = Vec::new();
898        let mut body: Vec<Line<'static>> = Vec::new();
899        if self.searching() && self.query.chars().count() >= search_min() {
900            let hits = index::preview_match(
901                &id,
902                &index::Query::new(&self.query),
903                env::var("TAIMUX_SEARCH_PREVIEW")
904                    .and_then(|v| v.parse().ok())
905                    .unwrap_or(4),
906            );
907            for h in hits {
908                out.push(Line::from(vec![
909                    Span::styled("⌕ ", Style::default().fg(Color::Yellow)),
910                    Span::raw(h),
911                ]));
912            }
913            if !out.is_empty() {
914                out.push(Line::from(""));
915            }
916        }
917        out.push(Line::from(vec![
918            Span::styled(
919                target,
920                Style::default()
921                    .fg(Color::Cyan)
922                    .add_modifier(Modifier::BOLD),
923            ),
924            Span::raw("   "),
925            Span::styled(cwd, Style::default().add_modifier(Modifier::DIM)),
926        ]));
927        out.push(Line::from(Span::styled(
928            "─".repeat(44),
929            Style::default().fg(Color::DarkGray),
930        )));
931        out.push(Line::from(""));
932
933        // A past conversation has no screen to capture: what it has is the
934        // last things that were said in it.
935        if id.starts_with("dead:") {
936            if id == "dead:!" {
937                body.push(Line::from(Span::styled(
938                    "the list is still being built",
939                    Style::default().fg(Color::DarkGray),
940                )));
941                return (out, body, false);
942            }
943            let Some((agent, key)) = taimux_core::index::split_past_id(&id) else {
944                body.push(Line::from(Span::styled(
945                    "that row does not name a conversation",
946                    Style::default().fg(Color::Red),
947                )));
948                return (out, body, false);
949            };
950            // A conversation kept in a database has no file to be missing, and
951            // its store answered when the list was built.
952            if key.starts_with('/') && !std::path::Path::new(key).is_file() {
953                body.push(Line::from(Span::styled(
954                    "this conversation is no longer on disk",
955                    Style::default().fg(Color::Red),
956                )));
957                return (out, body, false);
958            }
959            let want = env::var("TAIMUX_DEAD_TURNS")
960                .and_then(|v| v.parse().ok())
961                .unwrap_or(6);
962            let turns = taimux_core::agents::turns(agent, key, want);
963            if turns.is_empty() {
964                body.push(Line::from(Span::styled(
965                    "(nothing was said in this one)",
966                    Style::default().fg(Color::DarkGray),
967                )));
968            }
969            for t in turns {
970                // Two lines a turn is enough to recognise one, and the preview
971                // pane is short.
972                let cap = self.width.max(20) * 2;
973                let what = if t.text.chars().count() > cap {
974                    format!("{}…", t.text.chars().take(cap).collect::<String>())
975                } else {
976                    t.text
977                };
978                let (mark, st) = if t.you {
979                    (
980                        "❯ ",
981                        Style::default()
982                            .fg(Color::Cyan)
983                            .add_modifier(Modifier::BOLD),
984                    )
985                } else {
986                    ("  ", Style::default().add_modifier(Modifier::DIM))
987                };
988                body.push(Line::from(vec![
989                    Span::styled(mark, st),
990                    Span::styled(what, st),
991                ]));
992                body.push(Line::from(""));
993            }
994            // From the top: a conversation reads forwards, and its opening is
995            // already on the row as the title, so what you want first is what
996            // came after it.
997            return (out, body, false);
998        }
999        // capture-pane only works where the pane IS, so a session on another host
1000        // renders its own. That is an ssh, and the script already knows how to
1001        // make it: which taimux is over there, the bound it runs under, and what
1002        // to say when a host stops answering between the list and the cursor
1003        // landing on its row. Shelling out to it is one fork per cursor landing,
1004        // which is what fzf's preview cost anyway, and it beats keeping a second
1005        // copy of that knowledge here.
1006        if !host.is_empty() {
1007            let Some(script) = self.src.script.clone() else {
1008                body.push(Line::from(Span::styled(
1009                    format!("on {}: no taimux to ask", host),
1010                    Style::default().fg(Color::DarkGray),
1011                )));
1012                return (out, body, false);
1013            };
1014            let fresh = matches!(&self.shot, Some((k, at, _))
1015                                 if *k == id && at.elapsed() < REMOTE_TTL);
1016            if !fresh {
1017                let text = Command::new(&script)
1018                    .args(["preview", &id])
1019                    .output()
1020                    .ok()
1021                    .filter(|o| o.status.success())
1022                    .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
1023                    .unwrap_or_default();
1024                self.shot = Some((id.clone(), Instant::now(), text));
1025            }
1026            let text = self
1027                .shot
1028                .as_ref()
1029                .map(|(_, _, s)| s.clone())
1030                .unwrap_or_default();
1031            body.extend(tail(&text, usize::MAX));
1032            return (out, body, true);
1033        }
1034        let fresh = matches!(&self.shot, Some((k, at, _))
1035                             if *k == id && at.elapsed() < PREVIEW_TTL);
1036        if !fresh {
1037            self.shot = Some((
1038                id.clone(),
1039                Instant::now(),
1040                taimux_core::tmux::capture_coloured(&id).unwrap_or_default(),
1041            ));
1042        }
1043        let screen = self
1044            .shot
1045            .as_ref()
1046            .map(|(_, _, s)| s.clone())
1047            .unwrap_or_default();
1048        // The WHOLE screen, and the renderer takes the last screenful of it, so
1049        // there is something above the default view to scroll into. The padding
1050        // to the pane height is trimmed here either way, or the tail would be
1051        // all padding: the same trap that made every waiting session read as
1052        // idle when the state reader was ported.
1053        body.extend(tail(&screen, usize::MAX));
1054        // Anchored at the bottom: what a session is doing is the last thing on
1055        // its screen.
1056        (out, body, true)
1057    }
1058}
1059
1060/// The last `room` lines of a captured screen, which is where what a session is
1061/// doing lives.
1062///
1063/// The trailing blanks come off first. `capture-pane` pads its output to the pane
1064/// height, so a tail taken without trimming is all padding: that is the exact
1065/// trap that made every session waiting for an answer read as idle when the state
1066/// reader was ported, and it is the same capture being read here.
1067fn tail(screen: &str, room: usize) -> Vec<Line<'static>> {
1068    let mut lines = ansi::to_lines(screen);
1069    while lines
1070        .last()
1071        .is_some_and(|l| l.spans.iter().all(|s| s.content.trim().is_empty()))
1072    {
1073        lines.pop();
1074    }
1075    let over = lines.len().saturating_sub(room);
1076    lines.drain(..over);
1077    lines
1078}
1079
1080/// What a refresh brings back: the rows, how long they took, and what the time
1081/// went on.
1082struct Refresh {
1083    tsv: String,
1084    restarting: HashSet<String>,
1085    took: Duration,
1086    /// Empty unless something forked; see `stat`.
1087    spent: String,
1088    /// The client this popup is on, asked for only when we are in a popup that
1089    /// may reopen itself, and only when tmux can name it without guessing. It
1090    /// rides along with the refresh because that already runs off the input
1091    /// loop: a resize check of its own would be another fork on it.
1092    client: Option<(String, (u16, u16))>,
1093}
1094
1095/// Our own session, out of `$TMUX`: socket, server pid, session id.
1096fn own_session() -> Option<String> {
1097    let tmux = std::env::var("TMUX").ok()?;
1098    let id = tmux.split(',').nth(2)?.trim();
1099    (!id.is_empty()).then(|| format!("${}", id))
1100}
1101
1102/// The client this popup is drawn on, and its size, or None when that cannot be
1103/// answered without guessing.
1104///
1105/// **Asking tmux for `#{client_width}` with no target is the bug this exists to
1106/// avoid.** An untargeted query answers for whichever client tmux considers
1107/// current, and Patrick routinely has two attached to one session: a 213-column
1108/// desktop and a 46-column phone. A picker opened on the PHONE then measured
1109/// itself against the desktop, decided a 44-column popup had been outgrown,
1110/// closed itself, and reopened on the desktop over whatever pane was there. That
1111/// is what "stuck after selecting another session" turned out to be: a popup
1112/// arriving unbidden on the other client.
1113///
1114/// So the client has to be unambiguous. One client on our session is our client.
1115/// Two, and nothing here can tell which of them the popup belongs to (tmux
1116/// exposes no format for it, and `display-popup -e` does not expand formats, so
1117/// the binding cannot pass it either), which is exactly when this must do
1118/// nothing at all.
1119fn own_client() -> Option<(String, (u16, u16))> {
1120    let session = own_session()?;
1121    let out = taimux_core::tmux::ask(&[
1122        "list-clients",
1123        "-t",
1124        &session,
1125        "-F",
1126        "#{client_tty} #{client_width} #{client_height}",
1127    ])?;
1128    let mut lines = out.lines().filter(|l| !l.trim().is_empty());
1129    let only = lines.next()?;
1130    if lines.next().is_some() {
1131        return None; // more than one client: whose popup is this?
1132    }
1133    let mut f = only.split_whitespace();
1134    let (tty, w, h) = (f.next()?, f.next()?.parse().ok()?, f.next()?.parse().ok()?);
1135    (w > 0 && h > 0).then(|| (tty.to_string(), (w, h)))
1136}
1137
1138/// Could this popup usefully be bigger than it is?
1139///
1140/// tmux SHRINKS a popup to fit a client that got smaller and grows it back up to
1141/// the size it was asked for, so the only case left over is a terminal that grew
1142/// PAST that: a popup opened on a phone in portrait stays portrait-width after
1143/// the rotation, at 63% of a screen it was told to take 80% of. Measured, both
1144/// directions, before any of this was written.
1145///
1146/// `slack` is what keeps it from firing on a rounding difference of a column or
1147/// two, which would close and reopen the popup for nothing.
1148fn outgrown(ours: (u16, u16), client: (u16, u16), slack: u16) -> bool {
1149    let (pw, ph) = crate::install::popup_geometry(client.0 as usize);
1150    // A popup's usable area is its geometry less the border it draws.
1151    let want_w = (client.0 as u32 * pw as u32 / 100).saturating_sub(2) as u16;
1152    let want_h = (client.1 as u32 * ph as u32 / 100).saturating_sub(2) as u16;
1153    want_w > ours.0.saturating_add(slack) || want_h > ours.1.saturating_add(slack)
1154}
1155
1156/// Everything the picker has to carry across a reopen, so a resize costs you
1157/// your popup's geometry and nothing else.
1158///
1159/// Its Default is an ORDINARY open, not an empty struct: `preview` is on unless
1160/// something turned it off, and deriving Default silently opened every picker
1161/// with the preview hidden, which showed up as the list being twice as tall as
1162/// the page keys expected.
1163#[derive(Debug, PartialEq, Eq)]
1164pub struct State {
1165    pub query: String,
1166    pub mode: &'static str,
1167    pub search: bool,
1168    /// Whether the past list searches what was said, which it does unless
1169    /// ctrl-t turned that off there.
1170    pub search_past: bool,
1171    pub by_date: bool,
1172    pub preview: bool,
1173    /// The row the cursor was on, by pane id.
1174    pub on: String,
1175    /// The client whose popup this was, so the reopen goes to THAT one rather
1176    /// than to whichever tmux considers current a moment later.
1177    pub client: String,
1178}
1179
1180impl Default for State {
1181    fn default() -> Self {
1182        State {
1183            query: String::new(),
1184            mode: "all",
1185            search: true,
1186            search_past: true,
1187            by_date: false,
1188            preview: true,
1189            on: String::new(),
1190            client: String::new(),
1191        }
1192    }
1193}
1194
1195/// How the picker finished.
1196pub enum Outcome {
1197    Chosen(String),
1198    Aborted,
1199    /// The terminal grew: reopen at the geometry the binding would use now,
1200    /// with this state. Only ever returned from a popup that was told it is one.
1201    Resize(State),
1202}
1203
1204/// How slow a refresh has to be before it is written down.
1205///
1206/// Two seconds is well past anything healthy here (a full scan of 171 panes is
1207/// 90ms) and well short of the freeze that prompted this, so the log stays empty
1208/// on a normal day and names the culprit on a bad one.
1209fn slow_after() -> Duration {
1210    Duration::from_secs_f32(
1211        env::var("TAIMUX_SLOW_REFRESH")
1212            .and_then(|v| v.parse().ok())
1213            .unwrap_or(2.0),
1214    )
1215}
1216
1217/// A refresh that took too long, written where the sweep already sends you.
1218///
1219/// Appended rather than printed: the picker owns the screen, and the whole point
1220/// is that this happens while nobody can see anything.
1221fn log_slow(r: &Refresh) {
1222    let line = format!(
1223        "--- {} picker refresh took {:.1}s{}{}\n",
1224        taimux_core::log::stamp(),
1225        r.took.as_secs_f32(),
1226        if r.spent.is_empty() { "" } else { ": " },
1227        r.spent
1228    );
1229    let path = taimux_core::paths::runtime_dir().join("restart.log");
1230    if let Some(d) = path.parent() {
1231        let _ = std::fs::create_dir_all(d);
1232    }
1233    if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(&path) {
1234        let _ = f.write_all(line.as_bytes());
1235    }
1236}
1237
1238impl App {
1239    /// Rows now, on this thread. Startup and the ended list only: everything the
1240    /// loop does goes through `start_refresh` instead.
1241    fn fetch(&mut self) {
1242        if self.mode == Mode::Dead {
1243            self.past = self.src.ended.as_ref().map(|f| f()).unwrap_or_default();
1244        } else {
1245            self.restarting = (self.src.restarting)();
1246            self.tsv = (self.src.fetch)();
1247        }
1248    }
1249
1250    /// Ask for rows on a worker thread, leaving the loop free to draw and to
1251    /// read keys while the answer is on its way.
1252    ///
1253    /// The ended list is fetched inline, since it is a cache read with no fork in
1254    /// it and swapping it in late would mean drawing pane rows under the "ended
1255    /// sessions" label.
1256    fn start_refresh(&mut self) {
1257        if self.mode == Mode::Dead {
1258            self.fetch();
1259            self.rebuild();
1260            return;
1261        }
1262        if self.pending.is_some() {
1263            return;
1264        }
1265        let f = self.src.fetch.clone();
1266        let held = self.src.restarting.clone();
1267        let watch = self.src.popup;
1268        let (tx, rx) = std::sync::mpsc::channel();
1269        std::thread::spawn(move || {
1270            taimux_core::stat::reset();
1271            let at = Instant::now();
1272            // Before the scan, not after. A restart that ends between the two
1273            // leaves the session's new row marked for one refresh; the other
1274            // way round, a row the scan held could come back unmarked.
1275            let restarting = held();
1276            let tsv = f();
1277            let _ = tx.send(Refresh {
1278                tsv,
1279                restarting,
1280                took: at.elapsed(),
1281                spent: taimux_core::stat::report(),
1282                client: watch.then(own_client).flatten(),
1283            });
1284        });
1285        self.pending = Some(rx);
1286        self.pending_since = Instant::now();
1287    }
1288
1289    /// Take a refresh that has landed. True when the list changed, which is what
1290    /// tells the loop to rebuild.
1291    ///
1292    /// A thread that died without sending (a panic in the row source) drops the
1293    /// sender, and that arrives here as Disconnected: the refresh is simply
1294    /// forgotten and the next tick tries again, rather than the picker waiting
1295    /// on it forever.
1296    fn take_refresh(&mut self) -> bool {
1297        let Some(rx) = &self.pending else {
1298            return false;
1299        };
1300        match rx.try_recv() {
1301            Ok(r) => {
1302                if r.took >= slow_after() {
1303                    log_slow(&r);
1304                }
1305                self.client = r.client;
1306                // Pane rows, whichever list is on screen. One that lands under
1307                // the past list goes where it belongs and waits for the Tab back.
1308                self.tsv = r.tsv;
1309                self.restarting = r.restarting;
1310                self.pending = None;
1311                true
1312            }
1313            Err(TryRecvError::Empty) => false,
1314            Err(TryRecvError::Disconnected) => {
1315                self.pending = None;
1316                false
1317            }
1318        }
1319    }
1320
1321    /// Has a refresh been out long enough to be worth saying so on the border?
1322    ///
1323    /// Not from the first millisecond: every tick would flicker the label on a
1324    /// healthy machine, where the answer is back before the next draw.
1325    fn refreshing(&self) -> bool {
1326        self.pending.is_some() && self.pending_since.elapsed() > Duration::from_secs(1)
1327    }
1328
1329    /// The snippets the query earns in `mode`'s list, or none.
1330    ///
1331    /// **The "at least TAIMUX_SEARCH_MIN characters" gate lives here, not in the
1332    /// layout**, exactly as it does in bash: under three characters a term is in
1333    /// every transcript and a match would say nothing. Handing the layout a
1334    /// snippet map for a one-letter query turns every row into a search hit.
1335    fn snippets(&self, mode: Mode) -> HashMap<String, String> {
1336        if !self.searching_in(mode) || self.query.chars().count() < search_min() {
1337            return HashMap::new();
1338        }
1339        // Only the conversations this list can show: see `index::Scope`.
1340        let scope = if mode == Mode::Dead {
1341            index::Scope::Past
1342        } else {
1343            index::Scope::Live
1344        };
1345        index::snippets(&index::Query::new(&self.query), scope)
1346    }
1347
1348    /// Whether typing searches what was said, for the list on screen.
1349    fn searching(&self) -> bool {
1350        self.searching_in(self.mode)
1351    }
1352
1353    /// …and for any list: the past list has its own switch, on by default, and
1354    /// every other list shares one.
1355    fn searching_in(&self, mode: Mode) -> bool {
1356        if mode == Mode::Dead {
1357            self.search_past
1358        } else {
1359            self.search
1360        }
1361    }
1362
1363    /// ctrl-t: the list on screen's own switch. The past list and the live ones
1364    /// default differently, so turning one off must not turn the other on.
1365    fn toggle_search(&mut self) {
1366        if self.mode == Mode::Dead {
1367            self.search_past = !self.search_past;
1368        } else {
1369            self.search = !self.search;
1370        }
1371        self.rebuild();
1372    }
1373
1374    /// Whether the list on screen is in date order, newest first, rather than in
1375    /// its own order or ranked best match first: the idle or past list with
1376    /// ctrl-s on, and nothing else.
1377    fn dated(&self) -> bool {
1378        self.by_date && self.mode.has_dates()
1379    }
1380
1381    /// Re-lay the rows out and re-apply the query, putting the cursor back on the
1382    /// same SESSION rather than the same index. That is what `--track --id-nth=2`
1383    /// buys fzf, and owning the state makes it a lookup.
1384    fn rebuild(&mut self) {
1385        let on = self.selected().map(|r| r.pane_id.clone());
1386        self.all = self.layout(self.mode);
1387        self.apply_query();
1388        self.sel = on
1389            .and_then(|id| self.view.iter().position(|&i| self.all[i].pane_id == id))
1390            .unwrap_or(0);
1391        self.clamp();
1392    }
1393
1394    /// `mode`'s list, laid out for the query typed, before the query filters it.
1395    fn layout(&self, mode: Mode) -> Vec<rows::Row> {
1396        // The ended list is a different list, not this one filtered, so its own
1397        // rows are already only ended ones and asking for the filter as well
1398        // would be asking twice.
1399        let (lines, only) = if mode == Mode::Dead {
1400            (&self.past, "")
1401        } else {
1402            (&self.tsv, mode.filter())
1403        };
1404        rows::build(
1405            lines,
1406            &rows::Input {
1407                cur: &self.src.cur,
1408                width: self.width,
1409                home: &self.src.home,
1410                newver: &self.src.newver,
1411                only,
1412                // A row held through a restart keeps the version it had, so the
1413                // one you just pressed ctrl-x on stays in this list, marked ↻,
1414                // until it comes back on the installed one and drops out of it.
1415                outdated: mode == Mode::Outdated,
1416                // A row whose work reports back while you watch drops out at
1417                // the next refresh, so the list empties itself as the outdated
1418                // one does.
1419                background: mode == Mode::Background,
1420                query: &self.query,
1421                snips: self.snippets(mode),
1422                // A live pane can publish no title at all: claude sets one at a
1423                // turn boundary, so one restored by tmux-resurrect and not
1424                // prompted since has nothing there.
1425                ptitles: index::pane_titles(),
1426                restarting: self.restarting.clone(),
1427            },
1428        )
1429    }
1430
1431    /// Filter the rows in hand by the query, and recount what the past list's
1432    /// empty note points at.
1433    fn apply_query(&mut self) {
1434        self.view = filter(&self.all, &self.query, &self.matcher, self.dated());
1435        self.live_hits = self.count_live_hits();
1436    }
1437
1438    /// How many rows the live list would keep for this query, asked only where
1439    /// the past list keeps none: anywhere else it would be a second layout and
1440    /// a second read of the index on every keystroke, for a note nobody sees.
1441    ///
1442    /// It is the live list's OWN answer, its search switch included, rather
1443    /// than a count of index files that hold the words, so the note never
1444    /// promises a row that Tab does not then show.
1445    fn count_live_hits(&self) -> usize {
1446        if self.mode != Mode::Dead || !self.view.is_empty() || self.query.trim().is_empty() {
1447            return 0;
1448        }
1449        filter(&self.layout(Mode::All), &self.query, &self.matcher, false).len()
1450    }
1451
1452    /// The query changed.
1453    ///
1454    /// With text search on this is a full rebuild, not just a re-filter: a row
1455    /// that is in the list because of what its session SAID carries the snippet
1456    /// where its path would be, which is what puts the typed words ON the row so
1457    /// the matcher can keep working in the ordinary way. Re-filtering alone
1458    /// leaves the old rows in place, nothing carries the words, and every row
1459    /// disappears the moment you type something only a transcript holds.
1460    ///
1461    /// With search off it is only a filter, which is what makes typing into a
1462    /// picker you merely opened to jump as cheap as it always was.
1463    fn query_changed(&mut self) {
1464        if self.searching() {
1465            self.rebuild();
1466        } else {
1467            self.apply_query();
1468            self.clamp();
1469        }
1470    }
1471
1472    /// Move to the next list, or with `back` to the one before it.
1473    ///
1474    /// Re-filtered from the rows already in hand, so the new list is on screen
1475    /// at once; the scan behind it lands when it lands.
1476    fn step_mode(&mut self, back: bool) {
1477        // Nothing installed to compare against and the outdated stop is not in
1478        // the ring at all: every row there would be judged against an empty
1479        // version, so the list could only ever be empty.
1480        let (ended, outdated) = (self.src.ended.is_some(), !self.src.newver.is_empty());
1481        self.mode = if back {
1482            self.mode.prev(ended, outdated)
1483        } else {
1484            self.mode.next(ended, outdated)
1485        };
1486        self.rebuild();
1487        self.start_refresh();
1488    }
1489
1490    fn clamp(&mut self) {
1491        if self.view.is_empty() {
1492            self.sel = 0;
1493        } else if self.sel >= self.view.len() {
1494            self.sel = self.view.len() - 1;
1495        }
1496    }
1497
1498    /// Drop the last word of the query, which is fzf's `unix-word-rubout` and
1499    /// `backward-kill-word`. The trailing space goes with it, so a query ending
1500    /// in one loses a whole word rather than just the gap.
1501    fn kill_word(&mut self) {
1502        while self.query.ends_with(char::is_whitespace) {
1503            self.query.pop();
1504        }
1505        while !self.query.is_empty() && !self.query.ends_with(char::is_whitespace) {
1506            self.query.pop();
1507        }
1508        self.query_changed();
1509    }
1510
1511    /// Put the cursor on a pane, if it is in the list. Silent when it is not,
1512    /// which is the case where there is nothing to put it on, and `false` so the
1513    /// one caller that HAS somewhere else to put it can.
1514    fn focus(&mut self, id: &str) -> bool {
1515        match self.view.iter().position(|&i| self.all[i].pane_id == id) {
1516            Some(i) => {
1517                self.sel = i;
1518                true
1519            }
1520            None => false,
1521        }
1522    }
1523
1524    /// Put the cursor on the row nearest the pane the picker was opened from,
1525    /// for when that pane is not an agent session and so is not a row itself.
1526    /// See `nearest` for what "nearest" is.
1527    ///
1528    /// Not knowing where that pane is means not knowing, so the cursor is left
1529    /// where the rebuild put it (the top of the list) rather than moved on a
1530    /// guess. That is what every entry point but `pick` gets.
1531    fn focus_nearest(&mut self) {
1532        if self.src.cur_cwd.is_empty() && self.src.cur_target.is_empty() {
1533            return;
1534        }
1535        let rows: Vec<&rows::Row> = self.view.iter().map(|&i| &self.all[i]).collect();
1536        if let Some(i) = nearest(&rows, &self.src.cur_cwd, &self.src.cur_target) {
1537            self.sel = i;
1538        }
1539    }
1540
1541    /// Where the first scan puts the cursor: on the pane the picker was opened
1542    /// from, and when that pane is not an agent session at all, which is what F1
1543    /// from a shell is, on the row nearest to where it is.
1544    ///
1545    /// Not on the past list. A scan that lands there is one Tab was pressed
1546    /// ahead of, its rows are not on screen, and moving the cursor anyway is a
1547    /// jump through a list the scan has nothing to do with.
1548    fn open_on(&mut self, id: &str) {
1549        if self.mode != Mode::Dead && !self.focus(id) {
1550            self.focus_nearest();
1551        }
1552    }
1553
1554    fn selected(&self) -> Option<&rows::Row> {
1555        self.view.get(self.sel).map(|&i| &self.all[i])
1556    }
1557
1558    fn move_by(&mut self, d: isize) {
1559        if self.view.is_empty() {
1560            return;
1561        }
1562        let n = self.view.len() as isize;
1563        self.sel = (((self.sel as isize + d) % n + n) % n) as usize; // --cycle
1564    }
1565
1566    /// A screenful, and it CLAMPS where `move_by` cycles.
1567    ///
1568    /// fzf's page-up and page-down do not cycle even under `--cycle`, and that
1569    /// is the right behaviour rather than an inconsistency: a page that wrapped
1570    /// would be unusable for what paging is for. Holding Page Down to reach the
1571    /// bottom of a list would sail past the end and land back at the top, and
1572    /// nothing on the row tells you it happened.
1573    ///
1574    /// `page` is the list's drawn height, so it follows the popup's size and the
1575    /// preview being open. Zero is possible on a pane too short to draw a row,
1576    /// and would make the key do nothing.
1577    fn move_page(&mut self, pages: isize, page: usize) {
1578        if self.view.is_empty() {
1579            return;
1580        }
1581        let step = page.max(1) as isize;
1582        let last = self.view.len() as isize - 1;
1583        self.sel = (self.sel as isize + pages * step).clamp(0, last) as usize;
1584    }
1585}
1586
1587/// Returns the row that was chosen, an abort, or a request to be reopened at a
1588/// new size.
1589pub fn run(src: Source) -> std::io::Result<Outcome> {
1590    let kitty = env::var("TAIMUX_TUI_KITTY").is_some_and(|v| v == "1");
1591    let mut guard = Guard::new(kitty)?;
1592    let backend = CrosstermBackend::new(guard.out.try_clone()?);
1593    let mut term = Terminal::new(backend)?;
1594
1595    // 0 turns the timer off, as TAIMUX_REFRESH does for the fzf picker. There is
1596    // no idle gate here: fzf needs one because a reload blocks its input loop and
1597    // swallows keystrokes, and a tick in this loop is just a redraw.
1598    //
1599    // One second, down from three on 2026-09-20. Three was inherited from the
1600    // bash picker, where a refresh re-execed the script and blocked fzf's input
1601    // loop while it did; here it runs on a thread, the rows already on screen
1602    // stay up while it is out, and what the interval buys is how fast a session
1603    // that starts waiting for you turns `✳` while you are looking at the list.
1604    // Measured on 35 panes a scan is 85 ms, so a second apart it is under a tenth
1605    // of one core, and only while a picker is open.
1606    //
1607    // Not lower, and this is the floor rather than a preference: the screen
1608    // capture a daemon serves is cached for 750 ms, so two refreshes closer than
1609    // that would be answered from one capture, and the second would report a
1610    // state that had already been read rather than looking again.
1611    let refresh: f32 = env::var("TAIMUX_REFRESH")
1612        .and_then(|v| v.parse().ok())
1613        .unwrap_or(1.0);
1614    let live = refresh > 0.0;
1615
1616    let mut app = App {
1617        // Not `smart_case`, which is fzf's default and was this picker's: see
1618        // `index::Query`. The two matchers have to agree about what a capital
1619        // means, and the answer both give now is "nothing".
1620        matcher: SkimMatcherV2::default().ignore_case(),
1621        mode: Mode::All,
1622        search: false,
1623        search_past: false,
1624        by_date: false,
1625        preview: true,
1626        query: String::new(),
1627        width: row_width(term.size()?.width),
1628        tsv: String::new(),
1629        past: String::new(),
1630        all: Vec::new(),
1631        view: Vec::new(),
1632        sel: 0,
1633        shot: None,
1634        poff: 0,
1635        poff_for: String::new(),
1636        pending: None,
1637        pending_since: Instant::now(),
1638        client: None,
1639        restarting: HashSet::new(),
1640        live_hits: 0,
1641        src,
1642    };
1643    // Whatever a previous instance was doing when the terminal grew under it.
1644    // Default-empty otherwise, which is an ordinary open.
1645    app.query = std::mem::take(&mut app.src.state.query);
1646    app.mode = Mode::from_key(app.src.state.mode);
1647    // Only where there is a search to switch on. TAIMUX_SEARCH=0 takes ctrl-t and
1648    // the index away together, and the border must not then claim a ⌕ that has
1649    // nothing behind it.
1650    app.search = app.src.state.search && search_enabled();
1651    app.search_past = app.src.state.search_past && search_enabled();
1652    app.by_date = app.src.state.by_date;
1653    app.preview = app.src.state.preview;
1654    // Even the FIRST scan runs off the loop. It used to be synchronous, on the
1655    // reasoning that there is nothing to draw until it lands, and what that
1656    // produced was a POPUP WITH NOTHING IN IT for as long as the scan took:
1657    // reported as another stuck picker, an empty box over a session, no keys.
1658    // There is something to draw, and it is "looking for them".
1659    //
1660    // An empty answer used to close the picker too. It says one thing, and it is
1661    // the thing you need: F1 on a machine with no agent sessions was
1662    // indistinguishable from F1 not being bound, from taimux not being
1663    // installed, and from the popup failing to start.
1664    app.start_refresh();
1665    // The cursor opens on the pane the picker was opened from, which is the row
1666    // marked ●, and on the row nearest to that pane when it is not an agent
1667    // session and so has no row of its own (see `nearest`). After a reopen it
1668    // goes back where it was instead, since that is the row you were looking at
1669    // when the terminal changed shape under you. Applied when the rows arrive,
1670    // since there is nothing to put it on before that.
1671    let opening_on = if app.src.state.on.is_empty() {
1672        app.src.cur.clone()
1673    } else {
1674        app.src.state.on.clone()
1675    };
1676    let mut opened = false;
1677
1678    let mut state = ListState::default();
1679    let mut chosen: Option<String> = None;
1680    // Set when the terminal has grown past what this popup can use.
1681    let mut outgrew = false;
1682    let mut ticked = Instant::now();
1683    // How tall the list came out, written by the draw below and read by Page
1684    // Up / Page Down. Taken from the drawn area rather than recomputed from the
1685    // terminal size, because the layout it would have to reproduce (a border,
1686    // two fixed lines, and a preview that takes 60% only when there is room for
1687    // it) is exactly the sort of arithmetic that drifts from the real thing.
1688    let mut page: usize = 1;
1689    // Where the list starts on screen, for turning a click's row into a row of
1690    // the list. Same reasoning as `page`: measured, not recomputed.
1691    let mut list_y: u16 = 0;
1692    // The last left click, so a second one on the same row reads as a
1693    // double-click. crossterm reports presses, never double-clicks, so the only
1694    // way to have the gesture fzf had is to time it.
1695    let mut clicked: Option<(u16, Instant)> = None;
1696
1697    loop {
1698        state.select(if app.view.is_empty() {
1699            None
1700        } else {
1701            Some(app.sel)
1702        });
1703        term.draw(|f| {
1704            let count = format!(" {}/{} ", app.view.len(), app.all.len());
1705            let mut block = Block::bordered()
1706                .title(label(
1707                    app.mode,
1708                    app.dated(),
1709                    live,
1710                    app.searching(),
1711                    app.refreshing(),
1712                ))
1713                .title_bottom(Line::from(count.clone()));
1714            // Dim, and in the corner furthest from the cursor: it is reference,
1715            // read once after an update and never again, so it must not compete
1716            // with the count beside it or the list above.
1717            if room_for_tag(f.area().width, &count) {
1718                block = block.title_bottom(
1719                    Line::from(Span::styled(
1720                        version_tag(),
1721                        Style::default().fg(Color::DarkGray),
1722                    ))
1723                    .right_aligned(),
1724                );
1725            }
1726            let inner = block.inner(f.area());
1727            f.render_widget(block, f.area());
1728
1729            let [prompt, head, body] = Layout::vertical([
1730                Constraint::Length(1),
1731                Constraint::Length(1),
1732                Constraint::Min(1),
1733            ])
1734            .areas(inner);
1735
1736            f.render_widget(
1737                Paragraph::new(Line::from(vec![
1738                    Span::styled("pick ❯ ", Style::default().fg(Color::Cyan)),
1739                    Span::raw(app.query.clone()),
1740                ])),
1741                prompt,
1742            );
1743            f.render_widget(
1744                Paragraph::new(Line::from(Span::styled(
1745                    header(
1746                        app.src.script.is_some(),
1747                        app.src.ended.is_some(),
1748                        search_enabled(),
1749                        app.searching(),
1750                        app.mode.has_dates().then_some(app.by_date),
1751                    ),
1752                    Style::default().fg(Color::DarkGray),
1753                ))),
1754                head,
1755            );
1756
1757            // The preview takes the bottom 60%, as --preview-window=down,60% does.
1758            let (body, prev) = if app.preview && body.height >= 8 {
1759                let [a, b] =
1760                    Layout::vertical([Constraint::Percentage(40), Constraint::Percentage(60)])
1761                        .areas(body);
1762                (a, Some(b))
1763            } else {
1764                (body, None)
1765            };
1766            page = body.height as usize;
1767            list_y = body.y;
1768
1769            let items: Vec<ListItem> = app
1770                .view
1771                .iter()
1772                .map(|&i| {
1773                    ListItem::new(Line::from(
1774                        app.all[i]
1775                            .cells
1776                            .iter()
1777                            .map(|c| Span::styled(c.text.clone(), c.paint.style()))
1778                            .collect::<Vec<_>>(),
1779                    ))
1780                })
1781                .collect();
1782            if app.view.is_empty() {
1783                // Where the rows would be, in the same place your eye already
1784                // is, rather than a line tucked under the header.
1785                f.render_widget(
1786                    Paragraph::new(empty_note(
1787                        app.mode,
1788                        &app.query,
1789                        // Nothing has come back yet, which is not the same as
1790                        // nothing being there.
1791                        !opened,
1792                        // The RAW scan, not the laid-out rows: those already
1793                        // have the mode filter applied, so one idle session
1794                        // viewed through the waiting list read as a machine
1795                        // with nothing running on it at all.
1796                        app.tsv.trim().is_empty(),
1797                        app.src.ended.is_some(),
1798                        search_enabled() && !app.searching(),
1799                        app.live_hits,
1800                    ))
1801                    .style(Style::default().fg(Color::DarkGray))
1802                    .wrap(Wrap { trim: false }),
1803                    body,
1804                );
1805            } else {
1806                f.render_stateful_widget(
1807                    List::new(items)
1808                        .highlight_symbol("▶ ")
1809                        .highlight_style(Style::default().add_modifier(Modifier::REVERSED)),
1810                    body,
1811                    &mut state,
1812                );
1813            }
1814
1815            if let Some(area) = prev {
1816                let block = Block::default()
1817                    .borders(Borders::TOP)
1818                    .border_style(Style::default().fg(Color::DarkGray));
1819                let inner = block.inner(area);
1820                f.render_widget(block, area);
1821                let (head, text, at_bottom) = app.preview();
1822                // The header stays put and the body scrolls under it. Pinning it
1823                // is the whole reason the two are built separately: it says
1824                // WHICH session this is, and scrolling that off the top would
1825                // leave a screenful of text belonging to nothing in particular.
1826                let hh = (head.len() as u16).min(inner.height);
1827                let [hrect, brect] =
1828                    Layout::vertical([Constraint::Length(hh), Constraint::Min(0)]).areas(inner);
1829                f.render_widget(Paragraph::new(head).wrap(Wrap { trim: false }), hrect);
1830
1831                // Where the window sits in the body. `poff` is rows away from
1832                // the default view, negative towards the start, and the clamp is
1833                // what lets one offset mean the same thing for a live pane
1834                // (anchored at the bottom) and an ended conversation (anchored
1835                // at the top): at either extreme it simply stops.
1836                //
1837                // The body is NOT wrapped, and that is what makes the arithmetic
1838                // exact. `Paragraph::scroll` counts WRAPPED rows while this
1839                // counts lines, so with wrapping on a capture padded to a wider
1840                // pane every line became two rows: each keypress moved half a
1841                // line and the clamp stopped a third of the way up. Unwrapped, a
1842                // line is a row. It also suits what this is, a viewport onto a
1843                // pane: a line too long for the preview reads better clipped
1844                // than re-flowed, since that is what the pane looks like. The
1845                // header keeps its wrap, being prose.
1846                let most = text.len().saturating_sub(brect.height as usize) as i32;
1847                let base = if at_bottom { most } else { 0 };
1848                let start = (base + app.poff).clamp(0, most.max(0));
1849                // Write the clamped offset BACK, or it accumulates past the end
1850                // of the body: hold shift-up at the top for a second and coming
1851                // back down takes as many presses as went in, with nothing on
1852                // screen moving for any of them. The limits are only known here,
1853                // where the body and the area both are, which is why the field
1854                // cannot clamp itself.
1855                app.poff = start - base;
1856                f.render_widget(Paragraph::new(text).scroll((start as u16, 0)), brect);
1857            }
1858        })?;
1859
1860        // A refresh that has landed is taken here, between two draws, so the
1861        // rebuild it costs is the only work the loop ever does off the input
1862        // path. The ASK for one is free: it hands the row source to a thread.
1863        if app.take_refresh() {
1864            app.rebuild();
1865            if !opened {
1866                opened = true;
1867                app.open_on(&opening_on);
1868            }
1869            // The terminal has grown past what this popup was asked for, and
1870            // tmux will not grow a popup on its own. Leaving the loop is how the
1871            // picker asks to be reopened: the popup closes with it, and what it
1872            // was doing goes out in the Outcome.
1873            if let Some((_, size)) = app.client.clone() {
1874                if resize_enabled() && outgrown(term.size().map(|s| (s.width, s.height))?, size, 2)
1875                {
1876                    outgrew = true;
1877                    break;
1878                }
1879            }
1880        }
1881        if live && ticked.elapsed().as_secs_f32() >= refresh {
1882            ticked = Instant::now();
1883            app.start_refresh();
1884        }
1885        if !event::poll(Duration::from_millis(120))? {
1886            continue;
1887        }
1888        match event::read()? {
1889            // One event, carrying its own text, with no way to mistake it for
1890            // Enter. A pasted line break arrives as CR, so both are split on.
1891            Event::Paste(text) => {
1892                let first = text.split(['\r', '\n']).next().unwrap_or_default();
1893                app.query.push_str(first);
1894                app.query_changed();
1895            }
1896            // The wheel is the arrow keys, and a click is the cursor, which is
1897            // what fzf's default mouse handling did. Restored because the port
1898            // simply never asked the terminal for mouse events.
1899            Event::Mouse(MouseEvent { kind, row: my, .. }) => match kind {
1900                // Wrapping, because these ARE Up and Down: a wheel that stopped
1901                // where the arrow key it stands in for cycles would be the odd
1902                // one out. Over the preview too, since that pane has no scroll
1903                // of its own to offer instead.
1904                MouseEventKind::ScrollUp => app.move_by(-1),
1905                MouseEventKind::ScrollDown => app.move_by(1),
1906                // A click at or below where the list starts. Above it is the
1907                // prompt or the header, which are not rows.
1908                MouseEventKind::Down(MouseButton::Left) if my >= list_y => {
1909                    // Which row was under the pointer. `offset` is what the List
1910                    // widget has scrolled to, so this stays right on a list
1911                    // longer than the window, and a click past the last row
1912                    // lands on nothing rather than off the end.
1913                    let i = state.offset() + (my - list_y) as usize;
1914                    if i < app.view.len() {
1915                        app.sel = i;
1916                        // A second click on the row already under the cursor,
1917                        // soon enough, accepts it. fzf's double-click, with the
1918                        // clock this has to keep because crossterm reports
1919                        // presses and never the gesture.
1920                        let again =
1921                            clicked.is_some_and(|(r, t)| r == my && t.elapsed() < DOUBLE_CLICK);
1922                        clicked = Some((my, Instant::now()));
1923                        if again {
1924                            if let Some(r) = app.selected() {
1925                                chosen = Some(r.pane_id.clone());
1926                            }
1927                            break;
1928                        }
1929                    }
1930                }
1931                _ => {}
1932            },
1933            Event::Resize(w, _) => {
1934                app.width = row_width(w);
1935                app.rebuild();
1936            }
1937            Event::Key(k) => {
1938                // A terminal with the kitty flags pushed reports releases too, and
1939                // acting on both double-counts every key.
1940                if k.kind != KeyEventKind::Press {
1941                    continue;
1942                }
1943                let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
1944                let alt = k.modifiers.contains(KeyModifiers::ALT);
1945                let shift = k.modifiers.contains(KeyModifiers::SHIFT);
1946                match k.code {
1947                    // fzf aborts on all four of these, and abort is the one
1948                    // action worth having several ways to reach.
1949                    KeyCode::Esc => break,
1950                    KeyCode::Char('c') | KeyCode::Char('g') | KeyCode::Char('q') if ctrl => break,
1951                    KeyCode::Enter => {
1952                        if let Some(r) = app.selected() {
1953                            chosen = Some(r.pane_id.clone());
1954                        }
1955                        break;
1956                    }
1957                    // Scroll the PREVIEW, not the list, which is what fzf points
1958                    // these at. A live pane's preview opens on the bottom of its
1959                    // screen, so shift-up is how you see what came before it; an
1960                    // ended conversation opens at the top, so shift-down is how
1961                    // you read forwards through it. The offset is clamped at both
1962                    // ends of the body and reset whenever the cursor moves.
1963                    KeyCode::Up if shift => app.poff -= 1,
1964                    KeyCode::Down if shift => app.poff += 1,
1965                    KeyCode::Down => app.move_by(1),
1966                    KeyCode::Up => app.move_by(-1),
1967                    // Both pairs, as fzf binds both. ctrl-j is safe to take
1968                    // here: a terminal sends LF for it and CR for Enter, and
1969                    // crossterm keeps them apart, so this does not shadow
1970                    // accept. Checked rather than assumed.
1971                    KeyCode::Char('n') | KeyCode::Char('j') if ctrl => app.move_by(1),
1972                    KeyCode::Char('p') | KeyCode::Char('k') if ctrl => app.move_by(-1),
1973                    // The ends of the LIST. fzf points these at the ends of the
1974                    // QUERY by default, which in a picker you rarely type into is
1975                    // a key that visibly does nothing at all.
1976                    KeyCode::Home => app.sel = 0,
1977                    KeyCode::End => app.sel = app.view.len().saturating_sub(1),
1978                    // A screenful, by the height the list was actually drawn at,
1979                    // so it tracks the popup's size and whether the preview is
1980                    // open. fzf bound these itself and the port simply dropped
1981                    // them: Home and End were ported and these were not, which is
1982                    // why one pair kept working and the other went quiet.
1983                    KeyCode::PageDown => app.move_page(1, page),
1984                    KeyCode::PageUp => app.move_page(-1, page),
1985                    // Shift-tab walks the ring the other way. A terminal sends
1986                    // it as BackTab, and one with the kitty flags pushed sends
1987                    // Tab carrying SHIFT instead, so both are taken. BackTab is
1988                    // matched on its own rather than or-ed into the guarded arm
1989                    // below, because the modifier it arrives with is the part
1990                    // that differs between terminals and the key is not.
1991                    KeyCode::BackTab => app.step_mode(true),
1992                    KeyCode::Tab if shift => app.step_mode(true),
1993                    KeyCode::Tab => app.step_mode(false),
1994                    KeyCode::Char('r') if ctrl => app.start_refresh(),
1995                    // Nothing is bound when search is turned off, and the
1996                    // picker then behaves exactly as it did before there was any.
1997                    KeyCode::Char('t') if ctrl && search_enabled() => app.toggle_search(),
1998                    // By date: newest first by when each session last said
1999                    // something, the rows that say what was typed ahead of the
2000                    // loose matches (see `filter`). Bound only on the lists with
2001                    // a date to sort by (see `Mode::has_dates`), and a rebuild
2002                    // rather than a re-filter so the cursor stays on the session
2003                    // it was on: a second press then lands exactly where the
2004                    // first one started. It arrives as a key and not as XOFF,
2005                    // since raw mode turns flow control off.
2006                    KeyCode::Char('s') if ctrl && app.mode.has_dates() => {
2007                        app.by_date = !app.by_date;
2008                        app.rebuild();
2009                    }
2010                    // ctrl-/ reaches a terminal as several different bytes, so
2011                    // all of them are taken rather than one.
2012                    KeyCode::Char('/') | KeyCode::Char('_') | KeyCode::Char('\u{1f}') if ctrl => {
2013                        app.preview = !app.preview;
2014                    }
2015                    KeyCode::Char('u') if ctrl => {
2016                        app.query.clear();
2017                        app.query_changed();
2018                    }
2019                    // A word back, which fzf gives both of these. Worth having
2020                    // even though the query has no cursor: deleting the last
2021                    // word of "claude renovate" is a thing you want, and the
2022                    // alternative is holding backspace.
2023                    KeyCode::Char('w') if ctrl => app.kill_word(),
2024                    // Before the bare Backspace below, or alt-backspace would
2025                    // take a single character. It took one until now: the arm
2026                    // ignored modifiers, so fzf's backward-kill-word quietly
2027                    // behaved as plain backspace.
2028                    KeyCode::Backspace if alt => app.kill_word(),
2029                    // ctrl-h is backspace as far as fzf is concerned, and some
2030                    // terminals send it for the key. It needs naming separately
2031                    // because it arrives as a ctrl-char, not as Backspace.
2032                    KeyCode::Backspace => {
2033                        app.query.pop();
2034                        app.query_changed();
2035                    }
2036                    KeyCode::Char('h') if ctrl => {
2037                        app.query.pop();
2038                        app.query_changed();
2039                    }
2040                    // A full repaint, for a screen something else has written
2041                    // over. Every loop redraws already, so this only has to
2042                    // throw away what ratatui thinks is on the terminal.
2043                    //
2044                    // `resize` and NOT `Terminal::clear`, which would be the
2045                    // obvious call and is a trap here: it snapshots the cursor
2046                    // first, and the crossterm backend does that with
2047                    // `crossterm::cursor::position()`, which writes ESC[6n to
2048                    // the PROCESS's stdout rather than to the backend's writer.
2049                    // Stdout carries exactly one thing in this program, the
2050                    // chosen pane id, so ctrl-l put `[6n` where the caller reads
2051                    // the answer. Measured, not theorised.
2052                    //
2053                    // resize() on a fullscreen viewport takes the same path
2054                    // minus that snapshot: it clears through the backend's own
2055                    // writer and resets the back buffer, so the next draw
2056                    // repaints in full.
2057                    KeyCode::Char('l') if ctrl => repaint(&mut term),
2058                    // The two keys that act rather than navigate. They run the
2059                    // script the way fzf's execute() does: hand the terminal over,
2060                    // let the child own it, take it back.
2061                    KeyCode::Char('x') if ctrl => {
2062                        if let (Some(s), Some(r)) = (app.src.script.clone(), app.selected()) {
2063                            let id = r.pane_id.clone();
2064                            // Nothing to hold here: the restart writes the row
2065                            // down before its first keystroke and every scan
2066                            // lists it from there until the session is back,
2067                            // marked ↻. See `restarting` in core.
2068                            guard.suspend();
2069                            if let Err(e) = act_child(&s, &["_restart", &id]) {
2070                                crate::act::report_failed_child("the restart", &e);
2071                            }
2072                            guard.resume();
2073                            repaint(&mut term);
2074                            // Rebuilt from the rows already in hand and drawn on
2075                            // the next pass, so the list is back on screen at
2076                            // once. Asking for fresh rows here and WAITING for
2077                            // them is what left the picker showing the child's
2078                            // last screen, unable to draw or read a key, for as
2079                            // long as the scan took.
2080                            app.rebuild();
2081                            app.start_refresh();
2082                            // …and the cursor goes back on it explicitly, which
2083                            // the rebuild only does when it can re-pin the row
2084                            // it was on, so a press that did nothing never
2085                            // leaves the cursor somewhere else.
2086                            app.focus(&id);
2087                        }
2088                    }
2089                    // ctrl-o: carry this conversation into a different agent.
2090                    // Same shape as ctrl-x, and for the same reason: it draws a
2091                    // menu, waits on a key and then opens a window, none of
2092                    // which the picker's own loop can do while it is drawing.
2093                    KeyCode::Char('o') if ctrl => {
2094                        if let (Some(s), Some(r)) = (app.src.script.clone(), app.selected()) {
2095                            let id = r.pane_id.clone();
2096                            guard.suspend();
2097                            if let Err(e) = act_child(&s, &["_handoff", &id]) {
2098                                crate::act::report_failed_child("the handoff", &e);
2099                            }
2100                            guard.resume();
2101                            repaint(&mut term);
2102                            // Nothing in the list changed: a handoff opens a NEW
2103                            // window and leaves the conversation it came from
2104                            // exactly where it was. So the cursor goes straight
2105                            // back on the row rather than the list being rebuilt.
2106                            app.focus(&id);
2107                        }
2108                    }
2109                    KeyCode::F(8) => {
2110                        if let Some(s) = app.src.script.clone() {
2111                            guard.suspend();
2112                            if let Err(e) = act_child(&s, &["_sweep"]) {
2113                                crate::act::report_failed_child("the sweep", &e);
2114                            }
2115                            guard.resume();
2116                            repaint(&mut term);
2117                            // Same as ctrl-x, and this is the press it was
2118                            // REPORTED on: a sweep restarts every outdated
2119                            // session at once, so the scan that follows it is the
2120                            // slowest one the picker ever runs.
2121                            app.rebuild();
2122                            app.start_refresh();
2123                        }
2124                    }
2125                    // Anything else printable joins the query. `!alt` matters as
2126                    // much as `!ctrl` and was missing: ALT is not CTRL, so every
2127                    // alt-chord fell in here and TYPED ITS LETTER. Holding alt
2128                    // and pressing b put a "b" in the query, which is fzf's
2129                    // backward-word, and any stray chord the terminal passed
2130                    // through corrupted the search with no way to tell.
2131                    KeyCode::Char(c) if !ctrl && !alt => {
2132                        app.query.push(c);
2133                        app.query_changed();
2134                    }
2135                    _ => {}
2136                }
2137            }
2138            _ => {}
2139        }
2140    }
2141
2142    drop(term);
2143    drop(guard);
2144    Ok(match (chosen, outgrew) {
2145        (Some(id), _) => Outcome::Chosen(id),
2146        (None, true) => Outcome::Resize(State {
2147            query: app.query.clone(),
2148            mode: app.mode.key(),
2149            search: app.search,
2150            search_past: app.search_past,
2151            by_date: app.by_date,
2152            preview: app.preview,
2153            on: app
2154                .selected()
2155                .map(|r| r.pane_id.clone())
2156                .unwrap_or_default(),
2157            client: app.client.clone().map(|(tty, _)| tty).unwrap_or_default(),
2158        }),
2159        (None, false) => Outcome::Aborted,
2160    })
2161}
2162
2163#[cfg(test)]
2164mod tests {
2165    use super::*;
2166
2167    fn src(tsv: &str) -> Source {
2168        let t = tsv.to_string();
2169        Source {
2170            fetch: Arc::new(move || t.clone()),
2171            restarting: Arc::new(HashSet::new),
2172            ended: None,
2173            cur: String::new(),
2174            cur_cwd: String::new(),
2175            cur_target: String::new(),
2176            home: "/h".into(),
2177            newver: String::new(),
2178            script: None,
2179            popup: false,
2180            state: Default::default(),
2181        }
2182    }
2183
2184    fn app(tsv: &str) -> App {
2185        let mut a = App {
2186            src: src(tsv),
2187            matcher: SkimMatcherV2::default().ignore_case(),
2188            mode: Mode::All,
2189            search: false,
2190            search_past: false,
2191            by_date: false,
2192            preview: true,
2193            query: String::new(),
2194            width: 100,
2195            tsv: String::new(),
2196            past: String::new(),
2197            all: Vec::new(),
2198            view: Vec::new(),
2199            sel: 0,
2200            shot: None,
2201            poff: 0,
2202            poff_for: String::new(),
2203            pending: None,
2204            pending_since: Instant::now(),
2205            client: None,
2206            restarting: HashSet::new(),
2207            live_hits: 0,
2208        };
2209        a.fetch();
2210        a.rebuild();
2211        a
2212    }
2213
2214    fn ids(a: &App) -> Vec<String> {
2215        a.view.iter().map(|&i| a.all[i].pane_id.clone()).collect()
2216    }
2217
2218    /// The marker column says a restart is in flight. It goes there and not into
2219    /// the summary because the summary strips a leading marker glyph.
2220    ///
2221    /// The row itself is the scan's: a restart writes it down before its first
2222    /// keystroke and the scan lists it from there (see `restarting` in core), so
2223    /// all the picker adds is which rows those are.
2224    #[test]
2225    fn a_row_with_a_restart_in_flight_is_marked() {
2226        let mut a = app(THREE);
2227        a.src.restarting = Arc::new(|| HashSet::from(["%2".to_string()]));
2228        a.fetch();
2229        a.rebuild();
2230        let text = |id: &str| a.all.iter().find(|r| r.pane_id == id).unwrap().to_ansi();
2231        assert!(
2232            text("%2").contains('↻'),
2233            "expected the restart marker in {:?}",
2234            text("%2")
2235        );
2236        // …and it does not borrow the waiting star, which means something else
2237        assert!(!text("%2").contains('✳'), "must not read as asking");
2238        assert!(!text("%1").contains('↻'), "only the row being restarted");
2239    }
2240
2241    /// The mark comes and goes with the scan it was read beside, on the worker
2242    /// thread every refresh but the first runs on, so it is gone the moment the
2243    /// restart is over rather than lingering on a session already back.
2244    #[test]
2245    fn the_mark_rides_each_refresh_and_goes_with_the_restart() {
2246        let held = Arc::new(std::sync::Mutex::new(HashSet::from(["%2".to_string()])));
2247        let mut a = app(THREE);
2248        let h = held.clone();
2249        a.src.restarting = Arc::new(move || h.lock().unwrap().clone());
2250        let refresh = |a: &mut App| {
2251            a.start_refresh();
2252            for _ in 0..100 {
2253                if a.take_refresh() {
2254                    a.rebuild();
2255                    return;
2256                }
2257                std::thread::sleep(Duration::from_millis(10));
2258            }
2259            panic!("the refresh never arrived");
2260        };
2261        let marked = |a: &App| a.all.iter().any(|r| r.to_ansi().contains('↻'));
2262
2263        refresh(&mut a);
2264        assert!(marked(&a), "in flight");
2265        held.lock().unwrap().clear();
2266        refresh(&mut a);
2267        assert!(!marked(&a), "over");
2268        assert_eq!(ids(&a), ["%1", "%2", "%3"]);
2269    }
2270
2271    /// The bug this is all for: the picker used to call the row source from its
2272    /// input loop, so a scan that took 85 seconds after an F8 sweep was 85
2273    /// seconds with no draw and no key. Asking must return AT ONCE.
2274    #[test]
2275    fn asking_for_a_refresh_does_not_wait_for_it() {
2276        let mut a = app(THREE);
2277        a.src.fetch = Arc::new(|| {
2278            std::thread::sleep(Duration::from_millis(400));
2279            "%9\tz:1.1\t/h\tclaude\t1\tidle\t-\tlate arrival".to_string()
2280        });
2281        let at = Instant::now();
2282        a.start_refresh();
2283        assert!(
2284            at.elapsed() < Duration::from_millis(100),
2285            "start_refresh blocked for {:?}",
2286            at.elapsed()
2287        );
2288        assert!(!a.take_refresh(), "nothing has landed yet");
2289        assert_eq!(a.all.len(), 3, "and the old rows are still there to draw");
2290
2291        // …and it lands later, without anything having waited on it.
2292        let mut got = false;
2293        for _ in 0..100 {
2294            if a.take_refresh() {
2295                got = true;
2296                break;
2297            }
2298            std::thread::sleep(Duration::from_millis(20));
2299        }
2300        assert!(got, "the refresh never arrived");
2301        a.rebuild();
2302        assert_eq!(ids(&a), ["%9"]);
2303    }
2304
2305    /// One at a time. The timer must not stack refreshes on a machine where they
2306    /// take longer than the interval, which is the machine this matters on.
2307    #[test]
2308    fn a_second_refresh_is_not_started_while_one_is_out() {
2309        let mut a = app(THREE);
2310        let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2311        let r = runs.clone();
2312        a.src.fetch = Arc::new(move || {
2313            r.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2314            std::thread::sleep(Duration::from_millis(300));
2315            String::new()
2316        });
2317        a.start_refresh();
2318        a.start_refresh();
2319        a.start_refresh();
2320        std::thread::sleep(Duration::from_millis(500));
2321        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1);
2322    }
2323
2324    /// A row source that panics drops its sender rather than answering. The
2325    /// picker has to forget that refresh and carry on, not wait on it forever.
2326    #[test]
2327    fn a_refresh_that_never_answers_is_forgotten() {
2328        let mut a = app(THREE);
2329        a.src.fetch = Arc::new(|| panic!("the scan blew up"));
2330        a.start_refresh();
2331        for _ in 0..100 {
2332            if a.pending.is_none() {
2333                break;
2334            }
2335            let _ = a.take_refresh();
2336            std::thread::sleep(Duration::from_millis(20));
2337        }
2338        assert!(a.pending.is_none(), "still waiting on a dead thread");
2339        assert_eq!(a.all.len(), 3, "and the list it had is untouched");
2340    }
2341
2342    /// The border says so, but only once it has been a second: on a healthy
2343    /// machine the answer is back before the next draw, and a label that flashed
2344    /// every tick would be noise about nothing.
2345    #[test]
2346    fn the_border_says_refreshing_only_when_it_is_worth_saying() {
2347        let mut a = app(THREE);
2348        a.src.fetch = Arc::new(|| {
2349            std::thread::sleep(Duration::from_millis(1500));
2350            String::new()
2351        });
2352        a.start_refresh();
2353        assert!(!a.refreshing(), "not from the first millisecond");
2354        a.pending_since = Instant::now() - Duration::from_secs(2);
2355        assert!(a.refreshing());
2356        assert_eq!(
2357            label(Mode::All, false, true, false, true),
2358            " agent sessions · live · refreshing "
2359        );
2360    }
2361
2362    /// The picker used to CLOSE itself when the list came out empty, and that
2363    /// is what was reported as "F1 no longer works": on a machine with no agent
2364    /// sessions the popup opened and closed too fast to see, which looks exactly
2365    /// like an unbound key, a missing binary, or a popup that failed to start.
2366    /// The four silences mean different things and it now says which.
2367    #[test]
2368    fn an_empty_list_says_which_kind_of_empty_it_is() {
2369        let text = |ls: Vec<Line<'static>>| -> String {
2370            ls.iter()
2371                .map(|l| {
2372                    l.spans
2373                        .iter()
2374                        .map(|s| s.content.to_string())
2375                        .collect::<String>()
2376                })
2377                .collect::<Vec<_>>()
2378                .join("\n")
2379        };
2380
2381        // nothing running at all, which is the reported case
2382        let none = text(empty_note(Mode::All, "", false, true, false, false, 0));
2383        assert!(none.contains("No agent sessions on this machine"), "{none}");
2384        assert!(none.contains("Esc closes this"), "{none}");
2385        // …and with an ended list to offer, it offers it
2386        let none_ended = text(empty_note(Mode::All, "", false, true, true, false, 0));
2387        assert!(none_ended.contains("Tab reaches the conversations that ended"));
2388
2389        // something IS running, just not in this state
2390        let filtered = text(empty_note(Mode::Input, "", false, false, true, false, 0));
2391        assert!(
2392            filtered.contains("Nothing is waiting for an answer right now"),
2393            "{filtered}"
2394        );
2395        assert!(!filtered.contains("No agent sessions"), "{filtered}");
2396
2397        // a query nobody matches, which says what to press to undo it
2398        let q = text(empty_note(Mode::All, "zzz", false, false, true, false, 0));
2399        assert!(q.contains("Nothing matches zzz"), "{q}");
2400        assert!(q.contains("ctrl-u"), "{q}");
2401        assert!(!q.contains("ctrl-t"), "no search to offer: {q}");
2402        assert!(!q.contains("still open"), "no live hit to point at: {q}");
2403        // …and names ctrl-t when what was said is not being searched but could
2404        // be, which is where a pasted URL used to find nothing and say nothing
2405        let hint = text(empty_note(
2406            Mode::Dead,
2407            "https://x/273",
2408            false,
2409            false,
2410            true,
2411            true,
2412            0,
2413        ));
2414        assert!(
2415            hint.contains("ctrl-t searches what was said in them too"),
2416            "{hint}"
2417        );
2418        // …and points at the live list when the match is a session still open
2419        // in a pane, which the past list leaves out
2420        let one = text(empty_note(
2421            Mode::Dead,
2422            "https://x/13",
2423            false,
2424            false,
2425            true,
2426            false,
2427            1,
2428        ));
2429        assert!(
2430            one.contains("A session still open in a pane matches it: Tab shows it."),
2431            "{one}"
2432        );
2433        assert!(one.contains("ctrl-u"), "{one}");
2434        let two = text(empty_note(
2435            Mode::Dead,
2436            "https://x/13",
2437            false,
2438            false,
2439            true,
2440            false,
2441            2,
2442        ));
2443        assert!(
2444            two.contains("2 sessions still open in panes match it: Tab shows them."),
2445            "{two}"
2446        );
2447
2448        // the ended list, before anything has ended
2449        let dead = text(empty_note(Mode::Dead, "", false, false, true, false, 0));
2450        assert!(
2451            dead.contains("No past conversations have been found here yet"),
2452            "{dead}"
2453        );
2454
2455        // …and before the first scan has come back at all, which is the state a
2456        // popup used to show as an empty box. It outranks every other case,
2457        // because none of them is known yet.
2458        let scanning = text(empty_note(Mode::All, "", true, true, true, false, 0));
2459        assert!(
2460            scanning.contains("Looking for agent sessions"),
2461            "{scanning}"
2462        );
2463        assert!(!scanning.contains("No agent sessions"), "{scanning}");
2464        let scanning_q = text(empty_note(Mode::Input, "zzz", true, false, true, false, 0));
2465        assert!(
2466            scanning_q.contains("Looking for agent sessions"),
2467            "{scanning_q}"
2468        );
2469    }
2470
2471    /// The default state is an ORDINARY open, which above all means the preview
2472    /// is ON. Deriving Default gave `preview: false` and every picker opened
2473    /// with it hidden; the tell was the page keys moving twice as far, since the
2474    /// list had the preview's half of the window too.
2475    #[test]
2476    fn the_default_state_is_an_ordinary_open() {
2477        let d = State::default();
2478        assert!(d.preview);
2479        // every list searches what was said from the start
2480        assert!(d.search);
2481        assert!(d.search_past);
2482        assert!(!d.by_date);
2483        assert_eq!(Mode::from_key(d.mode), Mode::All);
2484        assert!(d.query.is_empty() && d.on.is_empty());
2485    }
2486
2487    /// tmux shrinks a popup to fit a client that got smaller and grows it back
2488    /// up to the size it was ASKED for, so the only case the picker has to act
2489    /// on is a terminal that grew past that. Both directions were measured
2490    /// before this was written; these are the numbers that came back.
2491    #[test]
2492    fn only_a_terminal_that_grew_past_the_popup_counts() {
2493        // opened at 160x50, so 80% is 128x40 and the usable area 126x38
2494        assert!(
2495            !outgrown((126, 38), (160, 50), 2),
2496            "the size it was opened at is not a reason to reopen"
2497        );
2498        // the client grew to 200x60: 80% of that is 160x48, well past 126x38
2499        assert!(outgrown((126, 38), (200, 60), 2));
2500        // …and the same popup on a client that SHRANK is tmux's business, not
2501        // ours: it has already clamped the popup to fit.
2502        assert!(!outgrown((58, 18), (60, 20), 2));
2503    }
2504
2505    /// A column or two of rounding must not close and reopen the popup, and the
2506    /// rule switches at 100 columns, so a phone rotating between portrait and
2507    /// landscape crosses it in both directions.
2508    #[test]
2509    fn the_slack_stops_a_reopen_over_rounding() {
2510        // 80 columns is "small", so the popup is 100% wide: 78 usable
2511        assert!(!outgrown((78, 19), (80, 24), 2));
2512        // one column of growth is not worth a flicker
2513        assert!(!outgrown((78, 19), (81, 24), 2));
2514        // portrait to landscape: 80 -> 140 crosses the rule, 80% of 140 is 112
2515        assert!(outgrown((78, 19), (140, 40), 2));
2516    }
2517
2518    /// What a resize carries over. Losing the query or the cursor to a rotation
2519    /// would make the reopen worse than the stuck popup it replaces.
2520    #[test]
2521    fn a_resize_hands_over_what_the_picker_was_doing() {
2522        let mut a = app(THREE);
2523        a.query = "banana".into();
2524        a.mode = Mode::Run;
2525        a.search = true;
2526        a.by_date = true;
2527        a.preview = false;
2528        a.query_changed();
2529        let state = State {
2530            query: a.query.clone(),
2531            mode: a.mode.key(),
2532            search: a.search,
2533            search_past: a.search_past,
2534            by_date: a.by_date,
2535            preview: a.preview,
2536            on: a.selected().map(|r| r.pane_id.clone()).unwrap_or_default(),
2537            // The client the popup was on, which the reopen must target rather
2538            // than asking tmux which one is "current".
2539            client: "/dev/pts/7".into(),
2540        };
2541        assert_eq!(
2542            state,
2543            State {
2544                query: "banana".into(),
2545                mode: "run",
2546                search: true,
2547                search_past: false,
2548                by_date: true,
2549                preview: false,
2550                on: "%2".into(),
2551                client: "/dev/pts/7".into(),
2552            }
2553        );
2554        // …and it comes back as the same picker on the other side
2555        assert_eq!(Mode::from_key(state.mode), Mode::Run);
2556        assert_eq!(Mode::from_key("outdated"), Mode::Outdated);
2557        assert_eq!(Mode::from_key("background"), Mode::Background);
2558        assert_eq!(Mode::from_key(""), Mode::All);
2559    }
2560
2561    /// focus() is what covers a REFUSED restart: nothing is held, so the rebuild
2562    /// has nothing to re-pin to, and without it the cursor fell to the top on
2563    /// exactly the presses that did nothing.
2564    #[test]
2565    fn focus_puts_the_cursor_back_and_is_silent_when_it_cannot() {
2566        let mut a = app(THREE);
2567        a.sel = 0;
2568        assert!(a.focus("%3"));
2569        assert_eq!(a.selected().map(|r| r.pane_id.as_str()), Some("%3"));
2570        assert!(!a.focus("%404"));
2571        assert_eq!(
2572            a.selected().map(|r| r.pane_id.as_str()),
2573            Some("%3"),
2574            "a pane that is not listed leaves the cursor alone"
2575        );
2576    }
2577
2578    /// The picker as `pick` opens it: a scan, plus where the pane it was opened
2579    /// from is, and no ● row because that pane runs no agent.
2580    fn app_at(tsv: &str, cwd: &str, target: &str) -> App {
2581        let mut a = app(tsv);
2582        a.src.cur_cwd = cwd.into();
2583        a.src.cur_target = target.into();
2584        a.focus_nearest();
2585        a
2586    }
2587
2588    fn on(a: &App) -> &str {
2589        a.selected().map(|r| r.pane_id.as_str()).unwrap_or("")
2590    }
2591
2592    /// Four sessions around one project tree, in a session the pane pressing F1
2593    /// is not in, so nothing but the directory can separate them.
2594    const TREE: &str = "%1\tw:1.1\t/h/notes\tclaude\t1\tidle\t-\tnotes\n\
2595                        %2\tw:2.1\t/h/proj/web\tclaude\t1\tidle\t-\tweb\n\
2596                        %3\tw:3.1\t/h/proj/web/docs\tclaude\t1\tidle\t-\tdocs\n\
2597                        %4\tw:4.1\t/h/proj\tclaude\t1\tidle\t-\tproj";
2598
2599    /// F1 from a shell: the pane it was pressed in runs no agent, so there is no
2600    /// ● row to open on, and the cursor used to land on whichever row the scan
2601    /// listed first, which is to say on nothing.
2602    #[test]
2603    fn a_pane_with_no_agent_opens_on_the_session_in_its_own_directory() {
2604        assert_eq!(on(&app_at(TREE, "/h/proj/web", "z:1.1")), "%2");
2605        // the same directory wins however it is written
2606        assert_eq!(on(&app_at(TREE, "/h/proj/web/", "z:1.1")), "%2");
2607        assert_eq!(on(&app_at(TREE, "/h/notes", "z:1.1")), "%1");
2608    }
2609
2610    /// Nothing is in the directory itself, so the nearest one is taken: DOWN the
2611    /// tree before up it, since the deeper session is the more specific answer
2612    /// and the parent is often just where several projects happen to live.
2613    #[test]
2614    fn a_subdirectory_beats_the_parent_directory() {
2615        let two = "%3\tw:3.1\t/h/proj/web/docs\tclaude\t1\tidle\t-\tdocs\n\
2616                   %4\tw:4.1\t/h/proj\tclaude\t1\tidle\t-\tproj";
2617        assert_eq!(on(&app_at(two, "/h/proj/web", "z:1.1")), "%3");
2618        // …and from deeper in, the session on the way back up
2619        assert_eq!(on(&app_at(TREE, "/h/proj/web/docs/api", "z:1.1")), "%3");
2620    }
2621
2622    /// The directory outranks the list: a session next door in the wrong tree is
2623    /// not the one you are working on.
2624    #[test]
2625    fn the_directory_outranks_how_near_the_pane_is() {
2626        let two = "%1\tw:1.1\t/h/proj\tclaude\t1\tidle\t-\tright tree\n\
2627                   %2\tw:4.1\t/h/other\tclaude\t1\tidle\t-\tnext door";
2628        assert_eq!(on(&app_at(two, "/h/proj", "w:5.1")), "%1");
2629    }
2630
2631    /// …and only then the list, which is what separates sessions the directory
2632    /// cannot: the same session first, nearest window in it, then anything else
2633    /// on this server, then another host, whose window numbers mean nothing here.
2634    #[test]
2635    fn equal_directories_are_separated_by_the_tmux_list() {
2636        let same = "%1\tother:1.1\t/h/proj\tclaude\t1\tidle\t-\tanother session\n\
2637                    %2\tw:9.1\t/h/proj\tclaude\t1\tidle\t-\tfar window\n\
2638                    %3\tw:2.1\t/h/proj\tclaude\t1\tidle\t-\tnext window";
2639        assert_eq!(on(&app_at(same, "/h/proj", "w:3.1")), "%3");
2640
2641        let remote = "ha:%9\tw:1.1\t/h/proj\tclaude\t1\tidle\t-\tover there\n\
2642                      %1\tother:1.1\t/h/proj\tclaude\t1\tidle\t-\there";
2643        assert_eq!(on(&app_at(remote, "/h/proj", "w:3.1")), "%1");
2644    }
2645
2646    /// A directory with nothing in common says nothing about which row is
2647    /// nearer, so the tie falls through to the list rather than to whichever
2648    /// session happens to sit closest to the root.
2649    #[test]
2650    fn a_directory_that_shares_nothing_falls_through_to_the_list() {
2651        let two = "%1\tw:1.1\t/h/a/b/c\tclaude\t1\tidle\t-\tdeep\n\
2652                   %2\tw:4.1\t/h/b\tclaude\t1\tidle\t-\tshallow";
2653        assert_eq!(on(&app_at(two, "/tmp/scratch", "w:5.1")), "%2");
2654    }
2655
2656    /// Not knowing where the pane is means not knowing: the cursor stays at the
2657    /// top rather than moving on a guess. That is every entry point but `pick`.
2658    #[test]
2659    fn an_unknown_position_leaves_the_cursor_at_the_top() {
2660        assert_eq!(on(&app_at(TREE, "", "")), "%1");
2661    }
2662
2663    const THREE: &str = "%1\ta:1.1\t/h\tclaude\t1\tidle\t-\tapple pie\n\
2664                         %2\tb:1.1\t/h\tclaude\t1\trun\t-\tbanana bread\n\
2665                         %3\tc:1.1\t/h\tclaude\t1\tinput\t-\tcherry tart";
2666
2667    /// The rows are fitted to the area they are drawn in, less the border and the
2668    /// pointer. Getting this wrong is invisible until a row is one column too
2669    /// long and the right-hand columns fall off.
2670    #[test]
2671    fn the_row_width_excludes_the_border_and_the_pointer() {
2672        assert_eq!(row_width(130), 126);
2673        assert_eq!(row_width(2), 0); // narrower than its own chrome
2674        assert_eq!(row_width(0), 0);
2675    }
2676
2677    #[test]
2678    fn tab_steps_round_the_cycle_and_starts_over() {
2679        let mut m = Mode::All;
2680        let seen: Vec<Mode> = (0..7)
2681            .map(|_| {
2682                m = m.next(true, true);
2683                m
2684            })
2685            .collect();
2686        assert_eq!(
2687            seen,
2688            vec![
2689                Mode::Input,
2690                Mode::Run,
2691                Mode::Idle,
2692                Mode::Background,
2693                Mode::Outdated,
2694                Mode::Dead,
2695                Mode::All
2696            ]
2697        );
2698    }
2699
2700    /// Shift-tab is the same ring read backwards, so a step each way from
2701    /// anywhere lands back where it started.
2702    #[test]
2703    fn shift_tab_steps_the_other_way_round_the_cycle() {
2704        let mut m = Mode::All;
2705        let seen: Vec<Mode> = (0..7)
2706            .map(|_| {
2707                m = m.prev(true, true);
2708                m
2709            })
2710            .collect();
2711        assert_eq!(
2712            seen,
2713            vec![
2714                Mode::Dead,
2715                Mode::Outdated,
2716                Mode::Background,
2717                Mode::Idle,
2718                Mode::Run,
2719                Mode::Input,
2720                Mode::All
2721            ]
2722        );
2723        for m in [
2724            Mode::All,
2725            Mode::Input,
2726            Mode::Run,
2727            Mode::Idle,
2728            Mode::Background,
2729            Mode::Outdated,
2730            Mode::Dead,
2731        ] {
2732            assert_eq!(m.next(true, true).prev(true, true), m);
2733            assert_eq!(m.prev(true, true).next(true, true), m);
2734        }
2735    }
2736
2737    /// Ended is skipped where there is nothing to show, rather than trapping the
2738    /// picker in a mode with no rows in it.
2739    #[test]
2740    fn the_ended_mode_is_skipped_without_a_sessions_cache() {
2741        assert_eq!(Mode::Background.next(false, false), Mode::All);
2742        assert_eq!(Mode::Background.next(true, false), Mode::Dead);
2743        // and backwards it is skipped the same way
2744        assert_eq!(Mode::All.prev(false, false), Mode::Background);
2745        assert_eq!(Mode::All.prev(true, false), Mode::Dead);
2746    }
2747
2748    /// …and so is outdated, where nothing is installed to judge a version
2749    /// against: every row would be measured against an empty version, so the
2750    /// list could only ever be empty.
2751    #[test]
2752    fn the_outdated_mode_is_skipped_when_no_version_is_installed() {
2753        assert_eq!(Mode::Background.next(false, true), Mode::Outdated);
2754        assert_eq!(Mode::Outdated.next(false, true), Mode::All);
2755        assert_eq!(Mode::Outdated.next(true, true), Mode::Dead);
2756        // both gates off: background is the last stop
2757        assert_eq!(Mode::Background.next(false, false), Mode::All);
2758        // …and going back from the first stop skips it just the same
2759        assert_eq!(Mode::All.prev(false, false), Mode::Background);
2760        assert_eq!(Mode::All.prev(false, true), Mode::Outdated);
2761    }
2762
2763    /// The background stop is never skipped, as no state stop is: it comes
2764    /// straight after idle whatever else is installed.
2765    #[test]
2766    fn the_background_mode_follows_idle_whatever_is_installed() {
2767        for (ended, outdated) in [(false, false), (true, false), (false, true), (true, true)] {
2768            assert_eq!(Mode::Idle.next(ended, outdated), Mode::Background);
2769            assert_eq!(Mode::Background.prev(ended, outdated), Mode::Idle);
2770        }
2771    }
2772
2773    #[test]
2774    fn the_label_says_which_list_and_what_is_on() {
2775        assert_eq!(
2776            label(Mode::All, false, false, false, false),
2777            " agent sessions "
2778        );
2779        assert_eq!(
2780            label(Mode::Input, false, true, false, false),
2781            " waiting for an answer · live "
2782        );
2783        assert_eq!(
2784            label(Mode::Outdated, false, false, false, false),
2785            " running outdated code "
2786        );
2787        assert_eq!(
2788            label(Mode::Background, false, false, false, false),
2789            " running background work "
2790        );
2791        assert_eq!(
2792            label(Mode::Dead, false, true, true, false),
2793            " past sessions · live · ⌕ "
2794        );
2795        // the order goes straight after the name, since it describes that list
2796        assert_eq!(
2797            label(Mode::Dead, true, true, true, false),
2798            " past sessions · by date · live · ⌕ "
2799        );
2800    }
2801
2802    /// Past conversations, newest first as the list arrives. Two SAY "tart", the
2803    /// older one where a word starts, which the matcher ranks higher; the newest
2804    /// of all only has its letters, scattered across four words.
2805    const PAST: &str =
2806        "dead:claude:/n.jsonl\t30m\t/h/a\tclaude\t1\tdead\t-\ttrial and error then tests\n\
2807         dead:claude:/r.jsonl\t1h\t/h/r\tclaude\t1\tdead\t-\trestart the ledger\n\
2808         dead:claude:/m.jsonl\t2d\t/h/b\tclaude\t1\tdead\t-\tapple pie\n\
2809         dead:claude:/o.jsonl\t9d\t/h/c\tclaude\t1\tdead\t-\tcherry tart";
2810
2811    fn app_past(query: &str) -> App {
2812        let mut a = app(THREE);
2813        a.src.ended = Some(Box::new(|| PAST.to_string()));
2814        a.mode = Mode::Dead;
2815        a.query = query.into();
2816        a.fetch();
2817        a.rebuild();
2818        a
2819    }
2820
2821    /// The reason for the key. A query ranks the past list best match first,
2822    /// which scatters what it keeps across the months; by date keeps the same
2823    /// matches, newest first, the order the list had before anything was typed.
2824    #[test]
2825    fn ctrl_s_keeps_the_past_list_newest_first_while_a_query_filters_it() {
2826        let mut a = app_past("tart");
2827        assert_eq!(
2828            ids(&a),
2829            [
2830                "dead:claude:/o.jsonl",
2831                "dead:claude:/r.jsonl",
2832                "dead:claude:/n.jsonl"
2833            ],
2834            "ranked, the word start wins, and the loose match comes last"
2835        );
2836        a.by_date = true;
2837        a.rebuild();
2838        assert_eq!(
2839            ids(&a),
2840            [
2841                "dead:claude:/r.jsonl",
2842                "dead:claude:/o.jsonl",
2843                "dead:claude:/n.jsonl"
2844            ],
2845            "by date, the two that say it newest first, THEN the loose one"
2846        );
2847        // …and typing more keeps that order rather than ranking again
2848        a.query = "tart e".into();
2849        a.query_changed();
2850        assert_eq!(
2851            ids(&a),
2852            [
2853                "dead:claude:/r.jsonl",
2854                "dead:claude:/o.jsonl",
2855                "dead:claude:/n.jsonl"
2856            ]
2857        );
2858    }
2859
2860    /// The past list leaves out a claude session still open in a pane, so a
2861    /// query whose only match is one of those used to read as a miss: a pasted
2862    /// merge request URL answered "Nothing matches" there while the session that
2863    /// opened it was one Tab away. Where the past list keeps nothing, it now
2864    /// counts what the live list would keep, and that live list is the next stop.
2865    #[test]
2866    fn an_empty_past_list_counts_the_live_sessions_the_query_matches() {
2867        // only the live "banana bread" says it
2868        let mut a = app_past("banana");
2869        assert!(a.view.is_empty(), "no past row says it: {:?}", ids(&a));
2870        assert_eq!(a.live_hits, 1);
2871        // …recounted as the query changes, on the path that only re-filters
2872        // too, which is the one typing takes with this list's search off
2873        a.query = "zzz".into();
2874        a.query_changed();
2875        assert_eq!(a.live_hits, 0, "nothing anywhere says that");
2876        a.query = "bread".into();
2877        a.query_changed();
2878        assert_eq!(a.live_hits, 1);
2879        // …and Tab from the past list does land on the live one, as the note says
2880        assert_eq!(Mode::Dead.next(true, true), Mode::All);
2881        assert_eq!(Mode::Dead.next(true, false), Mode::All);
2882        a.step_mode(false);
2883        assert_eq!(a.mode, Mode::All);
2884        assert_eq!(ids(&a), ["%2"]);
2885
2886        // a past list with a match of its own needs no pointer, even when a live
2887        // row says it too
2888        let b = app_past("tart");
2889        assert!(!b.view.is_empty());
2890        assert_eq!(b.live_hits, 0);
2891
2892        // and the live lists never count it: the rows there are the live ones
2893        let mut c = app(THREE);
2894        c.query = "zzz".into();
2895        c.query_changed();
2896        assert!(c.view.is_empty());
2897        assert_eq!(c.live_hits, 0);
2898    }
2899
2900    /// Why by date is not simply "leave every match where it stands". The
2901    /// letters of a query turn up scattered in rows that have nothing to do with
2902    /// it, and the ranking was what kept those under the rows that say it: tried
2903    /// on the real history without this, the top of the list was all noise. So
2904    /// the loose match stays last even as the newest row there is.
2905    #[test]
2906    fn by_date_keeps_the_loose_matches_under_the_ones_that_say_it() {
2907        let mut a = app_past("tart");
2908        a.by_date = true;
2909        a.rebuild();
2910        assert_eq!(
2911            ids(&a).last().map(String::as_str),
2912            Some("dead:claude:/n.jsonl")
2913        );
2914        // With nothing but loose matches, they are simply newest first.
2915        a.query = "tlr".into();
2916        a.query_changed();
2917        assert_eq!(ids(&a), ["dead:claude:/n.jsonl", "dead:claude:/r.jsonl"]);
2918    }
2919
2920    /// The cursor stays on the conversation it was on, so a second press lands
2921    /// exactly where the first one started.
2922    #[test]
2923    fn sorting_by_date_keeps_the_cursor_on_the_same_conversation() {
2924        let mut a = app_past("tart");
2925        assert_eq!(on(&a), "dead:claude:/o.jsonl");
2926        a.by_date = true;
2927        a.rebuild();
2928        assert_eq!(on(&a), "dead:claude:/o.jsonl");
2929        assert_eq!(a.sel, 1, "which is now below the newer one");
2930        a.by_date = false;
2931        a.rebuild();
2932        assert_eq!((on(&a), a.sel), ("dead:claude:/o.jsonl", 0));
2933    }
2934
2935    /// Only the idle and past lists sort by date. Left on through a Tab, the flag
2936    /// must not quietly stop the others ranking what a query keeps.
2937    #[test]
2938    fn by_date_leaves_the_other_lists_ranked() {
2939        let mut a = app("%1\ta:1.1\t/h\tclaude\t1\tidle\t-\trestart the ledger\n\
2940                         %2\tb:1.1\t/h\tclaude\t1\tidle\t-\tcherry tart");
2941        a.by_date = true;
2942        a.query = "tart".into();
2943        a.rebuild();
2944        assert!(!a.dated(), "all sessions at once is never in date order");
2945        assert_eq!(ids(&a), ["%2", "%1"], "so a query still ranks it");
2946        for m in [
2947            Mode::All,
2948            Mode::Input,
2949            Mode::Run,
2950            Mode::Background,
2951            Mode::Outdated,
2952        ] {
2953            assert!(!m.has_dates(), "{m:?}");
2954        }
2955        assert!(Mode::Idle.has_dates() && Mode::Dead.has_dates());
2956    }
2957
2958    /// Idle sessions in tmux order, as the scan lists them, each with when it
2959    /// last said something, except the codex one, which cannot say.
2960    const IDLE: &str = "%1\ta:1.1\t/h\tclaude\t1\tidle\t-\tapple pie\t1000\n\
2961                        %2\tb:1.1\t/h\tclaude\t1\tidle\t-\tbanana bread\t3000\n\
2962                        %3\tc:1.1\t/h\tcodex\t1\tidle\t-\tcherry tart\t-\n\
2963                        %4\td:1.1\t/h\tclaude\t1\tidle\t-\tdate loaf\t2000\n\
2964                        %5\te:1.1\t/h\tclaude\t1\trun\t-\telder cake\t9000";
2965
2966    /// The idle list by when each session last said something, newest first,
2967    /// with the one that cannot say after all of them. That list comes in tmux
2968    /// order, so unlike the past one it changes with no query typed at all.
2969    #[test]
2970    fn ctrl_s_orders_the_idle_list_by_the_last_message() {
2971        let mut a = app(IDLE);
2972        a.mode = Mode::Idle;
2973        a.rebuild();
2974        assert_eq!(ids(&a), ["%1", "%2", "%3", "%4"], "tmux order");
2975        a.by_date = true;
2976        a.rebuild();
2977        assert!(a.dated());
2978        assert_eq!(ids(&a), ["%2", "%4", "%1", "%3"]);
2979        // …and under a query: "a" is in every one of them as typed
2980        a.query = "a".into();
2981        a.query_changed();
2982        assert_eq!(ids(&a), ["%2", "%4", "%1", "%3"]);
2983    }
2984
2985    /// The race the past list's own buffer is for. A scan still out when Tab
2986    /// reaches that list lands afterwards, and it used to land ON it: "past
2987    /// sessions" showed live panes until the next tick.
2988    #[test]
2989    fn a_scan_that_lands_after_tab_leaves_the_past_list_alone() {
2990        let mut a = app(THREE);
2991        a.src.ended = Some(Box::new(|| PAST.to_string()));
2992        a.src.fetch = Arc::new(|| {
2993            std::thread::sleep(Duration::from_millis(150));
2994            THREE.to_string()
2995        });
2996        a.start_refresh();
2997        a.step_mode(true); // shift-tab from the first stop is the past list
2998        assert_eq!(a.mode, Mode::Dead);
2999        let past = ids(&a);
3000        assert_eq!(past.len(), 4);
3001        let mut landed = false;
3002        for _ in 0..100 {
3003            if a.take_refresh() {
3004                landed = true;
3005                break;
3006            }
3007            std::thread::sleep(Duration::from_millis(20));
3008        }
3009        assert!(landed, "the scan never arrived");
3010        a.rebuild();
3011        assert_eq!(ids(&a), past, "the past list is still the past list");
3012    }
3013
3014    /// …and the other way round. Leaving the past list used to draw ITS rows
3015    /// under the live label until a scan came back; the panes last seen are
3016    /// there at once instead.
3017    #[test]
3018    fn leaving_the_past_list_shows_the_panes_at_once() {
3019        let mut a = app_past("");
3020        a.step_mode(false); // tab from the last stop is back to all
3021        assert_eq!(a.mode, Mode::All);
3022        assert_eq!(ids(&a), ["%1", "%2", "%3"]);
3023    }
3024
3025    /// Every list searches what was said from an ordinary open, and ctrl-t flips
3026    /// the list on screen alone: turning it off to jump by name among the live
3027    /// sessions must leave the past list searching, and the other way round.
3028    #[test]
3029    fn ctrl_t_switches_the_list_on_screen_alone() {
3030        let mut a = app(THREE);
3031        (a.search, a.search_past) = (true, true); // an ordinary open, search allowed
3032        assert!(a.searching(), "a live list searches what was said");
3033        a.toggle_search();
3034        assert!(!a.searching(), "ctrl-t turns it off there");
3035        a.src.ended = Some(Box::new(|| PAST.to_string()));
3036        a.step_mode(true); // shift-tab from the first stop is the past list
3037        assert!(a.searching(), "…leaving the past list searching");
3038        a.toggle_search();
3039        assert!(!a.searching(), "ctrl-t turns the past list's off");
3040        a.step_mode(false); // back to all sessions
3041        a.toggle_search();
3042        assert!(a.searching(), "ctrl-t on a live list again");
3043        a.step_mode(true);
3044        assert!(!a.searching(), "…leaves the past list off, as it was left");
3045    }
3046
3047    /// The first scan places the cursor by the pane the picker was opened from,
3048    /// but not when it lands under the past list: none of the rows there is a
3049    /// pane, and moving the cursor anyway is a jump nobody asked for.
3050    #[test]
3051    fn the_first_scan_leaves_the_cursor_alone_on_the_past_list() {
3052        let mut a = app_past("");
3053        a.src.cur_cwd = "/h/c".into();
3054        a.open_on("%9");
3055        assert_eq!(a.sel, 0, "not moved to the row in that directory");
3056        // on a list of panes it does what it always did
3057        let mut b = app(TREE);
3058        b.src.cur_cwd = "/h/proj/web".into();
3059        b.open_on("%404");
3060        assert_eq!(on(&b), "%2");
3061    }
3062
3063    /// The list ctrl-x and F8 act on, gathered in one place. It crosses the four
3064    /// state modes, because being behind is not a state.
3065    #[test]
3066    fn the_outdated_mode_lists_the_rows_a_restart_would_act_on() {
3067        let mut a = app(VERSIONS);
3068        a.src.newver = "2.1.243".into();
3069        a.mode = Mode::Outdated;
3070        a.rebuild();
3071        assert_eq!(ids(&a), ["%1", "%2"], "behind, whatever they are doing");
3072
3073        // …and with nothing installed to compare against, nothing is behind.
3074        a.src.newver = String::new();
3075        a.rebuild();
3076        assert!(a.view.is_empty());
3077    }
3078
3079    /// The background stop lists the sessions that left work in flight, idle or
3080    /// working, and Tab lands on it straight from the idle one.
3081    #[test]
3082    fn the_background_mode_lists_the_sessions_with_work_in_flight() {
3083        let mut a = app("%1\ta:1.1\t/h\tclaude\t1\tidle\t-\twatching ci\t-\tbg\n\
3084                         %2\tb:1.1\t/h\tclaude\t1\tidle\t-\tall done\t-\t-\n\
3085                         %3\tc:1.1\t/h\tclaude\t1\trun\t-\tanother turn\t-\tbg\n\
3086                         %4\td:1.1\t/h\tcodex\t1\tidle\t-\tcannot say");
3087        a.mode = Mode::Idle;
3088        a.step_mode(false);
3089        assert_eq!(a.mode, Mode::Background);
3090        assert_eq!(
3091            ids(&a),
3092            ["%1", "%3"],
3093            "idle or working, whatever is still running"
3094        );
3095        // …and once that work has reported back the row drops out
3096        a.tsv = a.tsv.replace("watching ci\t-\tbg", "watching ci\t-\t-");
3097        a.rebuild();
3098        assert_eq!(ids(&a), ["%3"]);
3099    }
3100
3101    const VERSIONS: &str = "%1\ta:1.1\t/h\tclaude\t2.1.229\tidle\t-\tbehind\n\
3102                            %2\tb:1.1\t/h\tclaude\t2.1.229\tinput\t-\tbehind and asking\n\
3103                            %3\tc:1.1\t/h\tclaude\t2.1.243\trun\t-\tcurrent\n\
3104                            ha:%4\td:1.1\t/h\tclaude\t2.1.229\tidle\t-\tover there";
3105
3106    /// The stamp names the tool as well as the version, or a bare number in a
3107    /// corner would read as one more agent version like the ones down the right
3108    /// of every row. It is the crate version, which is what `taimux version`
3109    /// prints and what release-please bumps, so the three cannot drift.
3110    #[test]
3111    fn the_stamp_names_the_tool_and_carries_the_crate_version() {
3112        let tag = version_tag();
3113        assert!(tag.contains("taimux"));
3114        assert!(tag.contains(env!("CARGO_PKG_VERSION")));
3115        // padded both sides, so it does not touch the border corner
3116        assert!(tag.starts_with(' ') && tag.ends_with(' '));
3117    }
3118
3119    /// The stamp gives way to the count, never the other way round: ratatui
3120    /// gives a right-aligned title precedence, so without the check the count
3121    /// is what gets eaten, and the count is the live half.
3122    #[test]
3123    fn the_stamp_yields_to_the_count_on_a_narrow_border() {
3124        let count = " 5/5 ";
3125        let need = count.len() + version_tag().chars().count() + 2;
3126        assert!(room_for_tag(need as u16, count));
3127        assert!(!room_for_tag(need as u16 - 1, count));
3128        // a four-figure list needs more room for the same window
3129        assert!(!room_for_tag(need as u16, " 1000/1000 "));
3130        // and a window narrower than the stamp alone never gets it
3131        assert!(!room_for_tag(16, count));
3132    }
3133
3134    /// The header only ever advertises what is really bound: a key that does
3135    /// nothing is worse than a shorter header.
3136    #[test]
3137    fn the_header_advertises_only_bound_keys() {
3138        let bare = header(false, false, false, false, None);
3139        assert!(!bare.contains("ctrl-x"));
3140        assert!(!bare.contains("resume"));
3141        assert!(!bare.contains("ctrl-t"));
3142        assert!(!bare.contains("ctrl-s"));
3143        assert!(header(true, false, false, false, None).contains("ctrl-x"));
3144        assert!(header(false, true, false, false, None).contains("enter: switch/resume"));
3145        assert!(header(false, false, true, true, None).contains("(on)"));
3146        assert!(!header(false, false, true, false, None).contains("(on)"));
3147        // ctrl-s is bound on the past list, and only said there
3148        let past = header(false, true, false, false, Some(false));
3149        assert!(past.contains("ctrl-s: sort by date") && !past.contains("(on)"));
3150        assert!(header(false, true, false, false, Some(true)).contains("ctrl-s: sort by date (on)"));
3151    }
3152
3153    #[test]
3154    fn a_mode_shows_only_that_state() {
3155        let mut a = app(THREE);
3156        assert_eq!(a.view.len(), 3);
3157        a.mode = Mode::Run;
3158        a.rebuild();
3159        assert_eq!(a.view.len(), 1);
3160        assert!(a.selected().unwrap().plain().contains("banana"));
3161    }
3162
3163    #[test]
3164    fn the_query_filters_and_ranks() {
3165        let mut a = app(THREE);
3166        a.query = "banana".into();
3167        a.view = filter(&a.all, &a.query, &a.matcher, false);
3168        assert_eq!(a.view.len(), 1);
3169
3170        // an AND of terms, as fzf's extended search does, not one fuzzy match
3171        a.query = "apple tart".into();
3172        a.view = filter(&a.all, &a.query, &a.matcher, false);
3173        assert!(a.view.is_empty());
3174    }
3175
3176    #[test]
3177    fn no_query_keeps_the_lists_own_order() {
3178        let a = app(THREE);
3179        assert_eq!(a.view, vec![0, 1, 2]);
3180    }
3181
3182    /// A rebuild puts the cursor back on the same SESSION, not the same index.
3183    /// That is what --track --id-nth=2 buys fzf, and it matters because the
3184    /// refresh timer rebuilds under you while you are moving.
3185    #[test]
3186    fn a_rebuild_keeps_the_cursor_on_the_same_session() {
3187        let mut a = app(THREE);
3188        a.sel = 2;
3189        let was = a.selected().unwrap().pane_id.clone();
3190        // a session vanishes from the top of the list
3191        a.src = src("%2\tb:1.1\t/h\tclaude\t1\trun\t-\tbanana bread\n\
3192                     %3\tc:1.1\t/h\tclaude\t1\tinput\t-\tcherry tart");
3193        a.fetch();
3194        a.rebuild();
3195        assert_eq!(a.selected().unwrap().pane_id, was);
3196        assert_eq!(a.sel, 1);
3197    }
3198
3199    #[test]
3200    fn a_cursor_whose_row_is_gone_falls_back_to_the_top() {
3201        let mut a = app(THREE);
3202        a.sel = 2;
3203        a.src = src("%1\ta:1.1\t/h\tclaude\t1\tidle\t-\tapple pie");
3204        a.fetch();
3205        a.rebuild();
3206        assert_eq!(a.sel, 0);
3207    }
3208
3209    #[test]
3210    fn the_cursor_wraps_both_ways() {
3211        let mut a = app(THREE);
3212        a.move_by(-1);
3213        assert_eq!(a.sel, 2);
3214        a.move_by(1);
3215        assert_eq!(a.sel, 0);
3216    }
3217
3218    /// A page CLAMPS where a single step wraps, and the difference is the point:
3219    /// holding Page Down to reach the bottom of a long list must not sail past
3220    /// the end and land back at the top, with nothing on the row to say so.
3221    #[test]
3222    fn a_page_clamps_where_a_single_step_wraps() {
3223        let mut a = app(THREE);
3224        a.move_page(1, 2);
3225        assert_eq!(a.sel, 2);
3226        a.move_page(1, 2); // already at the end, and it stays there
3227        assert_eq!(a.sel, 2);
3228        a.move_page(-1, 2);
3229        assert_eq!(a.sel, 0);
3230        a.move_page(-1, 2);
3231        assert_eq!(a.sel, 0);
3232    }
3233
3234    /// A list drawn zero rows tall (a pane too short for one) would otherwise
3235    /// make the key do nothing at all, which reads as the key being unbound.
3236    #[test]
3237    fn a_page_of_no_rows_still_moves_one() {
3238        let mut a = app(THREE);
3239        a.move_page(1, 0);
3240        assert_eq!(a.sel, 1);
3241    }
3242
3243    /// Page Up and Page Down were the two keys the port dropped: fzf bound them
3244    /// itself, `Home` and `End` were ported by hand and these were not, so one
3245    /// pair kept working and the other went quiet. Nothing failed, which is why
3246    /// it took a report. The suite drives the real keys in a real terminal (see
3247    /// tests/run.sh); this is the arithmetic underneath.
3248    #[test]
3249    fn an_empty_view_pages_without_panicking() {
3250        let mut a = app(THREE);
3251        a.query = "zzzzz".into();
3252        a.query_changed();
3253        assert!(a.view.is_empty());
3254        a.move_page(1, 8);
3255        a.move_page(-1, 8);
3256        assert_eq!(a.sel, 0);
3257    }
3258
3259    /// An empty list must not be indexed into, and every key still has to work on
3260    /// one: a query that matches nothing is the ordinary way to get here.
3261    #[test]
3262    fn an_empty_view_is_safe_to_navigate() {
3263        let mut a = app(THREE);
3264        a.query = "zzzzz".into();
3265        a.view = filter(&a.all, &a.query, &a.matcher, false);
3266        assert!(a.view.is_empty());
3267        a.move_by(1);
3268        a.move_by(-1);
3269        a.clamp();
3270        assert!(a.selected().is_none());
3271    }
3272
3273    /// The padding `capture-pane` adds is what made every waiting session read as
3274    /// idle when the state reader was ported. Same capture, same trap, so the
3275    /// preview trims before it takes a tail.
3276    #[test]
3277    fn the_preview_tail_ignores_the_padding_capture_pane_adds() {
3278        let screen = "one\ntwo\nthree\n\n\n\n\n\n\n\n";
3279        let t = tail(screen, 2);
3280        let text: Vec<String> = t
3281            .iter()
3282            .map(|l| l.spans.iter().map(|s| s.content.to_string()).collect())
3283            .collect();
3284        assert_eq!(text, vec!["two", "three"]);
3285    }
3286
3287    #[test]
3288    fn a_screen_shorter_than_the_room_is_shown_whole() {
3289        assert_eq!(tail("one\ntwo\n", 40).len(), 2);
3290        assert!(tail("", 40).is_empty());
3291        assert!(tail("\n\n\n", 40).is_empty());
3292    }
3293
3294    /// The whole point of the exercise: a paste is text, never an Enter. Its
3295    /// first line joins the query and the rest is dropped, rather than being
3296    /// submitted into whatever is behind the picker.
3297    #[test]
3298    fn a_pasted_newline_stays_out_of_the_query() {
3299        let text = "set -g @plugin foo\rdo not write below this line";
3300        let first = text.split(['\r', '\n']).next().unwrap();
3301        assert_eq!(first, "set -g @plugin foo");
3302    }
3303}