kaeru 0.1.7

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
//! `kaeru doctor`: checks the setup, and says what to fix.

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

use anyhow::Result;

use super::{
    CODEX_HOOK, Checklist, Outcome, bash_profile_problem, codex_config_with_hooks, hook_files,
    hooks, loads_kaeru, on_path, profile, read_json, read_or_empty,
};
use crate::agents::codex;
use crate::engine::note::{Note, ShellNote};
use crate::procs::system::SystemTable;
use crate::procs::{self, ProcessTable};
use crate::store::Store;
use crate::terminals::{self, Env};

/// The name of kaeru's executable, which the profile line and the hooks run.
const KAERU: &str = if cfg!(windows) { "kaeru.exe" } else { "kaeru" };

/// Checks that kaeru is set up and prints what it found, for `kaeru doctor`.
/// It exits with 1 when something needs fixing.
///
/// # Errors
///
/// Fails when the state folder can't be opened.
pub fn doctor() -> Result<ExitCode> {
    let profiles = profile::profiles();
    let files = hook_files();
    let names: Vec<&str> = ["kaeru", "This tab", "Windows Terminal"]
        .into_iter()
        .chain(profiles.iter().map(|profile| profile.shell))
        .chain(files.iter().map(|file| file.agent))
        .collect();
    let mut report = Checklist::new(&names);
    match on_path(KAERU) {
        Some(path) => report.line(
            Outcome::Ok,
            "kaeru",
            &format!(
                "on the PATH: {}",
                crate::tui::home_as_tilde(&path.display().to_string())
            ),
        ),
        None => report.line(
            Outcome::Problem,
            "kaeru",
            "isn't on the PATH, so the profile lines and the hooks can't run it",
        ),
    }
    for profile in &profiles {
        let loads =
            read_or_empty(&profile.path).and_then(|bytes| profile::has_line(&bytes, profile.kind));
        match loads {
            Ok(true) => match bash_profile_problem(profile) {
                Some(problem) => report.line(Outcome::Problem, profile.shell, &problem),
                None => report.line(Outcome::Ok, profile.shell, loads_kaeru(profile.kind)),
            },
            Ok(false) => report.line(
                Outcome::Problem,
                profile.shell,
                "doesn't load kaeru. Run kaeru install.",
            ),
            Err(error) => report.line(Outcome::Problem, profile.shell, &format!("{error:#}")),
        }
    }
    let store = Store::open()?;
    check_this_tab(&mut report, &store);
    check_hooks(&mut report, &files);
    if let Ok(log) = fs::read_to_string(store.log_path()) {
        let recent: Vec<&str> = log.lines().rev().take(3).collect();
        if !recent.is_empty() {
            let path = crate::tui::home_as_tilde(&store.log_path().display().to_string());
            let last: Vec<&str> = recent.into_iter().rev().collect();
            report.line(
                Outcome::Note,
                "kaeru",
                &format!("the last problems in {path}:\n{}", last.join("\n")),
            );
        }
    }
    if report.problems == 0 {
        println!("\nNo problems found.");
        Ok(ExitCode::SUCCESS)
    } else {
        Ok(ExitCode::FAILURE)
    }
}

/// Checks the tab that `kaeru doctor` runs in: whether it is a tab of a known
/// terminal, whether its shell loaded kaeru, and whether the terminal reopens
/// its own tabs.
fn check_this_tab(report: &mut Checklist, store: &Store) {
    let mut table = SystemTable::snapshot();
    let Some(shell) = table.get(std::process::id()).and_then(|me| me.parent) else {
        return;
    };
    let full = table.lineage(shell);
    let lineage = procs::without_forks(&full);
    let env: Env = std::env::vars().collect();
    let shells: Vec<ShellNote> = store
        .notes()
        .into_iter()
        .filter_map(|stored| match stored.note {
            Note::Shell(shell) => Some(shell),
            Note::Agent(_) => None,
        })
        .collect();
    match terminals::tab_or_noted(&terminals::all(), &env, lineage, &shells) {
        Some((0, terminal)) => {
            let name = terminals::name_of(&terminal.adapter);
            let process = lineage.first().and_then(|shell| shell.to_ref());
            let tracked = process.is_some_and(|process| {
                store
                    .notes()
                    .iter()
                    .any(|stored| *stored.note.process() == process)
            });
            if tracked {
                report.line(Outcome::Ok, "This tab", &format!("tracked, in {name}"));
            } else {
                report.line(
                    Outcome::Problem,
                    "This tab",
                    &format!(
                        "isn't tracked, in {name}, because its shell didn't load kaeru. Open \
                         a new tab after kaeru install."
                    ),
                );
            }
            if terminal.adapter == "windows-terminal"
                && let Some((settings, value)) =
                    restores_its_own_tabs(terminal.exe.as_deref().map(Path::new))
            {
                report.line(
                    Outcome::Problem,
                    "Windows Terminal",
                    &format!(
                        "reopens its own tabs (\"firstWindowPreference\" is \"{value}\" in \
                         {}), so tabs could come back twice. Turn off \"Open windows from a \
                         previous session\" in its settings.",
                        crate::tui::home_as_tilde(&settings.display().to_string())
                    ),
                );
            }
            // Ghostty brings back its own tabs only on macOS.
            if cfg!(target_os = "macos")
                && terminal.adapter == "ghostty"
                && let Some(problem) = terminal
                    .exe
                    .as_deref()
                    .and_then(ghostty_save_state)
                    .and_then(|value| ghostty_restore_problem(&value))
            {
                report.line(Outcome::Problem, "Ghostty", &problem);
            }
        }
        Some(_) => report.line(
            Outcome::Note,
            "This tab",
            "not checked, because kaeru doctor runs inside another program here, such as an \
             agent. To check this tab, run kaeru doctor at its own prompt.",
        ),
        // Windows doesn't know the parent of a mintty window's bash, so an
        // untracked one looks like a shell outside any terminal.
        None if env
            .get("TERM_PROGRAM")
            .is_some_and(|program| program == "mintty") =>
        {
            report.line(
                Outcome::Problem,
                "This tab",
                "isn't tracked: this mintty window's shell didn't load kaeru. Open a new \
                 window after kaeru install.",
            );
        }
        None => report.line(
            Outcome::Note,
            "This tab",
            "not a tab of a terminal that kaeru knows, so kaeru doesn't track it",
        ),
    }
}

