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};
const KAERU: &str = if cfg!(windows) { "kaeru.exe" } else { "kaeru" };
pub fn doctor() -> Result<ExitCode> {
let profiles = profile::profiles();
let files = hook_files();
let names: Vec<&str> = ["kaeru", "This tab", "Open tabs", "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);
let adopted = store
.notes()
.iter()
.filter(|stored| matches!(&stored.note, Note::Shell(shell) if shell.adopted()))
.count();
if adopted > 0 {
report.line(Outcome::Note, "Open tabs", &adopted_text(adopted));
}
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)
}
}
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 note = process.and_then(|process| {
store
.notes()
.into_iter()
.find(|stored| *stored.note.process() == process)
});
match note.map(|stored| stored.note) {
Some(Note::Shell(shell)) if shell.adopted() => report.line(
Outcome::Note,
"This tab",
&format!(
"adopted, in {name}. kaeru reads its folder from outside. A new tab \
is tracked fully."
),
),
Some(_) => report.line(Outcome::Ok, "This tab", &format!("tracked, in {name}")),
None => 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, or run kaeru adopt."
),
),
}
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())
),
);
}
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.",
),
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",
),
}
}
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.",
);
}
}
}
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.",
);
}
}
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))
}
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)
})
}
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))
}
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())
})
}
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())
}
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")
}
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."
))
}
fn adopted_text(count: usize) -> String {
let (tabs, they) = if count == 1 {
("1 tab is".to_string(), "it is")
} else {
(format!("{count} tabs are"), "they are")
};
format!(
"{tabs} adopted: kaeru reads their folders from outside, so a folder can be out of \
date. Once {they} replaced by new tabs, kaeru tracks those fully."
)
}
#[cfg(test)]
mod tests {
#[test]
fn adopted_tabs_are_counted() {
assert!(adopted_text(1).starts_with("1 tab is adopted"));
assert!(adopted_text(3).starts_with("3 tabs are adopted"));
assert!(adopted_text(3).contains("Once they are replaced"));
}
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);
}
}