use std::fs;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use anyhow::Result;
use ratatui::crossterm::queue;
use ratatui::crossterm::style::{Color, Print, ResetColor, SetForegroundColor};
use super::read_or_empty;
use super::{
CODEX_HOOK, bash_profile_problem, codex_config_with_hooks, hook_files, hooks, on_path, profile,
read_json,
};
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" };
struct Report {
problems: usize,
color: bool,
}
impl Report {
fn new() -> Self {
Self {
problems: 0,
color: crate::tui::colors_wanted() && io::stdout().is_terminal(),
}
}
fn ok(&mut self, text: &str) {
self.line("ok", Color::Green, text);
}
fn problem(&mut self, text: &str) {
self.line("problem", Color::Red, text);
self.problems += 1;
}
fn note(&mut self, text: &str) {
self.line("note", Color::Yellow, text);
}
fn line(&self, label: &str, color: Color, text: &str) {
let label = format!("{label:<9}");
let mut out = io::stdout().lock();
let _ = if self.color {
queue!(
out,
SetForegroundColor(color),
Print(label),
ResetColor,
Print(text),
Print("\n")
)
} else {
queue!(out, Print(label), Print(text), Print("\n"))
};
let _ = out.flush();
}
}
pub fn doctor() -> Result<ExitCode> {
let mut report = Report::new();
match on_path(KAERU) {
Some(path) => report.ok(&format!("kaeru is on the PATH: {}", path.display())),
None => report
.problem("kaeru isn't on the PATH, so the profile line and the hooks can't run it."),
}
for profile in profile::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.problem(&problem),
None => report.ok(&format!("The {} profile loads kaeru.", profile.shell)),
},
Ok(false) => report.problem(&format!(
"The {} profile doesn't load kaeru. Run kaeru install.",
profile.shell
)),
Err(error) => report.problem(&format!("{error:#}")),
}
}
let store = Store::open()?;
check_this_tab(&mut report, &store);
check_hooks(&mut report);
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() {
report.note(&format!(
"The last problems in {}:",
store.log_path().display()
));
for line in recent.iter().rev() {
println!(" {line}");
}
}
}
if report.problems == 0 {
println!("\nNo problems found.");
Ok(ExitCode::SUCCESS)
} else {
Ok(ExitCode::FAILURE)
}
}
fn check_this_tab(report: &mut Report, 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.ok(&format!("This tab of {name} is tracked."));
} else {
report.problem(&format!(
"This tab of {name} isn't tracked, 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.problem(&format!(
"Windows Terminal 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.",
settings.display()
));
}
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.problem(&problem);
}
}
Some(_) => report
.note("This shell runs inside another program in a tab, which kaeru tracks instead."),
None if env
.get("TERM_PROGRAM")
.is_some_and(|program| program == "mintty") =>
{
report.problem(
"This mintty window isn't tracked, because its shell didn't load kaeru. Open a \
new window after kaeru install.",
)
}
None => report.note(
"This shell isn't a tab of a terminal that kaeru knows, so kaeru doesn't track it.",
),
}
}
fn check_hooks(report: &mut Report) {
for file in hook_files() {
if !file.agent_is_set_up() {
report.note(&format!("{} isn't set up on this computer.", file.agent));
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.problem(&format!("{error:#}"));
continue;
}
},
};
if has_hook {
report.ok(&format!("{} runs kaeru's hook.", file.agent));
if file.command == CODEX_HOOK {
report.note(
"Codex runs the hook only after you trust it: Codex asks when it starts, \
and /hooks lists it.",
);
check_codex_mode(report);
}
} else {
report.problem(&format!(
"{} doesn't run kaeru's hook. Run kaeru install.",
file.agent
));
}
}
}
fn check_codex_mode(report: &mut Report) {
if Store::open().is_ok_and(|store| store.config().codex_no_daemon) {
report.ok(
"Tabs that kaeru tracks start Codex with --no-daemon, so kaeru knows exactly which \
tab each Codex session is in.",
);
} else {
report.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, run kaeru install and let \
tabs start Codex with --no-daemon.",
);
}
}
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."
))
}
#[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 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);
}
}