kaeru 0.1.0

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
//! 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::Result;
use ratatui::crossterm::queue;
use ratatui::crossterm::style::{Color, Print, ResetColor, SetForegroundColor};

use crate::agents::Agent;
use crate::engine::note::{Note, TerminalRef};
use crate::engine::rules::TabState;
use crate::engine::tabs::{self, Tab};
use crate::os;
use crate::procs::system::SystemTable;
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";

/// 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 mut table = SystemTable::snapshot();
    let session = os::session_id()?;
    let waiting: Vec<StoredNote> =
        store::review(&store, &table, &session, config.single_window_close)
            .into_iter()
            .filter(|reviewed| reviewed.state == TabState::Waiting)
            .map(|reviewed| reviewed.stored)
            .collect();
    let notes: Vec<(Note, String)> = waiting
        .iter()
        .map(|stored| (stored.note.clone(), store::last_cwd(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);
        }
        println!("No tabs are waiting to come back.");
        return Ok(ExitCode::SUCCESS);
    }
    let entries: Vec<Entry> = tabs.iter().map(entry).collect();
    if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
        for line in picker::columns(&entries) {
            println!("{line}");
        }
        println!("Run kaeru in a terminal to choose which tabs to reopen.");
        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 env: Env = std::env::vars().collect();
    let here = terminals::tab_of(&terminals::all(), &env, &table.lineage(std::process::id()))
        .map(|(_, terminal)| terminal);
    // 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() {
        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);
        }
        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);
                adapter.reopen(exe, &[tab_to_open(tab)])
            }
            None => Err(anyhow::anyhow!(
                "this version of kaeru doesn't know the terminal {id}"
            )),
        };
        match result {
            Ok(()) => opened += 1,
            Err(error) => {
                for &index in &tab.notes {
                    let _ = store.save(&waiting[index].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,
    }
}

/// 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, String)> {
        reviewed
            .iter()
            .filter(|reviewed| reviewed.state == state)
            .map(|reviewed| {
                (
                    reviewed.stored.note.clone(),
                    store::last_cwd(&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()
}

/// 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) => 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 powershell_is_shown_by_its_name() {
        assert_eq!(shell_name(Some("pwsh")), "PowerShell");
        assert_eq!(shell_name(Some("powershell")), "PowerShell");
        assert_eq!(shell_name(Some("bash")), "bash");
    }

    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");
    }
}