kaeru 0.1.5

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Ghostty, on macOS. It runs all of its windows and tabs in one `ghostty`
//! process, which starts each tab's shell through `login`, and it sets
//! `TERM_PROGRAM=ghostty` in the tab. It brings back its own tabs after a
//! crash, or a quit that keeps windows, but it gives a tab's shell no id that
//! would tell kaeru which tab came back, so kaeru reopens Ghostty's tabs
//! itself, and `kaeru doctor` says how to turn Ghostty's own restore off.

use std::path::Path;

use anyhow::Result;

use super::{Env, TabToOpen, TerminalAdapter, applescript};
use crate::engine::rules::TerminalShape;
use crate::procs::ProcInfo;
use crate::shells;

/// The adapter for Ghostty.
pub struct Ghostty;

impl TerminalAdapter for Ghostty {
    fn id(&self) -> &'static str {
        "ghostty"
    }

    fn name(&self) -> &'static str {
        "Ghostty"
    }

    fn shape(&self) -> TerminalShape {
        TerminalShape::Tabs
    }

    fn find(&self, env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
        // kaeru opens Ghostty's tabs only on macOS so far, so elsewhere it
        // doesn't track them, to avoid offering tabs that it can't reopen.
        if cfg!(target_os = "macos") {
            ghostty_of(env, lineage)
        } else {
            None
        }
    }

    fn reopen(&self, _exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()> {
        for tab in tabs {
            applescript::run(NEW_TAB, &new_tab_arguments(tab))?;
        }
        Ok(())
    }
}

/// Returns the Ghostty process from a shell's lineage (nearest first), or
/// `None` when the shell isn't a tab of Ghostty. Programs started from a tab
/// inherit `TERM_PROGRAM`, so the variable alone doesn't make a shell a tab.
/// A tab's shell is started by `login`, which Ghostty started.
fn ghostty_of(env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
    if env.get("TERM_PROGRAM").map(String::as_str) != Some("ghostty") {
        return None;
    }
    let is_terminal = |process: &ProcInfo| process.name == "ghostty";
    match lineage.get(1) {
        Some(parent) if is_terminal(parent) => Some(parent.clone()),
        Some(parent) if parent.name == "login" => lineage
            .get(2)
            .filter(|process| is_terminal(process))
            .cloned(),
        _ => None,
    }
}

/// The AppleScript that opens a tab in Ghostty's front window, or a window
/// when it has none, in the folder that `argv` names, and, when `argv`
/// gives a line, types it into the tab's shell, as if you typed it. The tab
/// starts your login shell, as Ghostty's own tabs do. Ghostty has
/// AppleScript since version 1.3.
const NEW_TAB: &str = r#"on run argv
    set startFolder to item 1 of argv
    set typed to item 2 of argv
    with timeout of 30 seconds
        tell application id "com.mitchellh.ghostty"
            set settings to new surface configuration
            set initial working directory of settings to startFolder
            if typed is not "" then
                set initial input of settings to typed & return
            end if
            if (count of windows) is 0 then
                new window with configuration settings
            else
                new tab in front window with configuration settings
            end if
        end tell
    end timeout
end run"#;

/// Returns the arguments of [`NEW_TAB`] for one tab: its folder, and for a
/// tab that runs something, the line that goes to the folder and runs it,
/// which also works when the shell's startup files changed the folder.
fn new_tab_arguments(tab: &TabToOpen) -> Vec<String> {
    let typed = if tab.run.is_empty() {
        String::new()
    } else {
        shells::bash_run_line(&tab.cwd, &tab.run)
    };
    vec![tab.cwd.clone(), typed]
}

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

    const ID: &str = "00000000-0000-4000-8000-000000000001";

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

    /// A tab's shell (40), login (30) and Ghostty (20), and a shell inside
    /// the tab (50).
    fn tab_table() -> FakeTable {
        FakeTable::new(&[
            (50, Some(40), "zsh", Some(500)),
            (40, Some(30), "zsh", Some(400)),
            (30, Some(20), "login", Some(300)),
            (20, Some(1), "ghostty", Some(200)),
        ])
    }

    #[test]
    fn the_ghostty_that_started_a_tab_s_login_is_the_terminal() {
        let found = ghostty_of(&tab_env(), &lineage(&tab_table(), 40));
        assert_eq!(found.map(|process| process.pid), Some(20));
        let tracked = Ghostty
            .find(&tab_env(), &lineage(&tab_table(), 40))
            .is_some();
        assert_eq!(tracked, cfg!(target_os = "macos"));
    }

    #[test]
    fn a_shell_inside_a_tab_is_not_a_tab() {
        assert!(ghostty_of(&tab_env(), &lineage(&tab_table(), 50)).is_none());
        // A terminal started from a Ghostty tab inherits TERM_PROGRAM until
        // it sets its own, and the lineage still has to be Ghostty's.
        assert!(ghostty_of(&Env::new(), &lineage(&tab_table(), 40)).is_none());
    }

    #[test]
    fn ghostty_gives_kaeru_no_tab_id() {
        let mut env = tab_env();
        // Inherited from the terminal that started Ghostty.
        env.insert("TERM_SESSION_ID".into(), ID.into());
        assert_eq!(Ghostty.tab_id(&env), None);
    }

    fn tab(cwd: &str, run: &[&str]) -> TabToOpen {
        TabToOpen {
            title: "web-ui".into(),
            cwd: cwd.into(),
            shell: Some("zsh".into()),
            run: run.iter().map(|word| word.to_string()).collect(),
            ..TabToOpen::default()
        }
    }

    #[test]
    fn a_plain_tab_opens_in_its_folder_and_types_nothing() {
        let folder = "/Users/demo/code/it's my 프로젝트";
        assert_eq!(new_tab_arguments(&tab(folder, &[])), [folder, ""]);
    }

    #[test]
    fn an_agent_tab_types_the_line_that_resumes_its_session() {
        let folder = "/Users/demo/code/web ui";
        assert_eq!(
            new_tab_arguments(&tab(folder, &["claude", "--resume", ID])),
            [
                folder.to_string(),
                format!("cd -- '/Users/demo/code/web ui' && claude --resume {ID}")
            ]
        );
    }
}