kaeru 0.1.5

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
//! What kaeru shows you: the picker, which `kaeru` and the first new tab after
//! the terminal closed show, what `kaeru list` prints, and the frog that
//! `kaeru install` starts with.

mod picker;

use std::io::{self, IsTerminal, Write};
use std::path::Path;
use std::process::ExitCode;
use std::time::{Duration, SystemTime};

use anyhow::{Context, Result};
use ratatui::crossterm::queue;
use ratatui::crossterm::style::{Color, Print, ResetColor, SetForegroundColor};

use crate::agents::Agent;
use crate::engine::note::{Note, ShellNote, TerminalRef};
use crate::engine::rules::Liveness;
use crate::engine::rules::TabState;
use crate::engine::tabs::{self, Seen, Tab};
use crate::os;
use crate::procs::{self, system::SystemTable};
use crate::shells::{self, Shell};
use crate::store::{self, Store, StoredNote};
use crate::terminals::{self, Env, TabToOpen};
use picker::{Choice, Entry, Picker};

/// The exit code with which `kaeru` tells the shell snippet to close its tab:
/// a new tab that only showed the picker, and whose tabs all came back in its
/// own window, would otherwise be one tab more than there were.
pub const CLOSE_THIS_TAB: u8 = 4;

/// The variable that the snippet sets for `kaeru` when it shows the picker by
/// itself, in a new tab.
const NEW_TAB_VAR: &str = "KAERU_NEW_TAB";

/// The variable in which the bash snippet tells `kaeru` the process id of
/// the shell that shows the picker. Through `winpty`, kaeru's own lineage
/// doesn't lead back to that shell.
const SHELL_PID_VAR: &str = "KAERU_SHELL_PID";

/// How long kaeru waits between two tabs that it reopens. Each tab starts a
/// shell, and maybe an agent, so opening them all at once can load a slow
/// computer heavily.
const PAUSE: Duration = Duration::from_secs(1);

