kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! The picker's two screens: the waiting tabs, which the user picks from, and
//! the options, which `kaeru options` also shows by themselves. Its state
//! changes only through [`Picker::press`], so that the keys can be tested
//! without a terminal.

use std::ffi::OsStr;
use std::io;

use anyhow::Result;
use ratatui::Terminal;
use ratatui::backend::Backend;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use unicode_width::UnicodeWidthStr;

use crate::engine::config::Config;
use crate::engine::rules::SingleWindowClose;

/// One tab, as the picker shows it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    /// Whether an agent session ran in the tab, which puts the tab in the
    /// first section.
    pub agent: bool,
    /// The tab's name: its folder's name.
    pub name: String,
    /// What ran in the tab, such as `Claude Code` or `PowerShell`.
    pub what: String,
    /// When the tab was last used, such as `40 minutes ago`: when its agent's
    /// conversation last changed, or when its shell last showed a prompt.
    pub when: String,
    /// The tab's folder, with the home folder written as `~`.
    pub folder: String,
    /// The name of the terminal the tab ran in.
    pub terminal: String,
}

/// What the user chose.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Choice {
    /// Reopen the checked tabs, and forget the others.
    Done,
    /// Decide later. The tabs keep waiting.
    Later,
}

/// The picker's two screens.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Screen {
    Tabs,
    Options,
}

/// The options, in the order the options screen shows them.
const OPTIONS: [&str; 5] = [
    "Offer tabs that ran an agent session",
    "Offer tabs that ran only a shell",
    "Show this list in the first new tab after the terminal closes",
    "Offer Git Bash windows that you closed",
    "Start Codex with --no-daemon in the tabs that kaeru tracks",
];

/// How wide the start of a tab's line is: the cursor and the checkbox.
const CHECK_WIDTH: usize = 7;

/// What starts the line that the cursor is on, so that the cursor shows even
/// where the terminal's reversed colors are hard to see.
const CURSOR: &str = " > ";

/// What starts the other lines, as wide as [`CURSOR`].
const NO_CURSOR: &str = "   ";

/// The picker's state.
#[derive(Debug, Clone)]
pub struct Picker {
    /// The tabs, in the order they are shown: tabs with an agent session
    /// first.
    pub entries: Vec<Entry>,
    /// Which tabs are checked, by their place in `entries`.
    pub checked: Vec<bool>,
    /// The options, as the user left them.
    pub config: Config,
    /// Whether the picker uses colors. The cursor's line is reversed either
    /// way, which isn't a color.
    pub color: bool,
    /// How many columns the picker has, which the tabs' lines are fitted
    /// to, or 0 when that isn't known.
    pub width: usize,
    /// The tab the cursor is on, by its place in `entries`.
    cursor: usize,
    /// The option the cursor is on, on the options screen.
    option: usize,
    /// The screen that shows.
    screen: Screen,
    /// Whether only the options show, as for `kaeru options`, so that
    /// leaving them ends the picker.
    only_options: bool,
}

impl Picker {
    /// Returns a picker for these tabs, with every tab checked and the cursor
    /// on the first one, so that Enter brings every tab back.
    pub fn new(entries: Vec<Entry>, config: Config) -> Self {
        let checked = vec![true; entries.len()];
        Picker {
            entries,
            checked,
            config,
            color: true,
            width: 0,
            cursor: 0,
            option: 0,
            screen: Screen::Tabs,
            only_options: false,
        }
    }

    /// Returns a picker that shows only the options, for `kaeru options`.
    pub fn options(config: Config) -> Self {
        Picker {
            screen: Screen::Options,
            only_options: true,
            ..Picker::new(Vec::new(), config)
        }
    }