/// Checks the agents' hooks.
fn check_hooks(report: &mut Checklist, files: &[super::HookFile]) {
    for file in files {
        if !file.agent_is_set_up() {
            report.line(Outcome::Note, file.agent, "isn't set up on this computer");
            continue;
        }
        let inline = (file.command == CODEX_HOOK)
            .then(codex_config_with_hooks)
            .flatten();
        let has_hook = match &inline {
            Some(config) => fs::read_to_string(config).is_ok_and(|text| text.contains(CODEX_HOOK)),
            None => match read_json(&file.path) {
                Ok(root) => hooks::has_hook(&root, file.command),
                Err(error) => {
                    report.line(Outcome::Problem, file.agent, &format!("{error:#}"));
                    continue;
                }
            },
        };
        if has_hook {
            report.line(Outcome::Ok, file.agent, "runs kaeru's hook");
            if file.command == CODEX_HOOK {
                if inline.is_some() || !codex_trusts_the_hook(&file.path) {
                    report.line(
                        Outcome::Note,
                        file.agent,
                        "runs the hook only after you trust it: Codex asks when it starts, and \
                         /hooks lists it",
                    );
                }
                check_codex_mode(report);
            }
        } else {
            report.line(
                Outcome::Problem,
                file.agent,
                "doesn't run kaeru's hook. Run kaeru install.",
            );
        }
    }
}

/// Says how kaeru knows which tab a Codex session is in: exactly, when tabs
/// start Codex with `--no-daemon`, or else from when and where the session
/// started.
fn check_codex_mode(report: &mut Checklist) {
    if Store::open().is_ok_and(|store| store.config().codex_no_daemon) {
        report.line(
            Outcome::Ok,
            "Codex",
            "tracked tabs start it with --no-daemon, so kaeru knows each session's tab exactly",
        );
    } else {
        report.line(
            Outcome::Note,
            "Codex",
            "runs sessions in a shared background server, so kaeru works out a session's tab \
             from when and where it started. To make it exact, turn on codex-no-daemon in \
             kaeru options.",
        );
    }
}

/// Returns whether Codex trusts kaeru's hook in `hooks.json`, as its
/// `config.toml` records it.
fn codex_trusts_the_hook(hooks_json: &Path) -> bool {
    let Some(place) = read_json(hooks_json)
        .ok()
        .and_then(|root| hooks::place_of(&root, CODEX_HOOK))
    else {
        return false;
    };
    let Some(config) = codex::home_dir().map(|home| home.join("config.toml")) else {
        return false;
    };
    fs::read_to_string(config)
        .is_ok_and(|text| trusted_in(&text, &hooks_json.display().to_string(), place))
}

/// Returns whether the text of Codex's `config.toml` trusts the hook at
/// `place` in the hooks file at `path`. Codex keeps each trusted hook under
/// `[hooks.state]`, named by the file, the event and the hook's place, such
/// as `'~/.codex/hooks.json:session_start:0:0'`, with the hash it trusted
/// (verify: the format is Codex's own and isn't documented).
fn trusted_in(config: &str, path: &str, (group, index): (usize, usize)) -> bool {
    let Ok(config) = config.parse::<toml::Table>() else {
        return false;
    };
    let key = format!("{path}:session_start:{group}:{index}");
    config
        .get("hooks")
        .and_then(|hooks| hooks.get("state"))
        .and_then(|state| state.get(&key))
        .is_some_and(|hook| {
            hook.get("trusted_hash").is_some()
                && hook.get("enabled").and_then(toml::Value::as_bool) != Some(false)
        })
}