/// Shows the tabs that are waiting to come back, and reopens the ones that
/// the user picks, for `kaeru`. Without a terminal to draw in, it only lists
/// them. It exits with [`CLOSE_THIS_TAB`] when the snippet should close the
/// tab it ran in.
///
/// # Errors
///
/// Fails when the state folder or the session id can't be read, the picker
/// can't be drawn, or a terminal can't open the tabs.
pub fn pick() -> Result<ExitCode> {
    let store = Store::open()?;
    let config = store.config();
    let env: Env = std::env::vars().collect();
    let mut table = SystemTable::snapshot();
    // A terminal that brings back its own tabs may still be starting them,
    // and each of them takes over its notes as it starts.
    let lineage = table.lineage(std::process::id());
    if let Some((_, terminal)) = terminals::tab_of(&terminals::all(), &env, &lineage) {
        let wait = shells::restore_settle(&terminal, shells::now_ms());
        if !wait.is_zero() {
            std::thread::sleep(wait);
            table = SystemTable::snapshot();
        }
    }
    let session = os::session_id()?;
    let reviewed = store::review(&store, &table, &session, config.single_window_close);
    let waiting: Vec<StoredNote> = reviewed
        .iter()
        .filter(|one| one.state == TabState::Waiting)
        .filter(|one| !shells::left_to_its_terminal(&one.stored.note, &reviewed))
        .map(|one| one.stored.clone())
        .collect();
    let notes: Vec<(Note, Seen)> = waiting
        .iter()
        .map(|stored| (stored.note.clone(), store::last_seen(stored)))
        .collect();
    let tabs = tabs::to_offer(&notes, &config);
    if tabs.is_empty() {
        // Notes that the options leave out would never come back.
        for stored in &waiting {
            store.remove(stored);
        }
        // A new tab that showed the list by itself found the tabs gone
        // meanwhile, as when their terminal brought them back itself, and
        // has nothing to say.
        if !env.contains_key(NEW_TAB_VAR) {
            println!("No tabs are waiting to come back. To change the options, run kaeru options.");
        }
        return Ok(ExitCode::SUCCESS);
    }
    let entries: Vec<Entry> = tabs.iter().map(entry).collect();
    if !can_draw() {
        for line in picker::columns(&entries) {
            println!("{line}");
        }
        if std::env::var_os("MSYSTEM").is_some() && std::io::stdin().is_terminal() {
            println!("To choose which tabs to reopen, run winpty kaeru in this window.");
        } else {
            println!("Run kaeru in a terminal to choose which tabs to reopen.");
        }
        return Ok(ExitCode::SUCCESS);
    }
    // Held until the tabs are reopened, so that two pickers never reopen the
    // same tabs, and so that a new tab doesn't ask while this one does.
    let Some(_lock) = store.try_lock()? else {
        println!("kaeru's list is already open in another tab. Choose there, or close it first.");
        return Ok(ExitCode::SUCCESS);
    };
    let mut picker = Picker::new(entries, config);
    picker.color = colors_wanted();
    let choice = picker::run(&mut picker)?;
    if picker.config != config {
        store.save_config(&picker.config)?;
    }
    if choice == Choice::Later {
        return Ok(ExitCode::SUCCESS);
    }
    let to_open = in_opening_order(&tabs, &picker.checked);
    let shells: Vec<ShellNote> = store
        .notes()
        .into_iter()
        .filter_map(|stored| match stored.note {
            Note::Shell(shell) => Some(shell),
            Note::Agent(_) => None,
        })
        .collect();
    // The shell that shows the picker, and its tab's terminal.
    let lineage = table.lineage(std::process::id());
    let found = terminals::tab_or_noted(&terminals::all(), &env, &lineage, &shells);
    let asking = env
        .get(SHELL_PID_VAR)
        .and_then(|pid| pid.parse::<u32>().ok())
        .or_else(|| {
            let (index, _) = found.as_ref()?;
            Some(lineage.get(*index)?.pid)
        });
    let here = found.map(|(_, terminal)| terminal).or_else(|| {
        shells
            .iter()
            .find(|shell| Some(shell.process.pid) == asking)?
            .terminal
            .clone()
    });
    // The tab closes only when it was new and every tab came back next to it.
    let close = env.contains_key(NEW_TAB_VAR)
        && !to_open.is_empty()
        && to_open.iter().all(|tab| {
            here.as_ref()
                .is_some_and(|here| same_terminal(here, &tab.terminal))
        });
    let reopened = reopen(&store, &waiting, &to_open)?;
    let forgotten = picker.checked.iter().filter(|checked| !**checked).count();
    if forgotten > 0 {
        println!("Forgot {}.", count(forgotten));
    }
    if close && reopened == to_open.len() {
        // The tab goes away on purpose, so its note goes too, so that it
        // isn't offered when kaeru offers closed single windows.
        for stored in store.notes() {
            if let Note::Shell(shell) = &stored.note
                && Some(shell.process.pid) == asking
            {
                store.remove(&stored);
            }
        }
        Ok(ExitCode::from(CLOSE_THIS_TAB))
    } else {
        Ok(ExitCode::SUCCESS)
    }
}

/// Returns the checked tabs in the order they were first opened, which is the
/// order they come back in. Terminals don't tell kaeru where a tab sat, so a
/// tab that was moved comes back where it was first opened.
fn in_opening_order<'a>(tabs: &'a [Tab], checked: &[bool]) -> Vec<&'a Tab> {
    let mut chosen: Vec<&Tab> = tabs
        .iter()
        .zip(checked)
        .filter(|(_, checked)| **checked)
        .map(|(tab, _)| tab)
        .collect();
    chosen.sort_by_key(|tab| tab.started_ms);
    chosen
}

/// Returns whether two tabs are in the same copy of the same terminal.
fn same_terminal(a: &TerminalRef, b: &TerminalRef) -> bool {
    a.adapter == b.adapter
        && a.exe.as_deref().map(str::to_ascii_lowercase)
            == b.exe.as_deref().map(str::to_ascii_lowercase)
}

