kaeru 0.1.2

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! `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::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};

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

/// What `kaeru doctor` found, printed one line at a time.
#[derive(Default)]
struct Report {
    /// How many things need fixing.
    problems: usize,
}

impl Report {
    /// Prints something that is set up right.
    fn ok(&mut self, text: &str) {
        println!("ok       {text}");
    }

    /// Prints something that needs fixing, and counts it.
    fn problem(&mut self, text: &str) {
        println!("problem  {text}");
        self.problems += 1;
    }

    /// Prints something that is worth knowing but needs no fixing.
    fn note(&mut self, text: &str) {
        println!("note     {text}");
    }
}

/// 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 mut report = Report::default();
    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)
    }
}

/// 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 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()
                ));
            }
        }
        Some(_) => report
            .note("This shell runs inside another program in a tab, which kaeru tracks instead."),
        // 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.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.",
        ),
    }
}

/// Checks the agents' hooks.
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
            ));
        }
    }
}

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

/// 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())
    })
}

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

    #[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);
    }
}