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