kaeru 0.1.1

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Shell snippets: `kaeru init <shell>` prints the code that one line in your
//! profile loads, and `kaeru shell start` is what that code runs.
//!
//! A snippet registers its tab once, when the shell starts, and keeps the
//! tab's folder up to date. The shell writes the folder itself, so that no
//! process starts on each prompt.

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use anyhow::{Context, Result, bail};

use crate::agents::codex;
use crate::engine::config::Config;
use crate::engine::note::{Note, ShellNote};
use crate::engine::rules::TabState;
use crate::engine::tabs::{self, Seen};
use crate::os;
use crate::procs::ProcInfo;
use crate::procs::system::SystemTable;
use crate::store::{self, Reviewed, Store, StoredNote};
use crate::terminals::{self, Env};

/// The PowerShell snippet. It is plain ASCII, because PowerShell reads what
/// `kaeru init` prints in the console's code page.
const POWERSHELL: &str = include_str!("powershell.ps1");

/// The PowerShell function that starts Codex with `--no-daemon`, which the
/// snippet ends with when the `codex-no-daemon` option is on. Plain ASCII,
/// like the snippet.
const POWERSHELL_CODEX: &str = include_str!("powershell-codex.ps1");

/// The exit code of `kaeru shell start` that tells the snippet to show the
/// picker.
const ASK: u8 = 3;

/// What `kaeru shell start` tells the snippet.
struct Started {
    /// The tab's `.cwd` file, or `None` when the shell isn't a tab.
    cwd_file: Option<PathBuf>,
    /// Whether this tab shows the picker.
    ask: bool,
}

/// A shell that `kaeru init` can print a snippet for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Shell {
    Powershell,
    Bash,
    Zsh,
    Fish,
}

impl Shell {
    /// Returns the shell's name, as `kaeru init` takes it.
    pub fn name(self) -> &'static str {
        match self {
            Shell::Powershell => "powershell",
            Shell::Bash => "bash",
            Shell::Zsh => "zsh",
            Shell::Fish => "fish",
        }
    }
}

/// Prints the snippet for `shell`, as the user's options want it.
///
/// # Errors
///
/// Fails for a shell whose snippet is not built yet.
pub fn print_init(shell: Shell) -> Result<()> {
    match shell {
        Shell::Powershell => {
            let config = Store::open()
                .map(|store| store.config())
                .unwrap_or_default();
            print!("{}", powershell_snippet(&config));
            Ok(())
        }
        _ => bail!(
            "`kaeru init {}` is not built yet. See the roadmap in README.md.",
            shell.name()
        ),
    }
}

/// Returns the PowerShell snippet: the part that tracks the tab and, when the
/// `codex-no-daemon` option is on, the function that starts Codex with
/// `--no-daemon`.
fn powershell_snippet(config: &Config) -> String {
    let mut snippet = POWERSHELL.to_string();
    if config.codex_no_daemon {
        let one_off: Vec<String> = codex::ONE_OFF_COMMANDS
            .iter()
            .map(|command| format!("'{command}'"))
            .collect();
        snippet.push_str(&POWERSHELL_CODEX.replace("KAERU_ONE_OFF_COMMANDS", &one_off.join(", ")));
    }
    snippet
}

/// Records a shell that started in a tab, for `kaeru shell start`. It prints
/// the path of the tab's `.cwd` file for the snippet, or nothing when the
/// shell isn't a tab, and exits with code 3 when the tab should show the
/// picker. It never fails the shell: problems go to the log.
pub fn start(pid: u32) -> ExitCode {
    let Ok(store) = Store::open() else {
        return ExitCode::SUCCESS;
    };
    match record(&store, pid) {
        Ok(started) => {
            if let Some(cwd_file) = started.cwd_file {
                println!("{}", cwd_file.display());
            }
            if started.ask {
                return ExitCode::from(ASK);
            }
        }
        Err(error) => store.log(&format!("shell start: {error:#}")),
    }
    ExitCode::SUCCESS
}