/// Reopens tabs one at a time, each in the terminal it came from, with a
/// pause between them, and returns how many came back. The waiting notes of
/// tabs that weren't chosen are deleted first, which forgets them. A chosen
/// tab's notes are deleted just before the tab opens, so that the new tab
/// doesn't ask about them again, and so that the tabs not opened yet keep
/// waiting if kaeru is stopped partway. The notes of tabs that couldn't be
/// opened are written back, so that those tabs keep waiting.
///
/// # Errors
///
/// Fails, after trying every tab, when a terminal couldn't open one.
fn reopen(store: &Store, waiting: &[StoredNote], tabs: &[&Tab]) -> Result<usize> {
    let chosen: Vec<usize> = tabs
        .iter()
        .flat_map(|tab| tab.notes.iter().copied())
        .collect();
    for (index, stored) in waiting.iter().enumerate() {
        if !chosen.contains(&index) {
            store.remove(stored);
        }
    }
    let adapters = terminals::all();
    let mut opened = 0;
    let mut failure = None;
    for (number, tab) in tabs.iter().enumerate() {
        if number > 0 {
            std::thread::sleep(PAUSE);
        }
        // A shell note keeps the folder its tab was last in, in case the tab
        // can't open and the note is written back.
        let notes: Vec<Note> = tab
            .notes
            .iter()
            .map(|&index| {
                let mut note = waiting[index].note.clone();
                if let Note::Shell(shell) = &mut note {
                    shell.cwd = store::last_seen(&waiting[index]).cwd;
                }
                note
            })
            .collect();
        for &index in &tab.notes {
            store.remove(&waiting[index]);
        }
        if !Path::new(&tab.cwd).is_dir() {
            println!("Not reopened, because its folder is gone: {}", tab.cwd);
            continue;
        }
        println!(
            "Reopening {} of {}: {}",
            number + 1,
            tabs.len(),
            folder_name(&tab.cwd)
        );
        let id = tab.terminal.adapter.as_str();
        let result = match adapters.iter().find(|adapter| adapter.id() == id) {
            Some(adapter) => {
                let exe = tab.terminal.exe.as_deref().map(Path::new);
                let mut open = tab_to_open(tab);
                if runs_in_bash(&open, &tab.terminal) {
                    shells::write_bash_run_file(store.dir(), &open.cwd, &open.run).map(|file| {
                        open.rcfile = Some(file.display().to_string());
                    })?;
                }
                adapter.reopen(exe, &[open])
            }
            None => Err(anyhow::anyhow!(
                "this version of kaeru doesn't know the terminal {id}"
            )),
        };
        match result {
            Ok(()) => opened += 1,
            Err(error) => {
                for note in &notes {
                    let _ = store.save(note);
                }
                failure.get_or_insert(error);
            }
        }
    }
    if opened > 0 {
        println!("Reopened {}.", count(opened));
    }
    failure.map_or(Ok(opened), Err)
}

/// Returns what a terminal needs to know to open a tab again.
fn tab_to_open(tab: &Tab) -> TabToOpen {
    let run = tab
        .agent
        .as_ref()
        .and_then(|note| Some(Agent::from_id(&note.agent)?.resume_command(note)))
        .unwrap_or_default();
    TabToOpen {
        title: folder_name(&tab.cwd).to_string(),
        cwd: tab.cwd.clone(),
        profile: tab.terminal.profile.clone(),
        shell: tab.shell.clone(),
        run,
        shell_exe: tab.agent.as_ref().and_then(|note| note.shell_exe.clone()),
        rcfile: None,
    }
}

/// Returns whether a tab that runs something comes back in bash, which then
/// reads a file that kaeru writes: when its shell was bash, and in mintty,
/// whose windows run bash.
fn runs_in_bash(tab: &TabToOpen, terminal: &TerminalRef) -> bool {
    !tab.run.is_empty()
        && (tab
            .shell
            .as_deref()
            .is_some_and(|shell| shell.eq_ignore_ascii_case("bash"))
            || terminal.adapter == "mintty")
}