/// Returns Windows Terminal's settings file, and the value it found, when the
/// terminal is set to reopen its own tabs ("Open windows from a previous
/// session"). For the Microsoft Store copy, the settings are in its package's
/// folder; for a portable copy, in the `settings` folder next to it; and
/// otherwise in the user's local app data.
fn restores_its_own_tabs(exe: Option<&Path>) -> Option<(PathBuf, String)> {
    let local = dirs::data_local_dir()?;
    let exe_text = exe.map(|exe| exe.to_string_lossy().to_ascii_lowercase());
    let folder = exe.and_then(Path::parent);
    let settings = match (&exe_text, folder) {
        (Some(text), _) if text.contains(r"\windowsapps\") => {
            let package = if text.contains("windowsterminalpreview") {
                "Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe"
            } else {
                "Microsoft.WindowsTerminal_8wekyb3d8bbwe"
            };
            local
                .join("Packages")
                .join(package)
                .join("LocalState")
                .join("settings.json")
        }
        (_, Some(folder)) if folder.join(".portable").exists() => {
            folder.join("settings").join("settings.json")
        }
        _ => local
            .join("Microsoft")
            .join("Windows Terminal")
            .join("settings.json"),
    };
    let value = persisted_layout(&fs::read_to_string(&settings).ok()?)?;
    Some((settings, value))
}

/// Returns the value of `firstWindowPreference` in Windows Terminal's settings
/// when it makes the terminal reopen its own tabs. Every such value starts with
/// `persisted`: newer versions turn `persistedWindowLayout` into
/// `persistedLayoutAndContent`.
fn persisted_layout(settings: &str) -> Option<String> {
    settings.lines().find_map(|line| {
        let (_, rest) = line.split_once("\"firstWindowPreference\"")?;
        let value = rest.split('"').nth(1)?;
        value.starts_with("persisted").then(|| value.to_string())
    })
}

/// Returns Ghostty's `window-save-state`, which says when Ghostty brings back
/// its own windows and tabs, from what `ghostty +show-config` prints, run
/// with the Ghostty executable `exe`, or `None` when that can't run.
fn ghostty_save_state(exe: &str) -> Option<String> {
    let output = std::process::Command::new(exe)
        .arg("+show-config")
        .output()
        .ok()
        .filter(|output| output.status.success())?;
    Some(save_state(&String::from_utf8_lossy(&output.stdout)).to_string())
}

/// Returns the value of `window-save-state` in what `ghostty +show-config`
/// prints, which leaves out the settings that have their default value.
fn save_state(show_config: &str) -> &str {
    show_config
        .lines()
        .find_map(|line| {
            let (key, value) = line.split_once('=')?;
            (key.trim() == "window-save-state").then(|| value.trim())
        })
        .unwrap_or("default")
}

/// Returns what is wrong when Ghostty brings back its own tabs, with its
/// `window-save-state` as `value`. Ghostty gives its tabs no id that kaeru
/// can read, so kaeru can't tell which tabs Ghostty brought back, and would
/// offer them too.
fn ghostty_restore_problem(value: &str) -> Option<String> {
    let when = match value {
        "never" => return None,
        "always" => "whenever it starts",
        _ => "after a crash, or a restart that reopens windows",
    };
    Some(format!(
        "Ghostty brings back its own tabs {when}, because \"window-save-state\" is \
         \"{value}\" in its config, and it doesn't tell kaeru which tabs those are, so tabs \
         could come back twice. Add window-save-state = never to Ghostty's config, so that \
         kaeru brings them back."
    ))
}

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

    #[test]
    fn ghostty_s_own_restore_is_noticed() {
        assert_eq!(save_state("font-size = 13\n"), "default");
        assert_eq!(
            save_state("font-size = 13\nwindow-save-state = never\n"),
            "never"
        );
        assert!(ghostty_restore_problem("never").is_none());
        assert!(
            ghostty_restore_problem("default")
                .unwrap()
                .contains("after a crash")
        );
        assert!(
            ghostty_restore_problem("always")
                .unwrap()
                .contains("whenever it starts")
        );
    }

    #[test]
    fn codex_s_trust_in_the_hook_is_read_from_its_config() {
        let config = "[hooks.state]\n\n[hooks.state.'/home/demo/.codex/hooks.json:session_start:0:1']\n\
                      trusted_hash = \"sha256:00\"\nenabled = true\n";
        let path = "/home/demo/.codex/hooks.json";
        assert!(trusted_in(config, path, (0, 1)));
        assert!(!trusted_in(config, path, (0, 0)));
        let off = config.replace("enabled = true", "enabled = false");
        assert!(!trusted_in(&off, path, (0, 1)));
        assert!(!trusted_in("", path, (0, 1)));
    }

    #[test]
    fn windows_terminal_s_own_restore_is_noticed() {
        for value in ["persistedWindowLayout", "persistedLayoutAndContent"] {
            let settings = format!("{{\n    \"firstWindowPreference\": \"{value}\",\n}}");
            assert_eq!(persisted_layout(&settings).as_deref(), Some(value));
        }
        let off = "{\n    \"firstWindowPreference\": \"defaultProfile\",\n}";
        assert_eq!(persisted_layout(off), None);
        assert_eq!(persisted_layout("{}"), None);
    }
}