/// Writes the note of the shell with the id `pid`, unless it has one,
/// deletes the notes of closed tabs, and tells the tab about waiting tabs.
fn record(store: &Store, pid: u32) -> Result<Started> {
    let mut table = SystemTable::snapshot();
    let lineage = table.lineage(pid);
    let env: Env = std::env::vars().collect();
    let session = os::session_id()?;
    let config = store.config();
    let cwd = std::env::current_dir()?.display().to_string();
    let path = match shell_note(pid, &lineage, &env, &session, cwd)? {
        // A shell that loads its profile again keeps its note, and with it
        // what kaeru already knows about the tab.
        Some(note) if store.path_of(&note).exists() => Some(store.path_of(&note)),
        Some(note) => Some(store.save(&note)?),
        None => None,
    };
    let reviewed = store::review(store, &table, &session, config.single_window_close);
    // Only a tab's own shell says anything, so a shell nested in it doesn't.
    let ask = match &path {
        Some(_) => {
            let command_line = lineage
                .first()
                .and_then(|shell| shell.command_line.as_deref())
                .unwrap_or_default();
            offer(store, &reviewed, &config, runs_a_command(command_line))?
        }
        None => false,
    };
    Ok(Started {
        cwd_file: path.map(|path| store::cwd_file(&path)),
        ask,
    })
}

/// Tells a new tab about the tabs that are waiting, and returns whether it
/// shows the picker. It does when the user wants that, the shell wasn't
/// started to run a command, as a reopened agent tab is, and no other tab has
/// asked about these tabs yet. Otherwise it prints a one-line reminder.
/// Waiting notes are deleted when the options leave all of them out, because
/// they would never come back.
fn offer(
    store: &Store,
    reviewed: &[Reviewed],
    config: &Config,
    runs_a_command: bool,
) -> Result<bool> {
    let waiting: Vec<&StoredNote> = reviewed
        .iter()
        .filter(|reviewed| reviewed.state == TabState::Waiting)
        .map(|reviewed| &reviewed.stored)
        .collect();
    let notes: Vec<(Note, Seen)> = waiting
        .iter()
        .map(|stored| (stored.note.clone(), store::last_seen(stored)))
        .collect();
    let count = tabs::to_offer(&notes, config).len();
    if count == 0 {
        for stored in &waiting {
            store.remove(stored);
        }
        return Ok(false);
    }
    // Another tab holds the lock while it asks or reopens these tabs, and a
    // tab that it reopens would only repeat what that tab is showing.
    let Some(_lock) = store.try_lock()? else {
        return Ok(false);
    };
    if config.ask_on_start && !runs_a_command {
        let mut new = false;
        for stored in &waiting {
            // Another tab may have asked since the review, so the file on
            // disk decides.
            if let Ok(mut note) = store.read(&stored.path)
                && !note.offered()
            {
                note.set_offered();
                store.save(&note)?;
                new = true;
            }
        }
        if new {
            return Ok(true);
        }
    }
    let (tabs, them) = if count == 1 {
        ("1 tab is".to_string(), "it")
    } else {
        (format!("{count} tabs are"), "them")
    };
    eprintln!("kaeru: {tabs} waiting to come back. Run kaeru to see {them}.");
    Ok(false)
}

/// Returns whether a PowerShell command line runs a command or a script, as
/// kaeru's reopened agent tabs do, rather than starting a shell to type in.
/// PowerShell takes any prefix of a parameter's name, such as `-c` for
/// `-Command`, and `-ec` for `-EncodedCommand`.
pub fn runs_a_command(command_line: &str) -> bool {
    command_line.split_whitespace().skip(1).any(|argument| {
        let Some(name) = argument.strip_prefix(['-', '/']) else {
            return false;
        };
        let name = name.to_ascii_lowercase();
        !name.is_empty()
            && name.chars().all(|c| c.is_ascii_alphabetic())
            && (name == "ec"
                || ["command", "file", "encodedcommand"]
                    .iter()
                    .any(|parameter| parameter.starts_with(&name)))
    })
}