/// Returns a tab as the picker shows it.
fn entry(tab: &Tab) -> Entry {
    let (what, when) = match &tab.agent {
        Some(note) => match Agent::from_id(&note.agent) {
            Some(agent) => {
                let when = agent
                    .conversation_file(note)
                    .map_or_else(|| "no messages yet".to_string(), |file| last_used(&file));
                (agent.name().to_string(), when)
            }
            None => (note.agent.clone(), String::new()),
        },
        None => (shell_name(tab.shell.as_deref()), String::new()),
    };
    Entry {
        agent: tab.agent.is_some(),
        name: folder_name(&tab.cwd).to_string(),
        what,
        when,
        folder: home_as_tilde(&tab.cwd),
        terminal: terminals::name_of(&tab.terminal.adapter),
    }
}

/// Prints the tabs that kaeru tracks, one line each, for `kaeru list`: the
/// open ones, and the ones waiting to come back, which are the tabs that
/// `kaeru` offers. Like every run, it first deletes the notes of closed tabs.
///
/// # Errors
///
/// Fails when the state folder or the session id can't be read.
pub fn list() -> Result<()> {
    let store = Store::open()?;
    let config = store.config();
    let table = SystemTable::snapshot();
    let session = os::session_id()?;
    let reviewed = store::review(&store, &table, &session, config.single_window_close);
    let notes_in = |state: TabState| -> Vec<(Note, Seen)> {
        reviewed
            .iter()
            .filter(|reviewed| reviewed.state == state)
            .map(|reviewed| {
                (
                    reviewed.stored.note.clone(),
                    store::last_seen(&reviewed.stored),
                )
            })
            .collect()
    };
    let open = tabs::group(&notes_in(TabState::Open));
    let waiting = tabs::to_offer(&notes_in(TabState::Waiting), &config);
    if open.is_empty() && waiting.is_empty() {
        println!("No tabs are tracked yet.");
        return Ok(());
    }
    // One set of columns for both lists, so that they line up.
    let entries: Vec<Entry> = open.iter().chain(&waiting).map(entry).collect();
    let lines = picker::columns(&entries);
    let (open_lines, waiting_lines) = lines.split_at(open.len());
    for (title, lines) in [
        ("Open", open_lines),
        ("Waiting to come back", waiting_lines),
    ] {
        if !lines.is_empty() {
            println!("{title}:");
            for line in lines {
                println!("  {line}");
            }
        }
    }
    Ok(())
}

/// kaeru's frog, line by line, with the text to its right: kaeru's name and
/// what it does. The frog's lines have one width, so that the text lines up.
const GREETING: [(&str, &str); 4] = [
    ("   (o)____(o)  ", " kaeru"),
    (
        "  /          \\ ",
        " Your tabs come back after the terminal closes.",
    ),
    (" |  \\______/  |", ""),
    ("  \\__________/ ", ""),
];

/// Prints kaeru's frog, with kaeru's name and what it does to its right,
/// which `kaeru install` shows first. The frog is in the terminal's green,
/// unless colors are off or the output isn't a terminal.
///
/// # Errors
///
/// Fails when standard output can't be written to.
pub fn greet() -> io::Result<()> {
    let color = colors_wanted() && io::stdout().is_terminal();
    let mut out = io::stdout().lock();
    for (frog, text) in GREETING {
        let frog = if text.is_empty() {
            frog.trim_end()
        } else {
            frog
        };
        if color {
            queue!(
                out,
                SetForegroundColor(Color::DarkGreen),
                Print(frog),
                ResetColor
            )?;
        } else {
            queue!(out, Print(frog))?;
        }
        queue!(out, Print(text), Print("\n"))?;
    }
    queue!(out, Print("\n"))?;
    out.flush()
}

