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