/// Returns the note for the shell with the id `pid`, from its lineage, or
/// `None` when the shell isn't a tab of a known terminal. A shell inside
/// another program in a tab, such as a nested shell, belongs to that tab,
/// and kaeru can only reopen tabs of terminals that it has an adapter for.
///
/// # Errors
///
/// Fails when the shell's process is gone or its start time can't be read.
fn shell_note(
    pid: u32,
    lineage: &[ProcInfo],
    env: &Env,
    session: &str,
    cwd: String,
) -> Result<Option<Note>> {
    let shell = lineage
        .first()
        .filter(|process| process.pid == pid)
        .context("the shell's process is gone")?;
    let Some((0, terminal)) = terminals::tab_of(&terminals::all(), env, lineage) else {
        return Ok(None);
    };
    Ok(Some(Note::Shell(ShellNote {
        process: shell
            .to_ref()
            .context("the shell's start time can't be read")?,
        shell: shell_name(&shell.name),
        cwd,
        terminal: Some(terminal),
        session: session.into(),
        offered: false,
    })))
}

/// Returns the name kaeru stores for a shell's executable: its file name,
/// without `.exe`, such as `powershell` or `pwsh`.
pub fn shell_name(executable: &str) -> String {
    let path = Path::new(executable);
    let is_exe = path
        .extension()
        .is_some_and(|extension| extension.eq_ignore_ascii_case("exe"));
    let name = if is_exe {
        path.file_stem()
    } else {
        path.file_name()
    };
    name.map_or_else(
        || executable.to_string(),
        |name| name.to_string_lossy().into_owned(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::procs::{fake::FakeTable, lineage};

    /// A tab's shell (20) in Windows Terminal (10), with a shell inside it
    /// (30).
    fn tab_table() -> FakeTable {
        FakeTable::new(&[
            (30, Some(20), "pwsh.exe", Some(3_000)),
            (20, Some(10), "powershell.exe", Some(2_000)),
            (10, None, "WindowsTerminal.exe", Some(1_000)),
        ])
    }

    fn tab_env() -> Env {
        Env::from([("WT_SESSION".to_string(), "x".to_string())])
    }

    #[test]
    fn the_shell_of_a_tab_gets_a_note() {
        let table = tab_table();
        let note = shell_note(20, &lineage(&table, 20), &tab_env(), "win-1", "C:\\".into());
        let Some(Note::Shell(note)) = note.unwrap() else {
            panic!("no shell note");
        };
        assert_eq!(note.shell, "powershell");
        assert_eq!(note.terminal.unwrap().process.pid, 10);
    }

    #[test]
    fn a_shell_inside_a_tab_gets_no_note() {
        let table = tab_table();
        let note = shell_note(30, &lineage(&table, 30), &tab_env(), "win-1", "C:\\".into());
        assert!(note.unwrap().is_none());
    }

    #[test]
    fn a_shell_outside_known_terminals_gets_no_note() {
        let table = tab_table();
        let note = shell_note(
            20,
            &lineage(&table, 20),
            &Env::new(),
            "win-1",
            "C:\\".into(),
        );
        assert!(note.unwrap().is_none());
    }

    #[test]
    fn shell_names_drop_the_exe_extension() {
        assert_eq!(shell_name("powershell.exe"), "powershell");
        assert_eq!(shell_name("pwsh.EXE"), "pwsh");
        assert_eq!(shell_name("zsh"), "zsh");
    }

    #[test]
    fn the_powershell_snippet_is_ascii_and_starts_the_tab() {
        assert!(POWERSHELL.is_ascii());
        assert!(POWERSHELL.contains("kaeru shell start --pid $PID"));
    }

    #[test]
    fn other_snippets_are_not_built_yet() {
        assert!(print_init(Shell::Bash).is_err());
    }

    #[test]
    fn the_codex_function_comes_only_with_its_option() {
        let plain = powershell_snippet(&Config::default());
        assert!(!plain.contains("function global:codex"));
        let with_codex = powershell_snippet(&Config {
            codex_no_daemon: true,
            ..Config::default()
        });
        assert!(with_codex.starts_with(POWERSHELL));
        assert!(with_codex.contains("function global:codex"));
        assert!(with_codex.contains("'exec', "));
        assert!(!with_codex.contains("KAERU_ONE_OFF_COMMANDS"));
        assert!(with_codex.is_ascii());
    }

    /// Runs the snippet's Codex function in Windows PowerShell, with a
    /// stand-in for Codex that prints what it reads and its arguments, and
    /// returns what it printed. The PATH holds only the stand-in and Windows,
    /// so that a real Codex can't run. The stand-in is both a script and a
    /// batch file, because PowerShell may pick either one, as it does for the
    /// npm package's `codex.ps1` and `codex.cmd`.
    #[cfg(windows)]
    fn run_codex_function(calls: &str) -> String {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("codex.ps1"),
            "foreach ($line in $input) { \"in:$line\" }\r\n\
             foreach ($argument in $args) { \"arg:$argument\" }\r\n",
        )
        .unwrap();
        std::fs::write(
            dir.path().join("codex.cmd"),
            "@echo off\r\n\
             for /f \"delims=\" %%l in ('findstr \"^\"') do echo in:%%l\r\n\
             :next\r\nif \"%~1\"==\"\" goto :eof\r\necho arg:%~1\r\nshift\r\ngoto next\r\n",
        )
        .unwrap();
        let function = powershell_snippet(&Config {
            codex_no_daemon: true,
            ..Config::default()
        });
        let function = &function[POWERSHELL.len()..];
        let script = format!(
            "$env:PATH = '{};' + $env:SystemRoot + '\\System32'\n\
             $global:__kaeru_cwd_file = 'tracked'\n{function}\n{calls}",
            dir.path().display()
        );
        let powershell = std::path::Path::new(&std::env::var("SystemRoot").unwrap())
            .join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
        let output = std::process::Command::new(powershell)
            .args([
                "-NoProfile",
                "-NonInteractive",
                "-ExecutionPolicy",
                "Bypass",
            ])
            .args(["-Command", &script])
            .output()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
        String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n")
    }

    /// Runs the PowerShell snippet in Windows PowerShell under a prompt theme
    /// that shows `$?`, with a stand-in for `kaeru` that tracks the tab, then
    /// runs `commands` and returns what the prompt shows. The snippet only
    /// starts in an interactive console, so the test lifts that check.
    #[cfg(windows)]
    fn prompt_after(commands: &str) -> String {
        let dir = tempfile::tempdir().unwrap();
        let cwd_file = dir.path().join("tab.cwd");
        std::fs::write(
            dir.path().join("kaeru.cmd"),
            format!("@echo {}\r\n", cwd_file.display()),
        )
        .unwrap();
        let snippet = POWERSHELL.replace(
            "$Host.Name -eq 'ConsoleHost' -and -not [Console]::IsInputRedirected -and",
            "$true -and",
        );
        let script = format!(
            "$env:PATH = '{};' + $env:SystemRoot + '\\System32'\n\
             function global:prompt {{ \"theme sees $?\" }}\n{snippet}\n{commands}\nprompt",
            dir.path().display()
        );
        let powershell = std::path::Path::new(&std::env::var("SystemRoot").unwrap())
            .join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
        let output = std::process::Command::new(powershell)
            .args([
                "-NoProfile",
                "-NonInteractive",
                "-ExecutionPolicy",
                "Bypass",
            ])
            .args(["-Command", &script])
            .output()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    #[cfg(windows)]
    #[test]
    fn the_prompt_theme_still_sees_whether_the_last_command_failed() {
        assert_eq!(
            prompt_after("Get-Item 'C:\\no-such-folder' -ErrorAction SilentlyContinue"),
            "theme sees False"
        );
        assert_eq!(
            prompt_after("Get-Item 'C:\\' | Out-Null"),
            "theme sees True"
        );
    }

    #[cfg(windows)]
    #[test]
    fn the_codex_function_adds_no_daemon_only_for_the_interactive_screen() {
        let printed = run_codex_function(
            "'1'; codex\n\
             '2'; codex resume --last\n\
             '3'; codex exec 'fix the tests'\n\
             '4'; codex --no-daemon\n\
             '5'; codex --remote ws://localhost:1\n\
             '6'; 'fix the tests' | codex exec -",
        );
        assert_eq!(
            printed.trim_end(),
            "1\narg:--no-daemon\n\
             2\narg:--no-daemon\narg:resume\narg:--last\n\
             3\narg:exec\narg:fix the tests\n\
             4\narg:--no-daemon\n\
             5\narg:--remote\narg:ws://localhost:1\n\
             6\nin:fix the tests\narg:exec\narg:-"
        );
    }

    #[test]
    fn a_shell_started_to_run_something_is_recognized() {
        assert!(runs_a_command(
            "powershell.exe -NoExit -EncodedCommand AAAA"
        ));
        assert!(runs_a_command("powershell -ec AAAA"));
        assert!(runs_a_command("pwsh -c Get-Date"));
        assert!(runs_a_command("powershell -File script.ps1"));
        assert!(!runs_a_command("powershell.exe"));
        assert!(!runs_a_command("powershell.exe -NoLogo -NoExit"));
        assert!(!runs_a_command("pwsh -ExecutionPolicy Bypass"));
    }

    /// Returns a store in a temporary folder that holds one waiting tab: a
    /// shell whose terminal is gone.
    fn store_with_a_waiting_tab() -> (tempfile::TempDir, Store) {
        use crate::engine::note::{ProcessRef, TerminalRef};
        use crate::engine::rules::TerminalShape;

        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        let note = Note::Shell(ShellNote {
            process: ProcessRef {
                pid: 20,
                started_ms: 2_000,
            },
            shell: "powershell".into(),
            cwd: r"C:\Users\demo\code\web-ui".into(),
            terminal: Some(TerminalRef {
                adapter: "windows-terminal".into(),
                process: ProcessRef {
                    pid: 10,
                    started_ms: 1_000,
                },
                shape: TerminalShape::Tabs,
                tab_id: None,
                profile: None,
                exe: None,
            }),
            session: "win-1".into(),
            offered: false,
        });
        store.save(&note).unwrap();
        (dir, store)
    }

    /// Returns what the store's notes mean when none of their processes run.
    fn review_with_nothing_running(store: &Store) -> Vec<Reviewed> {
        let table = FakeTable::new(&[]);
        store::review(
            store,
            &table,
            "win-1",
            Config::default().single_window_close,
        )
    }

    #[test]
    fn only_the_first_new_tab_asks() {
        let (_dir, store) = store_with_a_waiting_tab();
        let config = Config::default();
        let reviewed = review_with_nothing_running(&store);
        assert!(offer(&store, &reviewed, &config, false).unwrap());
        let reviewed = review_with_nothing_running(&store);
        assert!(!offer(&store, &reviewed, &config, false).unwrap());
        assert_eq!(store.notes().len(), 1, "the tab still waits");
    }

    #[test]
    fn a_new_tab_waits_quietly_while_another_tab_holds_the_list() {
        let (_dir, store) = store_with_a_waiting_tab();
        // Another tab's picker holds the lock while it asks or reopens.
        let held = store.try_lock().unwrap().unwrap();
        let reviewed = review_with_nothing_running(&store);
        assert!(!offer(&store, &reviewed, &Config::default(), false).unwrap());
        assert!(!store.notes()[0].note.offered(), "it asks later, not now");
        drop(held);
        let reviewed = review_with_nothing_running(&store);
        assert!(offer(&store, &reviewed, &Config::default(), false).unwrap());
    }

    #[test]
    fn a_reopened_agent_tab_never_asks() {
        let (_dir, store) = store_with_a_waiting_tab();
        let reviewed = review_with_nothing_running(&store);
        assert!(!offer(&store, &reviewed, &Config::default(), true).unwrap());
        assert!(!store.notes()[0].note.offered());
    }

    #[test]
    fn tabs_that_the_options_leave_out_are_forgotten() {
        let (_dir, store) = store_with_a_waiting_tab();
        let config = Config {
            offer_shells: false,
            ..Config::default()
        };
        let reviewed = review_with_nothing_running(&store);
        assert!(!offer(&store, &reviewed, &config, false).unwrap());
        assert!(store.notes().is_empty());
    }
}