    /// Handles one key, and returns the user's choice once there is one.
    pub fn press(&mut self, key: KeyEvent) -> Option<Choice> {
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            return Some(Choice::Later);
        }
        match self.screen {
            Screen::Tabs => self.press_on_tabs(key.code),
            Screen::Options => self.press_on_options(key.code),
        }
    }

    /// Handles a key on the tabs screen. Space checks or unchecks the tab
    /// under the cursor, and Enter finishes, wherever the cursor is.
    fn press_on_tabs(&mut self, code: KeyCode) -> Option<Choice> {
        let last = self.entries.len().saturating_sub(1);
        match code {
            KeyCode::Up | KeyCode::Char('k') => self.cursor = self.cursor.saturating_sub(1),
            KeyCode::Down | KeyCode::Char('j') => self.cursor = (self.cursor + 1).min(last),
            KeyCode::Enter | KeyCode::Char('d') => return Some(Choice::Done),
            KeyCode::Char(' ') => {
                if let Some(checked) = self.checked.get_mut(self.cursor) {
                    *checked = !*checked;
                }
            }
            KeyCode::Char('a') => {
                let all = self.checked.iter().all(|checked| *checked);
                self.checked.fill(!all);
            }
            KeyCode::Char('n' | 'q') | KeyCode::Esc => return Some(Choice::Later),
            KeyCode::Char('o') => self.screen = Screen::Options,
            _ => {}
        }
        None
    }

    /// Handles a key on the options screen. Leaving it goes back to the
    /// tabs, or ends the picker when only the options show.
    fn press_on_options(&mut self, code: KeyCode) -> Option<Choice> {
        match code {
            KeyCode::Up | KeyCode::Char('k') => self.option = self.option.saturating_sub(1),
            KeyCode::Down | KeyCode::Char('j') => {
                self.option = (self.option + 1).min(OPTIONS.len() - 1);
            }
            KeyCode::Char(' ') | KeyCode::Enter => self.toggle_option(),
            KeyCode::Char('o' | 'q') | KeyCode::Esc if self.only_options => {
                return Some(Choice::Later);
            }
            KeyCode::Char('o' | 'q') | KeyCode::Esc => self.screen = Screen::Tabs,
            _ => {}
        }
        None
    }

    /// Changes the option that the cursor is on.
    fn toggle_option(&mut self) {
        let config = &mut self.config;
        match self.option {
            0 => config.offer_agents = !config.offer_agents,
            1 => config.offer_shells = !config.offer_shells,
            2 => config.ask_on_start = !config.ask_on_start,
            3 => {
                config.single_window_close = match config.single_window_close {
                    SingleWindowClose::Forget => SingleWindowClose::Offer,
                    SingleWindowClose::Offer => SingleWindowClose::Forget,
                };
            }
            _ => config.codex_no_daemon = !config.codex_no_daemon,
        }
    }

    /// Returns whether an option is on, by its place in `OPTIONS`.
    fn option_is_on(&self, index: usize) -> bool {
        match index {
            0 => self.config.offer_agents,
            1 => self.config.offer_shells,
            2 => self.config.ask_on_start,
            3 => self.config.single_window_close == SingleWindowClose::Offer,
            _ => self.config.codex_no_daemon,
        }
    }

    /// Returns the lines of the screen that shows.
    fn lines(&self) -> Vec<Line<'static>> {
        match self.screen {
            Screen::Tabs => self.tab_lines(),
            Screen::Options => self.option_lines(),
        }
    }

    /// Returns the lines of the tabs screen.
    fn tab_lines(&self) -> Vec<Line<'static>> {
        let count = self.entries.len();
        let tabs = if count == 1 {
            "1 tab".to_string()
        } else {
            format!("{count} tabs")
        };
        // When every tab ran in one terminal, the heading names it, and the
        // lines leave it out.
        let of = one_terminal(&self.entries)
            .map(|terminal| format!(" of {terminal}"))
            .unwrap_or_default();
        let mut lines = vec![
            Line::from(format!(" 🐸 kaeru: {tabs}{of} can come back")),
            Line::default(),
        ];
        let fit = (self.width > CHECK_WIDTH).then(|| self.width - CHECK_WIDTH);
        let texts = columns(&self.entries, fit);
        for (title, agent) in [("Agent sessions", true), ("Shells", false)] {
            let count = self
                .entries
                .iter()
                .filter(|entry| entry.agent == agent)
                .count();
            if count == 0 {
                continue;
            }
            let bold = Style::new().add_modifier(Modifier::BOLD);
            lines.push(Line::styled(format!("  {title} ({count})"), bold));
            for (index, entry) in self.entries.iter().enumerate() {
                if entry.agent == agent {
                    let under_cursor = index == self.cursor;
                    lines.push(self.check_line(self.checked[index], &texts[index], under_cursor));
                }
            }
        }
        lines.push(Line::default());
        lines.push(self.done_text());
        // The label says what a does next, as it flips every box one way.
        let all = if self.checked.iter().all(|checked| *checked) {
            "clear all"
        } else {
            "check all"
        };
        lines.push(self.keys(&[
            ("up/down", "move"),
            ("space", "check"),
            ("a", all),
            ("esc", "later"),
            ("o", "options"),
        ]));
        lines
    }

    /// Returns the line that says what Enter does: how many tabs it reopens,
    /// and how many it forgets.
    fn done_text(&self) -> Line<'static> {
        let reopen = self.checked.iter().filter(|checked| **checked).count();
        let forget = self.checked.len() - reopen;
        let counts = [
            ("reopen", reopen, Color::Green),
            ("forget", forget, Color::Red),
        ]
        .into_iter()
        .filter(|&(_, count, _)| count > 0);
        let mut spans = vec![
            Span::raw("  "),
            Span::styled("<enter>", self.paint(Color::Cyan)),
            Span::raw(" "),
        ];
        for (index, (what, count, color)) in counts.enumerate() {
            if index > 0 {
                spans.push(Span::raw(", "));
            }
            spans.push(Span::styled(format!("{what} {count}"), self.paint(color)));
        }
        Line::from(spans)
    }

    /// Returns the lines of the options screen.
    fn option_lines(&self) -> Vec<Line<'static>> {
        let mut lines = vec![Line::from(" 🐸 kaeru options"), Line::default()];
        for (index, option) in OPTIONS.iter().enumerate() {
            let under_cursor = index == self.option;
            lines.push(self.check_line(self.option_is_on(index), option, under_cursor));
        }
        lines.push(Line::default());
        let mut keys = if self.only_options {
            self.keys(&[("space", "change"), ("esc", "save and leave")])
        } else {
            self.keys(&[("space", "change"), ("esc", "back")])
        };
        if !self.only_options {
            keys.push_span("   (changes apply the next time this list opens)");
        }
        lines.push(keys);
        lines
    }

    /// Returns a line with a checkbox: `[x]` in green when it is checked, and
    /// `[ ]` dimmed when it isn't. The line the cursor is on starts with `>`
    /// and is reversed instead, without colors.
    fn check_line(&self, checked: bool, text: &str, under_cursor: bool) -> Line<'static> {
        let mark = if checked { "[x]" } else { "[ ]" };
        if under_cursor {
            let reversed = Style::new().add_modifier(Modifier::REVERSED);
            return Line::styled(format!("{CURSOR}{mark} {text}"), reversed);
        }
        let color = if checked {
            Color::Green
        } else {
            Color::DarkGray
        };
        Line::from(vec![
            Span::raw(NO_CURSOR),
            Span::styled(mark, self.paint(color)),
            Span::raw(format!(" {text}")),
        ])
    }

    /// Returns the line that lists the keys, with each key colored, so that
    /// it stands out from what it does.
    fn keys(&self, keys: &[(&str, &str)]) -> Line<'static> {
        let mut spans = vec![Span::raw("  ")];
        for (index, (key, action)) in keys.iter().enumerate() {
            if index > 0 {
                spans.push(Span::raw("   "));
            }
            spans.push(Span::styled(format!("<{key}>"), self.paint(Color::Cyan)));
            spans.push(Span::raw(format!(" {action}")));
        }
        Line::from(spans)
    }

    /// Returns a style with this text color, or no style when colors are
    /// off. These are the terminal's basic colors, which follow its color
    /// theme.
    fn paint(&self, color: Color) -> Style {
        if self.color {
            Style::new().fg(color)
        } else {
            Style::new()
        }
    }
}

