kaeru 0.1.1

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
//! The picker's two screens: the waiting tabs, which the user picks from, and
//! the options. 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 agent's conversation was last used, such as `40 minutes ago`.
    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 {
    /// Done: 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; 4] = [
    "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 the tab of a single-window terminal that you closed",
];

/// 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,
    /// The line the cursor is on: a tab, by its place in `entries`, or the
    /// Done line, which comes right after the last tab.
    cursor: usize,
    /// The option the cursor is on, on the options screen.
    option: usize,
    /// The screen that shows.
    screen: Screen,
}

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

    /// Returns the cursor's place when it is on the Done line.
    fn done_line(&self) -> usize {
        self.entries.len()
    }

    /// 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);
                None
            }
        }
    }

    /// Handles a key on the tabs screen. Enter does what the cursor's line
    /// says: it checks or unchecks a tab, and on the Done line it finishes.
    fn press_on_tabs(&mut self, code: KeyCode) -> Option<Choice> {
        let done = self.done_line();
        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(done),
            KeyCode::Enter if self.cursor == done => return Some(Choice::Done),
            KeyCode::Char(' ') | KeyCode::Enter => {
                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('d') => return Some(Choice::Done),
            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.
    fn press_on_options(&mut self, code: KeyCode) {
        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 => self.screen = Screen::Tabs,
            _ => {}
        }
    }

    /// 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,
            _ => {
                config.single_window_close = match config.single_window_close {
                    SingleWindowClose::Forget => SingleWindowClose::Offer,
                    SingleWindowClose::Offer => SingleWindowClose::Forget,
                };
            }
        }
    }

    /// 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,
            _ => self.config.single_window_close == SingleWindowClose::Offer,
        }
    }

    /// 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 were_open = if count == 1 {
            "1 tab was open".to_string()
        } else {
            format!("{count} tabs were open")
        };
        let mut lines = vec![
            Line::from(format!(" 🐸 kaeru: {were_open} when your terminal closed")),
            Line::default(),
        ];
        let texts = columns(&self.entries);
        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());
        lines.push(Line::default());
        // 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(&[
            ("space", "check"),
            ("a", all),
            ("d", "done"),
            ("esc", "later"),
            ("o", "options"),
        ]));
        lines
    }

    /// Returns the Done line, which says what Done 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: Vec<(String, Color)> = [
            ("reopen", reopen, Color::Green),
            ("forget", forget, Color::Red),
        ]
        .into_iter()
        .filter(|&(_, count, _)| count > 0)
        .map(|(what, count, color)| (format!("{what} {count}"), color))
        .collect();
        if self.cursor == self.done_line() {
            let text: Vec<&str> = counts.iter().map(|(text, _)| text.as_str()).collect();
            let style = Style::new().add_modifier(Modifier::REVERSED | Modifier::BOLD);
            return Line::styled(format!("   Done: {}", text.join(", ")), style);
        }
        let mut spans = vec![
            Span::raw("   "),
            Span::styled("Done", Style::new().add_modifier(Modifier::BOLD)),
            Span::raw(": "),
        ];
        for (index, (text, color)) in counts.into_iter().enumerate() {
            if index > 0 {
                spans.push(Span::raw(", "));
            }
            spans.push(Span::styled(text, 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 = self.keys(&[("space", "change"), ("esc", "back")]);
        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 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!("   {mark} {text}"), reversed);
        }
        let color = if checked {
            Color::Green
        } else {
            Color::DarkGray
        };
        Line::from(vec![
            Span::raw("   "),
            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 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.
pub fn columns(entries: &[Entry]) -> 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());
        }
    }
    entries
        .iter()
        .map(|entry| {
            let shown: Vec<String> = cells(entry)
                .into_iter()
                .zip(widths)
                .filter(|&(_, width)| width > 0)
                .map(|(cell, width)| pad(cell, width))
                .collect();
            shown.join("   ").trim_end().to_string()
        })
        .collect()
}

/// 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 {
        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 keys
/// under the Done line show with it.
const LINES_BELOW_CURSOR: usize = 2;

/// 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 Done line of the tabs screen, as text.
    fn done_text(picker: &Picker) -> String {
        picker
            .tab_lines()
            .iter()
            .map(Line::to_string)
            .find(|line| line.trim_start().starts_with("Done"))
            .expect("the tabs screen has a Done line")
    }

    #[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 enter_checks_a_tab_and_finishes_on_the_done_line() {
        let mut picker = picker();
        picker.press(key(KeyCode::Up));
        assert_eq!(picker.press(key(KeyCode::Enter)), None);
        assert_eq!(picker.checked, [true, true, false]);
        picker.press(key(KeyCode::Down));
        assert_eq!(picker.press(key(KeyCode::Enter)), Some(Choice::Done));
    }

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

    #[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::Up));
        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"));
        picker.press(key(KeyCode::Char('a')));
        assert!(keys(&picker).contains("<a> check all"));
        picker.press(key(KeyCode::Up));
        picker.press(key(KeyCode::Char(' ')));
        assert!(
            keys(&picker).contains("<a> check all"),
            "some are still unchecked"
        );
    }

    #[test]
    fn the_cursor_stays_between_the_first_tab_and_the_done_line() {
        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));
        }
        assert_eq!(picker.press(key(KeyCode::Enter)), Some(Choice::Done));
    }

    #[test]
    fn each_choice_has_its_key() {
        let mut on_a_tab = picker();
        on_a_tab.press(key(KeyCode::Up));
        assert_eq!(on_a_tab.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_done_line_says_what_done_does() {
        let mut picker = picker();
        assert_eq!(done_text(&picker).trim(), "Done: reopen 3");
        picker.press(key(KeyCode::Up));
        picker.press(key(KeyCode::Char(' ')));
        assert_eq!(done_text(&picker).trim(), "Done: reopen 2, forget 1");
        picker.press(key(KeyCode::Char('a')));
        picker.press(key(KeyCode::Char('a')));
        assert_eq!(done_text(&picker).trim(), "Done: forget 3");
    }

    #[test]
    fn colors_mark_the_checkboxes_unless_they_are_off() {
        let mut picker = picker();
        picker.press(key(KeyCode::Up));
        picker.press(key(KeyCode::Up));
        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)[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_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 were open"));
        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 was open"));
        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::Up)),
            // 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 were open"));
    }

    #[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 Done, at the end 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("Done: reopen 30"));
        assert!(shown(&terminal).contains("<d> done"));
        // Up to the first tab, and the top of the list comes back.
        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::Up, 30).chain([KeyCode::Char('d')]);
        choose(&mut terminal, &mut picker, || {
            Ok(Event::Key(key(keys.next().unwrap())))
        })
        .unwrap();
        assert!(shown(&terminal).contains("tab-0 "));
        assert!(!shown(&terminal).contains("Done:"));
    }

    #[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()]),
            [
                r"api-server   Claude Code   40 minutes ago   ~\code\api-server   Windows Terminal"
                    .to_string(),
                format!(
                    r"web-ui{}PowerShell{}~\code\web-ui{}Windows Terminal",
                    gap(7),
                    gap(21),
                    gap(7)
                ),
            ]
        );
        assert_eq!(
            columns(&[shell]),
            [r"web-ui   PowerShell   ~\code\web-ui   Windows Terminal"]
        );
    }
}