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