/// Returns whether the picker may use colors, given the value of `NO_COLOR`:
/// not when it is set to anything, as <https://no-color.org> asks.
pub fn colors_allowed(no_color: Option<&OsStr>) -> bool {
    no_color.is_none_or(OsStr::is_empty)
}

/// Returns the terminal that every tab ran in, when they all ran in one.
pub fn one_terminal(entries: &[Entry]) -> Option<&str> {
    let first = &entries.first()?.terminal;
    entries
        .iter()
        .all(|entry| entry.terminal == *first)
        .then_some(first.as_str())
}

/// The column of folders, and of names, by their place in [`cells`].
const NAME: usize = 0;
const FOLDER: usize = 3;
const TERMINAL: usize = 4;

/// The gap between two columns.
const GAP: &str = "   ";

/// Returns each tab as one line of text, in columns that line up: its name,
/// what ran in it, when, its folder and its terminal. The picker and
/// `kaeru list` both show tabs this way. A column that is empty for every
/// tab is left out, and so is the terminal when every tab has the same one.
/// When the lines would be wider than `fit`, folders are shortened from the
/// left, since their ends say the most, and then names from the right.
pub fn columns(entries: &[Entry], fit: Option<usize>) -> Vec<String> {
    let mut widths = [0; 5];
    for entry in entries {
        for (width, cell) in widths.iter_mut().zip(cells(entry)) {
            *width = (*width).max(cell.width());
        }
    }
    if one_terminal(entries).is_some() {
        widths[TERMINAL] = 0;
    }
    if let Some(fit) = fit {
        let shown = widths.iter().filter(|width| **width > 0).count();
        let total = widths.iter().sum::<usize>() + GAP.len() * shown.saturating_sub(1);
        let mut over = total.saturating_sub(fit);
        for (column, least) in [(FOLDER, 12), (NAME, 10)] {
            let cut = over.min(widths[column].saturating_sub(least));
            widths[column] -= cut;
            over -= cut;
        }
    }
    entries
        .iter()
        .map(|entry| {
            let shown: Vec<String> = cells(entry)
                .into_iter()
                .zip(widths)
                .enumerate()
                .filter(|&(_, (_, width))| width > 0)
                .map(|(column, (cell, width))| pad(&shorten(cell, width, column == FOLDER), width))
                .collect();
            shown.join(GAP).trim_end().to_string()
        })
        .collect()
}