/// Resumes, in this tab, the agent session that ran in it before its
/// terminal restored the tab by itself, for `kaeru resume`. kaeru doesn't do
/// this by itself, because a terminal sends a tab input while it sets the tab
/// up, which a question would read as its answer, so a restored tab only says
/// that you can run `kaeru resume`.
///
/// With `shell`, kaeru prints the code that resumes the session for that
/// shell to run, and its messages go to stderr. The snippet's `kaeru`
/// function runs `kaeru resume` that way, so that the session runs in the
/// tab's shell, as if you typed its command, and no kaeru process waits
/// while it runs. A kaeru that waits would keep its own file in use, and on
/// Windows, an update can't replace a file that is in use.
///
/// # Errors
///
/// Fails when the state folder or the session id can't be read, or the
/// agent can't be started.
pub fn resume(shell: Option<Shell>) -> Result<ExitCode> {
    // What the shell runs goes to stdout, so with a shell, the messages for
    // you go to stderr, which the shell shows.
    let say = |message: String| {
        if shell.is_some() {
            eprintln!("{message}");
        } else {
            println!("{message}");
        }
    };
    let store = Store::open()?;
    let config = store.config();
    let mut table = SystemTable::snapshot();
    let session = os::session_id()?;
    let env: Env = std::env::vars().collect();
    let lineage = table.lineage(std::process::id());
    let Some(here) = terminals::tab_of(&terminals::all(), &env, &lineage)
        .map(|(_, terminal)| terminal)
        .filter(|terminal| terminal.tab_id.is_some())
    else {
        say("This isn't a tab that its terminal restored, so no session waits in it.".into());
        return Ok(ExitCode::SUCCESS);
    };
    let reviewed = store::review(&store, &table, &session, config.single_window_close);
    // The session ran in this tab in the terminal's run before: the same tab
    // id, from a terminal process that is gone. It waits, or it still runs
    // without a window, because that terminal ended without ending it.
    let found = reviewed.into_iter().find_map(|reviewed| {
        let Note::Agent(note) = &reviewed.stored.note else {
            return None;
        };
        let old = note.terminal.as_ref()?;
        let from_before = old.adapter == here.adapter
            && old.tab_id == here.tab_id
            && old.process != here.process
            && procs::liveness(&table, &old.process) != Liveness::Running;
        let orphan = procs::liveness(&table, &note.process) == Liveness::Running;
        (from_before && (reviewed.state == TabState::Waiting || orphan))
            .then(|| (reviewed.stored.clone(), note.clone(), orphan))
    });
    let Some((stored, note, orphan)) = found else {
        say("No agent session waits to be resumed in this tab.".into());
        return Ok(ExitCode::SUCCESS);
    };
    let Some(agent) = Agent::from_id(&note.agent) else {
        return Ok(ExitCode::SUCCESS);
    };
    if orphan {
        // Two processes on one conversation would get in each other's way,
        // so the one without a window ends first, and its shell with it.
        table.end(&note.process);
        if let Some(shell) = &note.shell {
            table.end(shell);
        }
        std::thread::sleep(PAUSE);
        say(format!(
            "Ended the {} session that ran without a window.",
            agent.name()
        ));
    }
    store.remove(&stored);
    let note = &note;
    let words = agent.resume_command(note);
    say(format!(
        "Resuming the {} session: {}",
        agent.name(),
        words.join(" ")
    ));
    if let Some(shell) = shell {
        println!("{}", shells::run_code(shell, &note.cwd, &words)?);
        return Ok(ExitCode::SUCCESS);
    }
    let status = command_for(&words)?
        .current_dir(&note.cwd)
        .status()
        .with_context(|| format!("can't start {}", words.join(" ")))?;
    Ok(ExitCode::from(
        status
            .code()
            .and_then(|code| u8::try_from(code).ok())
            .unwrap_or(1),
    ))
}

/// Returns the command that runs these words, the program first. On
/// Windows, the program is looked up on the PATH with the extensions in
/// `PATHEXT`, because agents that npm installs are `.cmd` files, which run
/// through `cmd.exe`.
fn command_for(words: &[String]) -> Result<std::process::Command> {
    let (program, arguments) = words.split_first().context("there is nothing to run")?;
    if cfg!(windows)
        && let Some(found) = find_program(program)
    {
        let extension = found
            .extension()
            .map(|extension| extension.to_string_lossy().to_ascii_lowercase());
        if matches!(extension.as_deref(), Some("cmd" | "bat")) {
            let mut command = std::process::Command::new("cmd.exe");
            command.arg("/c").arg(found).args(arguments);
            return Ok(command);
        }
        let mut command = std::process::Command::new(found);
        command.args(arguments);
        return Ok(command);
    }
    let mut command = std::process::Command::new(program);
    command.args(arguments);
    Ok(command)
}

