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