/// Returns `text` shortened to `width` columns with `...`, which replaces
/// its start when `keep_end` is set, and its end otherwise. Text that fits
/// stays as it is.
fn shorten(text: &str, width: usize, keep_end: bool) -> String {
    if text.width() <= width {
        return text.to_string();
    }
    let room = width.saturating_sub(3);
    let mut kept = Vec::new();
    let mut used = 0;
    let chars: Vec<char> = if keep_end {
        text.chars().rev().collect()
    } else {
        text.chars().collect()
    };
    for c in chars {
        let wide = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
        if used + wide > room {
            break;
        }
        used += wide;
        kept.push(c);
    }
    if keep_end {
        kept.reverse();
        format!("...{}", kept.into_iter().collect::<String>())
    } else {
        format!("{}...", kept.into_iter().collect::<String>())
    }
}

/// Returns the text of a tab's columns, in the order they are shown.
fn cells(entry: &Entry) -> [&str; 5] {
    [
        entry.name.as_str(),
        entry.what.as_str(),
        entry.when.as_str(),
        entry.folder.as_str(),
        entry.terminal.as_str(),
    ]
}

/// Returns `text` padded with spaces to `width` columns. Wide characters,
/// such as Korean, take two columns each.
fn pad(text: &str, width: usize) -> String {
    format!("{text}{}", " ".repeat(width.saturating_sub(text.width())))
}

/// Shows the picker until the user chooses, and returns the choice.
///
/// The picker shows on the terminal's alternate screen, as full-screen
/// programs do, so that the terminal brings back what the screen showed
/// before once the picker closes. Nothing of the picker stays behind then,
/// even when the window was resized while it showed.
///
/// # Errors
///
/// Fails when the terminal can't be drawn on or read from.
pub fn run(picker: &mut Picker) -> Result<Choice> {
    // A failed start may have set up part of the terminal already.
    let mut terminal = ratatui::try_init().inspect_err(|_| ratatui::restore())?;
    let choice = choose(&mut terminal, picker, event::read);
    ratatui::restore();
    choice
}

/// Draws the picker and reads events until the user chooses.
fn choose<B: Backend>(
    terminal: &mut Terminal<B>,
    picker: &mut Picker,
    mut read: impl FnMut() -> io::Result<Event>,
) -> Result<Choice>
where
    B::Error: Send + Sync + 'static,
{
    loop {
        picker.width = usize::from(terminal.size()?.width);
        let lines = picker.lines();
        terminal.draw(|frame| {
            let area = frame.area();
            let scroll = scroll_for(&lines, area.height);
            frame.render_widget(Paragraph::new(lines).scroll((scroll, 0)), area);
        })?;
        if let Event::Key(key) = read()?
            && key.kind == KeyEventKind::Press
            && let Some(choice) = picker.press(key)
        {
            return Ok(choice);
        }
    }
}

/// How many lines below the cursor's line stay in view, so that the last
/// tab shows with the lines below it.
const LINES_BELOW_CURSOR: usize = 3;