/// Returns where a program is on the PATH, with the first extension in
/// `PATHEXT` that exists, as Windows looks programs up.
fn find_program(program: &str) -> Option<std::path::PathBuf> {
    let extensions = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
    std::env::split_paths(&std::env::var_os("PATH")?).find_map(|folder| {
        extensions
            .split(';')
            .filter(|extension| !extension.is_empty())
            .map(|extension| folder.join(format!("{program}{extension}")))
            .find(|candidate| candidate.is_file())
    })
}

/// Shows the options and saves them when the user leaves, for
/// `kaeru options`. Without a terminal to draw in, it prints them.
///
/// # Errors
///
/// Fails when the state folder can't be opened, the options can't be drawn,
/// or they can't be saved.
pub fn options() -> Result<()> {
    let store = Store::open()?;
    let config = store.config();
    if !can_draw() {
        print!("{}", toml::to_string(&config)?);
        if std::env::var_os("MSYSTEM").is_some() && io::stdin().is_terminal() {
            println!(
                "These are kaeru's options. To change them in this window, run winpty kaeru options."
            );
        } else {
            println!("These are kaeru's options. Run kaeru options in a terminal to change them.");
        }
        return Ok(());
    }
    let mut picker = Picker::options(config);
    picker.color = colors_wanted();
    picker::run(&mut picker)?;
    if picker.config == config {
        println!("The options stay as they were.");
    } else {
        store.save_config(&picker.config)?;
        println!("Saved the options.");
    }
    Ok(())
}

/// Returns whether kaeru can draw the picker: its input and output are a
/// terminal, and on Windows, its input is a console. In mintty, a Windows
/// program reads from a pipe that Rust counts as a terminal, but the picker
/// can't draw there without `winpty`.
fn can_draw() -> bool {
    let console = cfg!(not(windows)) || console_input();
    io::stdin().is_terminal() && io::stdout().is_terminal() && console
}

/// Returns whether kaeru's input is a Windows console.
#[cfg(windows)]
fn console_input() -> bool {
    os::has_console_input()
}

/// Returns true: only Windows has consoles.
#[cfg(not(windows))]
fn console_input() -> bool {
    true
}

/// Returns whether kaeru may use colors, which it may unless `NO_COLOR` is
/// set to something.
fn colors_wanted() -> bool {
    picker::colors_allowed(std::env::var_os("NO_COLOR").as_deref())
}

/// Returns a shell's name as the picker shows it, such as `PowerShell`.
fn shell_name(shell: Option<&str>) -> String {
    match shell {
        Some(shell)
            if shell.eq_ignore_ascii_case("powershell") || shell.eq_ignore_ascii_case("pwsh") =>
        {
            "PowerShell".into()
        }
        Some(shell) if shell.eq_ignore_ascii_case("bash") => "Bash".into(),
        Some(shell) => shell.into(),
        None => "shell".into(),
    }
}

/// Returns the last part of a folder's path, which names the tab. It works
/// for `\` and `/`, whichever OS wrote the path.
fn folder_name(cwd: &str) -> &str {
    let trimmed = cwd.trim_end_matches(['\\', '/']);
    trimmed
        .rsplit(['\\', '/'])
        .next()
        .filter(|name| !name.is_empty())
        .unwrap_or(cwd)
}

/// Returns a folder's path with the home folder written as `~`, which makes
/// it shorter.
fn home_as_tilde(cwd: &str) -> String {
    let Some(home) = dirs::home_dir() else {
        return cwd.into();
    };
    let home = home.display().to_string();
    let rest = cwd.get(home.len()..).filter(|_| {
        cwd.get(..home.len())
            .is_some_and(|start| start.eq_ignore_ascii_case(&home))
    });
    match rest {
        Some(rest) if rest.is_empty() || rest.starts_with(['\\', '/']) => format!("~{rest}"),
        _ => cwd.into(),
    }
}

