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