kaeru 0.1.9

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, each with the id that its AppleScript gives the
//! tab's terminal. It doesn't tell the tab's shell that id, so kaeru finds
//! it with [`probe_tab_id`]. On Linux, Ghostty doesn't bring back its tabs.

use std::path::Path;

use anyhow::Result;

use super::{Env, Restores, 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 restores_its_own_tabs(&self) -> Restores {
        // Its tabs have an id only when kaeru could read it, which
        // `probe_tab_id` does, and only on macOS. Without one, kaeru reopens
        // the tabs itself, as before.
        if cfg!(target_os = "macos") {
            Restores::Sometimes
        } else {
            Restores::Never
        }
    }

    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 returns the ids of Ghostty's terminals whose title is
/// the one that `argv` gives, one per line, or nothing when none has it.
/// Ghostty shows a title that a program sets a moment after the program
/// sets it, so the script looks a few times. Ghostty has AppleScript since
/// version 1.3, and a terminal is one tab, or one split of a tab.
#[cfg(target_os = "macos")]
const TERMINAL_WITH_TITLE: &str = r#"on run argv
    set wanted to item 1 of argv
    with timeout of 5 seconds
        tell application id "com.mitchellh.ghostty"
            repeat 20 times
                set found to {}
                repeat with candidate in terminals
                    if name of candidate is wanted then
                        set end of found to (id of candidate as text)
                    end if
                end repeat
                if (count of found) > 0 then
                    set AppleScript's text item delimiters to linefeed
                    return found as text
                end if
                delay 0.02
            end repeat
        end tell
    end timeout
    return ""
end run"#;

/// How long kaeru waits for Ghostty to say which terminal a tab is, before
/// it gives up, so that a new tab shows its prompt soon even then.
#[cfg(target_os = "macos")]
const PROBE_LIMIT: std::time::Duration = std::time::Duration::from_secs(2);

/// Returns the id of the Ghostty terminal that this process runs in, which
/// Ghostty keeps when it brings the tab back, or `None` when it can't be
/// read. Ghostty doesn't tell the tab's shell the id, and its AppleScript
/// tells a terminal's title but not its programs, so kaeru sets the tab's
/// title to a token that is new each time, asks Ghostty which terminal has
/// that title, and then clears the title, which the shell's prompt sets
/// again. It runs before the first prompt, when nothing else sets the title.
#[cfg(target_os = "macos")]
pub fn probe_tab_id() -> Option<String> {
    use std::io::Write;

    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |since| since.subsec_nanos());
    let token = format!("kaeru-{}-{nanos:x}", std::process::id());
    let mut tty = std::fs::OpenOptions::new()
        .write(true)
        .open("/dev/tty")
        .ok()?;
    tty.write_all(title_sequence(&token).as_bytes()).ok()?;
    tty.flush().ok()?;
    let printed = applescript::output(TERMINAL_WITH_TITLE, &[token], PROBE_LIMIT);
    let _ = tty.write_all(title_sequence("").as_bytes());
    let _ = tty.flush();
    the_one_id(&printed.ok()?)
}

/// Returns `None`: Ghostty brings back its own tabs only on macOS.
#[cfg(not(target_os = "macos"))]
pub fn probe_tab_id() -> Option<String> {
    None
}

/// Returns the escape sequence that sets a terminal's title.
#[cfg(any(target_os = "macos", test))]
fn title_sequence(title: &str) -> String {
    format!("\x1b]2;{title}\x07")
}

/// Returns the id that [`TERMINAL_WITH_TITLE`] printed, when it printed
/// exactly one that is a UUID. Tokens are new each time, so two terminals
/// with the token can't be told apart, and give no id.
#[cfg(any(target_os = "macos", test))]
fn the_one_id(printed: &str) -> Option<String> {
    let ids: Vec<&str> = printed
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .collect();
    match ids.as_slice() {
        [id] if crate::agents::is_uuid(id) => Some((*id).to_string()),
        _ => 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 the_probe_takes_one_terminal_id() {
        let id = "00000000-0000-4000-8000-00000000000B";
        assert_eq!(the_one_id(&format!("{id}\n")).as_deref(), Some(id));
        assert_eq!(the_one_id(""), None);
        assert_eq!(the_one_id(&format!("{id}\n{id}\n")), None);
        assert_eq!(the_one_id("tab-1\n"), None);
        assert_eq!(title_sequence("kaeru-1-a"), "\x1b]2;kaeru-1-a\x07");
    }

    #[test]
    fn ghostty_restores_its_own_tabs_only_on_macos() {
        let expected = if cfg!(target_os = "macos") {
            Restores::Sometimes
        } else {
            Restores::Never
        };
        assert_eq!(Ghostty.restores_its_own_tabs(), expected);
    }

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