/// Returns how long ago a file was last changed, in words.
fn last_used(file: &Path) -> String {
    let seconds = std::fs::metadata(file)
        .and_then(|metadata| metadata.modified())
        .ok()
        .and_then(|modified| SystemTime::now().duration_since(modified).ok())
        .map_or(0, |elapsed| elapsed.as_secs());
    ago(seconds)
}

/// Returns a time span in words, such as `40 minutes ago`.
fn ago(seconds: u64) -> String {
    let (count, unit) = match seconds {
        0..60 => return "just now".into(),
        60..3_600 => (seconds / 60, "minute"),
        3_600..86_400 => (seconds / 3_600, "hour"),
        _ => (seconds / 86_400, "day"),
    };
    let plural = if count == 1 { "" } else { "s" };
    format!("{count} {unit}{plural} ago")
}

/// Returns a number of tabs in words, such as `1 tab` or `3 tabs`.
fn count(tabs: usize) -> String {
    if tabs == 1 {
        "1 tab".into()
    } else {
        format!("{tabs} tabs")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_tab_is_named_after_its_folder() {
        assert_eq!(folder_name(r"C:\Users\demo\code\mobile-app"), "mobile-app");
        assert_eq!(folder_name("/home/demo/code/api-server/"), "api-server");
        assert_eq!(folder_name(r"D:\"), "D:");
    }

    #[test]
    fn time_spans_read_as_words() {
        assert_eq!(ago(5), "just now");
        assert_eq!(ago(60), "1 minute ago");
        assert_eq!(ago(40 * 60), "40 minutes ago");
        assert_eq!(ago(2 * 3_600), "2 hours ago");
        assert_eq!(ago(3 * 86_400), "3 days ago");
    }

    #[test]

    fn shells_are_shown_by_their_names() {
        assert_eq!(shell_name(Some("pwsh")), "PowerShell");
        assert_eq!(shell_name(Some("powershell")), "PowerShell");
        assert_eq!(shell_name(Some("bash")), "Bash");
        assert_eq!(shell_name(Some("fish")), "fish");
    }

    fn terminal(exe: &str) -> TerminalRef {
        TerminalRef {
            adapter: "windows-terminal".into(),
            process: crate::engine::note::ProcessRef {
                pid: 1,
                started_ms: 100,
            },
            shape: crate::engine::rules::TerminalShape::Tabs,
            tab_id: None,
            profile: None,
            exe: Some(exe.into()),
        }
    }

    fn tab(cwd: &str, started_ms: u64) -> Tab {
        Tab {
            notes: Vec::new(),
            cwd: cwd.into(),
            shell: None,
            agent: None,
            terminal: terminal(r"C:\Apps\WindowsTerminal.exe"),
            started_ms,
        }
    }

    #[test]
    fn checked_tabs_come_back_in_the_order_they_were_opened() {
        // As the picker lists them: agent sessions first.
        let tabs = [
            tab("agent-opened-third", 3_000),
            tab("agent-opened-first", 1_000),
            tab("shell-opened-second", 2_000),
            tab("shell-unchecked", 500),
        ];
        let order: Vec<&str> = in_opening_order(&tabs, &[true, true, true, false])
            .iter()
            .map(|tab| tab.cwd.as_str())
            .collect();
        assert_eq!(
            order,
            [
                "agent-opened-first",
                "shell-opened-second",
                "agent-opened-third"
            ]
        );
    }

    #[test]
    fn tabs_of_another_copy_of_the_terminal_are_elsewhere() {
        let here = terminal(r"C:\Apps\WindowsTerminal.exe");
        assert!(same_terminal(
            &here,
            &terminal(r"c:\apps\windowsterminal.exe")
        ));
        assert!(!same_terminal(
            &here,
            &terminal(r"D:\Portable\WindowsTerminal.exe")
        ));
    }

    #[test]
    fn the_frog_lines_have_one_width_so_that_the_text_lines_up() {
        let width = GREETING[0].0.len();
        assert!(GREETING.iter().all(|(frog, _)| frog.len() == width));
    }

    #[test]
    fn folders_outside_home_keep_their_path() {
        assert_eq!(home_as_tilde("Q:\\elsewhere"), "Q:\\elsewhere");
    }
}