/// Returns how many lines to scroll the picker by, so that the line the
/// cursor is on, which is the reversed one, and a little below it fit on a
/// screen `height` lines tall. A list that fits doesn't scroll.
fn scroll_for(lines: &[Line], height: u16) -> u16 {
    let height = usize::from(height);
    if lines.len() <= height || height == 0 {
        return 0;
    }
    let cursor = lines
        .iter()
        .position(|line| line.style.add_modifier.contains(Modifier::REVERSED))
        .unwrap_or(0);
    let bottom = (cursor + LINES_BELOW_CURSOR).min(lines.len() - 1);
    u16::try_from((bottom + 1).saturating_sub(height)).unwrap_or(u16::MAX)
}

#[cfg(test)]
mod tests {
    use ratatui::backend::TestBackend;
    use ratatui::buffer::Cell;

    use super::*;

    fn entry(name: &str, agent: bool) -> Entry {
        Entry {
            agent,
            name: name.into(),
            what: if agent { "Claude Code" } else { "PowerShell" }.into(),
            when: String::new(),
            folder: format!(r"~\code\{name}"),
            terminal: "Windows Terminal".into(),
        }
    }

    fn picker() -> Picker {
        Picker::new(
            vec![
                entry("api-server", true),
                entry("web-ui", false),
                entry("프로젝트", false),
            ],
            Config::default(),
        )
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    /// Returns the line of the tabs screen that says what Enter does.
    fn done_text(picker: &Picker) -> String {
        picker
            .tab_lines()
            .iter()
            .map(Line::to_string)
            .find(|line| line.trim_start().starts_with("<enter>"))
            .expect("the tabs screen says what Enter does")
    }

    #[test]
    fn every_tab_starts_checked_and_enter_brings_them_all_back() {
        let mut picker = picker();
        assert_eq!(picker.checked, [true, true, true]);
        assert_eq!(picker.press(key(KeyCode::Enter)), Some(Choice::Done));
    }

    #[test]
    fn space_checks_the_tab_under_the_cursor_and_enter_finishes_anywhere() {
        let mut picker = picker();
        assert_eq!(picker.press(key(KeyCode::Char(' '))), None);
        assert_eq!(picker.checked, [false, true, true]);
        picker.press(key(KeyCode::Down));
        picker.press(key(KeyCode::Char(' ')));
        assert_eq!(picker.checked, [false, false, true]);
        assert_eq!(picker.press(key(KeyCode::Enter)), Some(Choice::Done));
    }

    #[test]
    fn a_checks_all_or_none() {
        let mut picker = picker();
        picker.press(key(KeyCode::Char('a')));
        assert_eq!(picker.checked, [false, false, false]);
        picker.press(key(KeyCode::Char(' ')));
        picker.press(key(KeyCode::Char('a')));
        assert_eq!(picker.checked, [true, true, true]);
    }

    #[test]
    fn the_all_key_says_what_it_does_next() {
        let keys = |picker: &Picker| picker.tab_lines().last().unwrap().to_string();
        let mut picker = picker();
        assert!(keys(&picker).contains("<a> clear all"));
        assert!(keys(&picker).contains("<up/down> move"));
        picker.press(key(KeyCode::Char('a')));
        assert!(keys(&picker).contains("<a> check all"));
        picker.press(key(KeyCode::Char(' ')));
        assert!(
            keys(&picker).contains("<a> check all"),
            "some are still unchecked"
        );
    }

    #[test]
    fn the_cursor_stays_between_the_first_and_the_last_tab() {
        let mut picker = picker();
        for _ in 0..5 {
            picker.press(key(KeyCode::Up));
        }
        picker.press(key(KeyCode::Char(' ')));
        assert_eq!(picker.checked, [false, true, true]);
        for _ in 0..5 {
            picker.press(key(KeyCode::Down));
        }
        picker.press(key(KeyCode::Char(' ')));
        assert_eq!(picker.checked, [false, true, false]);
    }

    #[test]
    fn each_choice_has_its_key() {
        assert_eq!(picker().press(key(KeyCode::Char('d'))), Some(Choice::Done));
        assert_eq!(picker().press(key(KeyCode::Char('n'))), Some(Choice::Later));
        assert_eq!(picker().press(key(KeyCode::Esc)), Some(Choice::Later));
        let control_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert_eq!(picker().press(control_c), Some(Choice::Later));
    }

    #[test]
    fn the_options_alone_change_and_end_with_esc() {
        let mut picker = Picker::options(Config::default());
        let shown: Vec<String> = picker.lines().iter().map(Line::to_string).collect();
        assert!(
            shown
                .iter()
                .any(|line| line.starts_with(" > [x] Offer tabs that ran an agent"))
        );
        assert!(
            shown
                .iter()
                .any(|line| line.contains("<esc> save and leave"))
        );
        for _ in 0..3 {
            picker.press(key(KeyCode::Down));
        }
        assert_eq!(picker.press(key(KeyCode::Char(' '))), None);
        assert_eq!(picker.config.single_window_close, SingleWindowClose::Offer);
        picker.press(key(KeyCode::Down));
        picker.press(key(KeyCode::Char(' ')));
        assert!(picker.config.codex_no_daemon);
        assert_eq!(picker.press(key(KeyCode::Esc)), Some(Choice::Later));
    }

    #[test]
    fn a_line_says_what_enter_does() {
        let mut picker = picker();
        assert_eq!(done_text(&picker).trim(), "<enter> reopen 3");
        picker.press(key(KeyCode::Char(' ')));
        assert_eq!(done_text(&picker).trim(), "<enter> reopen 2, forget 1");
        picker.press(key(KeyCode::Char('a')));
        picker.press(key(KeyCode::Char('a')));
        assert_eq!(done_text(&picker).trim(), "<enter> forget 3");
    }

    #[test]
    fn colors_mark_the_checkboxes_unless_they_are_off() {
        let mut picker = picker();
        picker.press(key(KeyCode::Down));
        picker.press(key(KeyCode::Char(' ')));
        let colors = |picker: &Picker| -> Vec<Color> {
            let lines = picker.tab_lines();
            let spans = lines.iter().flat_map(|line| &line.spans);
            spans.filter_map(|span| span.style.fg).collect()
        };
        assert!(colors(&picker).contains(&Color::Green));
        // The tab under the cursor is reversed, so its own colors would
        // turn into backgrounds.
        let reversed: Vec<String> = picker
            .tab_lines()
            .iter()
            .filter(|line| line.style.add_modifier.contains(Modifier::REVERSED))
            .map(Line::to_string)
            .collect();
        let web_ui = format!(" > [ ] {}", columns(&picker.entries, None)[1]);
        assert_eq!(reversed, [web_ui]);
        picker.color = false;
        assert!(colors(&picker).is_empty());
    }

    #[test]
    fn no_color_turns_colors_off() {
        assert!(colors_allowed(None));
        assert!(colors_allowed(Some(OsStr::new(""))));
        assert!(!colors_allowed(Some(OsStr::new("1"))));
    }

    #[test]
    fn options_change_on_their_own_screen() {
        let mut picker = picker();
        picker.press(key(KeyCode::Char('o')));
        picker.press(key(KeyCode::Down));
        picker.press(key(KeyCode::Char(' ')));
        assert!(!picker.config.offer_shells);
        assert_eq!(
            picker.press(key(KeyCode::Enter)),
            None,
            "Enter changes the option"
        );
        assert!(picker.config.offer_shells);
        picker.press(key(KeyCode::Esc));
        assert_eq!(picker.press(key(KeyCode::Enter)), Some(Choice::Done));
    }

    #[test]
    fn the_heading_names_the_terminal_that_every_tab_ran_in() {
        let heading = |picker: &Picker| picker.tab_lines()[0].to_string();
        assert!(heading(&picker()).contains("3 tabs of Windows Terminal can come back"));
        let mut mixed = vec![entry("web-ui", false), entry("api", false)];
        mixed[1].terminal = "Warp".into();
        let mixed = Picker::new(mixed, Config::default());
        assert!(heading(&mixed).contains("2 tabs can come back"));
        assert!(columns(&mixed.entries, None)[1].ends_with("Warp"));
    }

    #[test]
    fn the_list_has_a_section_for_each_kind_of_tab_with_its_count() {
        let text: Vec<String> = picker()
            .tab_lines()
            .iter()
            .map(|line| line.to_string())
            .collect();
        assert!(text[0].contains("3 tabs of Windows Terminal"));
        assert!(text.iter().any(|line| line == "  Agent sessions (1)"));
        assert!(text.iter().any(|line| line == "  Shells (2)"));
        let only_shells = Picker::new(vec![entry("web-ui", false)], Config::default());
        let text: Vec<String> = only_shells
            .tab_lines()
            .iter()
            .map(|line| line.to_string())
            .collect();
        assert!(text[0].contains("1 tab of Windows Terminal"));
        assert!(!text.iter().any(|line| line.starts_with("  Agent sessions")));
    }

    #[test]
    fn the_picker_shows_and_reads_key_presses_until_one_chooses() {
        let mut terminal = Terminal::new(TestBackend::new(80, 12)).unwrap();
        let mut picker = picker();
        let release =
            KeyEvent::new_with_kind(KeyCode::Up, KeyModifiers::NONE, KeyEventKind::Release);
        let mut events = [
            Event::FocusGained,
            Event::Key(key(KeyCode::Down)),
            Event::Key(key(KeyCode::Down)),
            // Windows also reports when a key is let go, which changes nothing.
            Event::Key(release),
            Event::Key(key(KeyCode::Char(' '))),
            Event::Key(key(KeyCode::Char('d'))),
        ]
        .into_iter();
        let read = || Ok(events.next().expect("d chooses"));
        let choice = choose(&mut terminal, &mut picker, read).unwrap();
        assert_eq!(choice, Choice::Done);
        assert_eq!(picker.checked, [true, true, false]);
        let shown: String = terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(Cell::symbol)
            .collect();
        assert!(shown.contains("3 tabs of Windows Terminal"));
    }

    #[test]
    fn a_long_list_scrolls_to_keep_the_cursor_in_view() {
        let entries: Vec<Entry> = (0..30).map(|i| entry(&format!("tab-{i}"), false)).collect();
        let mut picker = Picker::new(entries, Config::default());
        let mut terminal = Terminal::new(TestBackend::new(80, 10)).unwrap();
        let shown = |terminal: &Terminal<TestBackend>| -> String {
            terminal
                .backend()
                .buffer()
                .content
                .iter()
                .map(Cell::symbol)
                .collect()
        };
        // The cursor starts on the first tab, at the top of the list.
        let mut keys = [KeyCode::Char('d')].into_iter();
        choose(&mut terminal, &mut picker, || {
            Ok(Event::Key(key(keys.next().unwrap())))
        })
        .unwrap();
        assert!(shown(&terminal).contains("tab-0 "));
        assert!(!shown(&terminal).contains("reopen 30"));
        // Down to the last tab, and the end of the list shows.
        let mut picker = Picker::new(
            (0..30).map(|i| entry(&format!("tab-{i}"), false)).collect(),
            Config::default(),
        );
        let mut keys = std::iter::repeat_n(KeyCode::Down, 30).chain([KeyCode::Char('d')]);
        choose(&mut terminal, &mut picker, || {
            Ok(Event::Key(key(keys.next().unwrap())))
        })
        .unwrap();
        assert!(shown(&terminal).contains("tab-29 "));
        assert!(shown(&terminal).contains("<enter> reopen 30"));
    }

    #[test]
    fn a_list_that_fits_doesnt_scroll() {
        let lines = picker().tab_lines();
        assert_eq!(scroll_for(&lines, 40), 0);
    }

    #[test]
    fn wide_characters_are_padded_by_their_width() {
        assert_eq!(pad("프로", 6), "프로  ");
        assert_eq!(pad("web", 6), "web   ");
    }

    #[test]
    fn columns_line_up_and_leave_out_what_no_tab_has() {
        let mut agent = entry("api-server", true);
        agent.when = "40 minutes ago".into();
        let shell = entry("web-ui", false);
        let gap = |spaces: usize| " ".repeat(spaces);
        assert_eq!(
            columns(&[agent, shell.clone()], None),
            [
                r"api-server   Claude Code   40 minutes ago   ~\code\api-server".to_string(),
                format!(r"web-ui{}PowerShell{}~\code\web-ui", gap(7), gap(21)),
            ]
        );
        assert_eq!(
            columns(&[shell], None),
            [r"web-ui   PowerShell   ~\code\web-ui"]
        );
    }

    #[test]
    fn long_folders_are_shortened_from_the_left_to_fit() {
        let mut deep = entry("api-server", true);
        deep.folder = r"~\work\clients\demo\projects\api-server".into();
        let line = &columns(&[deep], Some(44))[0];
        assert_eq!(line, r"api-server   Claude Code   ...cts\api-server");
        assert!(line.width() <= 44);
        assert_eq!(shorten("프로젝트", 7, false), "프로...");
        assert_eq!(shorten("web-ui", 7, true), "web-ui");
    }
}