kaeru 0.1.8

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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
//! 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, which grows from a tadpole.

mod frog;
mod picker;

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

use anyhow::{Context, Result};
use ratatui::crossterm::event::{self, Event, KeyEventKind};
use ratatui::crossterm::style::{
    Attribute, Color, Print, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor,
};
use ratatui::crossterm::{cursor, queue, terminal};

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()?;
    crate::install::adopt::refresh(&store, &mut table);
    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, None) {
            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 plan: Vec<store::Reopening> = tabs
        .iter()
        .enumerate()
        .map(|(index, tab)| store::Reopening {
            number: index + 1,
            total: tabs.len(),
            cwd: tab.cwd.clone(),
        })
        .collect();
    // Without the plan, the tabs only don't say how far it has come.
    if let Err(error) = store.plan_reopening(&plan) {
        store.log(&format!("{error:#}"));
    }
    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: on Windows, when its shell was bash, and
/// in mintty, whose windows run bash. Elsewhere, terminals start the tab's
/// shell with the code in a variable, or type it in.
fn runs_in_bash(tab: &TabToOpen, terminal: &TerminalRef) -> bool {
    cfg!(windows)
        && !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 => {
            let when = tab.last_prompt_ms.map(ago_ms).unwrap_or_default();
            (shell_name(tab.shell.as_deref()), when)
        }
    };
    // An adopted tab's folder can be older than the tab's, and the list
    // says so.
    let what = if tab.adopted {
        format!("{what} (adopted)")
    } else {
        what
    };
    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, the ones waiting to come back, which are the tabs that `kaeru`
/// offers, and the ones whose terminal brought them back by itself, where
/// `kaeru resume` continues their sessions. Like every run, it first deletes
/// the notes of closed tabs. The lines fit the terminal's width.
///
/// # 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 mut table = SystemTable::snapshot();
    let session = os::session_id()?;
    crate::install::adopt::refresh(&store, &mut table);
    let reviewed = store::review(&store, &table, &session, config.single_window_close);
    // A waiting tab is either offered, or left to its terminal, which brings
    // it back by itself, as the picker decides.
    let notes_in = |state: TabState, left: bool| -> Vec<(Note, Seen)> {
        reviewed
            .iter()
            .filter(|reviewed| reviewed.state == state)
            .filter(|one| {
                state != TabState::Waiting
                    || shells::left_to_its_terminal(&one.stored.note, &reviewed) == left
            })
            .map(|reviewed| {
                (
                    reviewed.stored.note.clone(),
                    store::last_seen(&reviewed.stored),
                )
            })
            .collect()
    };
    let open = tabs::group(&notes_in(TabState::Open, false));
    let waiting = tabs::to_offer(&notes_in(TabState::Waiting, false), &config);
    let left = tabs::group(&notes_in(TabState::Waiting, true));
    if open.is_empty() && waiting.is_empty() && left.is_empty() {
        println!("No tabs are tracked yet.");
        return Ok(());
    }
    // One set of columns for all the lists, so that they line up.
    let entries: Vec<Entry> = open
        .iter()
        .chain(&waiting)
        .chain(&left)
        .map(entry)
        .collect();
    let fit = io::stdout()
        .is_terminal()
        .then(|| terminal::size().ok())
        .flatten()
        .map(|(columns, _)| usize::from(columns).saturating_sub(2));
    let lines = picker::columns(&entries, fit);
    let (open_lines, rest) = lines.split_at(open.len());
    let (waiting_lines, left_lines) = rest.split_at(waiting.len());
    for (title, lines) in [
        ("Open", open_lines),
        ("Waiting to come back", waiting_lines),
        (
            "Brought back by their terminal (run kaeru resume in the tab)",
            left_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.
/// It shows where the animated frog can't.
const GREETING: [(&str, &str); 4] = [
    ("   (o)____(o)  ", " kaeru"),
    (
        "  /          \\ ",
        " Your tabs come back after the terminal closes.",
    ),
    (" |  \\______/  |", ""),
    ("  \\__________/ ", ""),
];

/// What kaeru does, in one line, which shows next to the animated frog.
const TAGLINE: &str = "Your tabs come back after the terminal closes.";

/// Shows kaeru's frog, with kaeru's name and what it does, which `kaeru
/// install` starts with. In a terminal that can show it, a tadpole turns
/// into the frog, and any key skips to the end. Otherwise, the frog is drawn in
/// characters, in the terminal's green unless colors are off.
///
/// # Errors
///
/// Fails when standard output can't be written to.
pub fn greet() -> io::Result<()> {
    let color = colors_wanted() && io::stdout().is_terminal();
    let size = terminal::size().unwrap_or((0, 0));
    let term_program = std::env::var("TERM_PROGRAM").ok();
    // A terminal that can't do what the animation needs gets the frog drawn
    // in characters.
    if color && can_draw() && fits_the_animation(size) {
        let full_color = full_color(term_program.as_deref());
        if animate_frog(size.0, full_color, true).is_ok() {
            return Ok(());
        }
    } else if color && term_program.as_deref() == Some("mintty") && !can_draw() {
        // mintty, such as Git Bash's own window, shows the animation, but a
        // Windows program there has no console to learn the window's size
        // or read single keys from. So kaeru takes mintty's own default
        // width, and the animation plays to its end.
        let columns = mintty_columns(std::env::var("COLUMNS").ok().as_deref());
        if animate_frog(columns, true, false).is_ok() {
            return Ok(());
        }
    }
    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()
}

/// Returns whether a terminal of `(columns, rows)` has room for the animated
/// frog, with a line below it.
fn fits_the_animation((columns, rows): (u16, u16)) -> bool {
    columns >= frog::COLUMNS + 2 && rows > frog::ROWS + 1
}

/// Returns how wide a mintty window is taken to be: `COLUMNS` when the shell
/// exports it, and otherwise mintty's default of 80 columns.
fn mintty_columns(columns: Option<&str>) -> u16 {
    columns
        .and_then(|columns| columns.trim().parse().ok())
        .unwrap_or(80)
}

/// Returns whether the terminal, named by `TERM_PROGRAM`, shows any color of
/// red, green and blue. macOS Terminal shows only 256 colors.
fn full_color(term_program: Option<&str>) -> bool {
    term_program != Some("Apple_Terminal")
}

/// Adds a command's escape code to a text. The animation writes escape codes
/// itself, so that it also works where there is no Windows console for
/// crossterm to call instead, as in mintty.
fn put(text: &mut String, command: impl ratatui::crossterm::Command) {
    // Writing to a String can't fail.
    let _ = command.write_ansi(text);
}

/// Plays the frog's animation where the cursor is, and leaves the last frame,
/// with kaeru's name and what it does next to the frog, or below it when the
/// terminal, `columns` wide, is too narrow. With `keys`, keys are read raw
/// while it plays, so that any key, Ctrl+C too, skips to the end.
fn animate_frog(columns: u16, full_color: bool, keys: bool) -> io::Result<()> {
    let mut out = io::stdout().lock();
    let rows = frog::ROWS;
    if keys {
        // Through crossterm first, which turns on escape codes in a Windows
        // console.
        queue!(out, cursor::Hide)?;
    }
    // Room for the frog first, so that drawing it never scrolls the screen.
    let mut text = "\n".repeat(usize::from(rows));
    put(&mut text, cursor::MoveUp(rows));
    put(&mut text, cursor::Hide);
    out.write_all(text.as_bytes())?;
    out.flush()?;
    if keys {
        terminal::enable_raw_mode()?;
    }
    let played = play(&mut out, full_color, keys);
    if keys {
        let _ = terminal::disable_raw_mode();
    }
    let side = frog::COLUMNS + 2;
    let beside = usize::from(columns) >= usize::from(side) + TAGLINE.len();
    let mut text = String::new();
    if beside {
        // The name and the tagline go in the middle rows.
        put(&mut text, cursor::MoveDown(rows / 2 - 1));
        put(&mut text, cursor::MoveToColumn(side));
        put(&mut text, SetForegroundColor(Color::DarkGreen));
        put(&mut text, SetAttribute(Attribute::Bold));
        text.push_str("kaeru");
        put(&mut text, SetAttribute(Attribute::Reset));
        put(&mut text, ResetColor);
        put(&mut text, cursor::MoveDown(1));
        put(&mut text, cursor::MoveToColumn(side));
        text.push_str(TAGLINE);
        put(&mut text, cursor::MoveDown(rows - rows / 2));
    } else {
        put(&mut text, cursor::MoveDown(rows));
    }
    put(&mut text, cursor::MoveToColumn(0));
    put(&mut text, cursor::Show);
    if !beside {
        text.push_str(&format!("kaeru: {TAGLINE}\n"));
    }
    text.push('\n');
    let finished = out.write_all(text.as_bytes()).and_then(|()| out.flush());
    played.and(finished)
}

/// Draws the frames of the frog's animation at 20 a second until the last
/// one. With `keys`, a key shows the last one at once. The cursor starts and
/// ends at the frog's top left.
fn play(out: &mut impl Write, full_color: bool, keys: bool) -> io::Result<()> {
    let started = Instant::now();
    loop {
        let t = started.elapsed().as_secs_f64();
        let frame = frame_text(&frog::frame(t.min(frog::LENGTH)), full_color);
        out.write_all(frame.as_bytes())?;
        out.flush()?;
        if t >= frog::LENGTH {
            return Ok(());
        }
        if !keys {
            std::thread::sleep(frog::FRAME);
        } else if event::poll(frog::FRAME)?
            && let Event::Key(key) = event::read()?
            && key.kind == KeyEventKind::Press
        {
            let last = frame_text(&frog::frame(frog::LENGTH), full_color);
            out.write_all(last.as_bytes())?;
            return out.flush();
        }
    }
}

/// Returns one frame of the frog's animation as text with escape codes: it
/// draws the rows from the cursor down, and moves the cursor back to where
/// it started.
fn frame_text(cells: &[frog::Cell], full_color: bool) -> String {
    let paint = |rgb: [u8; 3]| {
        if full_color {
            Color::Rgb {
                r: rgb[0],
                g: rgb[1],
                b: rgb[2],
            }
        } else {
            Color::AnsiValue(frog::to_256(rgb))
        }
    };
    let rows: Vec<&[frog::Cell]> = cells.chunks(usize::from(frog::COLUMNS)).collect();
    let mut text = String::new();
    for (index, row) in rows.iter().enumerate() {
        put(&mut text, cursor::MoveToColumn(0));
        for cell in *row {
            if cell.dots == 0 {
                put(&mut text, ResetColor);
                text.push(' ');
                continue;
            }
            put(
                &mut text,
                SetBackgroundColor(cell.bg.map_or(Color::Reset, paint)),
            );
            put(&mut text, SetForegroundColor(paint(cell.fg)));
            text.push(cell.symbol());
        }
        put(&mut text, ResetColor);
        if index + 1 < rows.len() {
            put(&mut text, cursor::MoveDown(1));
        }
    }
    let up = u16::try_from(rows.len().saturating_sub(1)).unwrap_or(0);
    if up > 0 {
        put(&mut text, cursor::MoveUp(up));
    }
    text
}

/// 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.
pub 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.
pub 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 time, in milliseconds since the Unix epoch, was,
/// in words.
fn ago_ms(ms: u64) -> String {
    let now = SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |since| since.as_millis());
    let then = u128::from(ms);
    ago(u64::try_from(now.saturating_sub(then) / 1_000).unwrap_or(u64::MAX))
}

/// 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,
            last_prompt_ms: None,
            adopted: false,
        }
    }

    #[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 the_frog_is_animated_only_where_it_fits() {
        assert!(fits_the_animation((80, 24)));
        assert!(!fits_the_animation((frog::COLUMNS, 24)));
        assert!(!fits_the_animation((80, frog::ROWS)));
    }

    #[test]
    fn mintty_is_taken_to_be_as_wide_as_its_default() {
        assert_eq!(mintty_columns(None), 80);
        assert_eq!(mintty_columns(Some("120")), 120);
        assert_eq!(mintty_columns(Some("wide")), 80);
    }

    #[test]
    fn a_frame_is_drawn_with_escape_codes_and_returns_the_cursor() {
        let text = frame_text(&frog::frame(frog::LENGTH), true);
        // It starts at the left, draws in true color, and moves back up.
        assert!(text.starts_with("\x1b[1G"));
        assert!(text.contains("\x1b[38;2;"));
        assert!(text.ends_with(&format!("\x1b[{}A", frog::ROWS - 1)));
        assert!(text.chars().any(|c| ('\u{2801}'..='\u{28ff}').contains(&c)));
        let few = frame_text(&frog::frame(frog::LENGTH), false);
        assert!(few.contains("\x1b[38;5;") && !few.contains("\x1b[38;2;"));
    }

    #[test]
    fn macos_terminal_gets_256_colors() {
        assert!(!full_color(Some("Apple_Terminal")));
        assert!(full_color(Some("iTerm.app")));
        assert!(full_color(None));
    }

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