kaeru 0.1.7

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Ghostty, on macOS and Linux. It runs all of its windows and tabs in one
//! `ghostty` process, and it sets `TERM_PROGRAM=ghostty` in the tab. On
//! macOS, it starts each tab's shell through `login`, and on Linux, through
//! `/bin/sh -c`. On macOS, 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. On Linux,
//! Ghostty doesn't bring back its tabs.

use std::path::Path;

use anyhow::Result;

use super::{Env, TabToOpen, TerminalAdapter, applescript, launch};
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 and Linux so far, so
        // elsewhere it doesn't track them, to avoid offering tabs that it
        // can't reopen.
        if cfg!(any(target_os = "macos", target_os = "linux")) {
            ghostty_of(env, lineage)
        } else {
            None
        }
    }

    fn reopen(&self, exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()> {
        for tab in tabs {
            if cfg!(target_os = "macos") {
                applescript::run(NEW_TAB, &new_tab_arguments(tab))?;
            } else {
                let program = exe.unwrap_or(Path::new("ghostty"));
                launch::start(program, &new_window_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` on macOS, and by `sh` on Linux, 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" || parent.name == "sh" => 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]
}

/// Returns the arguments of `ghostty` that open one tab as a window, on
/// Linux, in the tab's folder. Ghostty opens tabs only from its own menus
/// and keys there, so each tab comes back as a window. `-e` comes last,
/// because Ghostty takes everything after it as the command.
fn new_window_arguments(tab: &TabToOpen) -> Vec<String> {
    let mut args = vec![format!("--working-directory={}", tab.cwd)];
    let command = launch::command(tab);
    if !command.is_empty() {
        args.push("-e".into());
        args.extend(command);
    }
    args
}

#[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!(any(target_os = "macos", target_os = "linux")));
    }

    #[test]
    fn on_linux_the_ghostty_that_started_a_tab_s_sh_is_the_terminal() {
        let table = FakeTable::new(&[
            (40, Some(30), "bash", Some(400)),
            (30, Some(20), "sh", Some(300)),
            (20, Some(1), "ghostty", Some(200)),
        ]);
        let found = ghostty_of(&tab_env(), &lineage(&table, 40));
        assert_eq!(found.map(|process| process.pid), Some(20));
    }

    #[test]
    fn on_linux_a_tab_opens_as_a_window_with_its_agent_session() {
        let folder = "/home/demo/code/web ui";
        let mut agent = tab(folder, &["claude", "--resume", ID]);
        agent.shell = Some("bash".into());
        assert_eq!(
            new_window_arguments(&agent),
            [
                format!("--working-directory={folder}"),
                "-e".into(),
                "env".into(),
                format!("KAERU_RUN=cd -- '{folder}' && claude --resume {ID}"),
                "bash".into(),
            ]
        );
        assert_eq!(
            new_window_arguments(&tab(folder, &[])),
            [format!("--working-directory={folder}")]
        );
    }

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