kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Terminal, the terminal app that comes with macOS. It runs all of its
//! windows and tabs in one `Terminal` process, which starts each tab's shell
//! through `login`, and it sets `TERM_PROGRAM=Apple_Terminal` and
//! `TERM_SESSION_ID`, an id for the tab, which stays the same when Terminal
//! brings the tab back by itself, as after a restart that reopens windows.

use std::path::Path;

use anyhow::Result;

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

/// The adapter for Terminal.
pub struct AppleTerminal;

impl TerminalAdapter for AppleTerminal {
    fn id(&self) -> &'static str {
        "apple-terminal"
    }

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

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

    fn find(&self, env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
        // 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 Terminal started.
        if env.get("TERM_PROGRAM").map(String::as_str) != Some("Apple_Terminal") {
            return None;
        }
        let is_terminal = |process: &ProcInfo| process.name == "Terminal";
        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,
        }
    }

    fn tab_id(&self, env: &Env) -> Option<String> {
        env.get("TERM_SESSION_ID")
            .filter(|id| !id.is_empty())
            .cloned()
    }

    fn restores_its_own_tabs(&self) -> Restores {
        Restores::Sometimes
    }

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

/// The AppleScript that opens a Terminal window and types the line that
/// `argv` gives into its shell, as if you typed it. The window starts your
/// login shell, as Terminal's own windows do. Terminal's AppleScript has no
/// command that opens a tab, so each tab comes back as a window.
const NEW_WINDOW: &str = r#"on run argv
    set typed to item 1 of argv
    with timeout of 30 seconds
        tell application id "com.apple.Terminal"
            do script typed
        end tell
    end timeout
end run"#;

/// Returns the arguments of [`NEW_WINDOW`] for one tab: the line that goes
/// to its folder and runs what it runs.
fn new_window_arguments(tab: &TabToOpen) -> Vec<String> {
    vec![shells::bash_run_line(&tab.cwd, &tab.run)]
}

#[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(), "Apple_Terminal".to_string()),
            ("TERM_SESSION_ID".to_string(), ID.to_string()),
        ])
    }

    /// A tab's shell (40), login (30) and Terminal (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), "Terminal", Some(200)),
        ])
    }

    #[test]
    fn the_terminal_that_started_a_tab_s_login_is_the_terminal() {
        let found = AppleTerminal.find(&tab_env(), &lineage(&tab_table(), 40));
        assert_eq!(found.map(|process| process.pid), Some(20));
        assert_eq!(AppleTerminal.tab_id(&tab_env()).as_deref(), Some(ID));
    }

    #[test]
    fn a_shell_inside_a_tab_is_not_a_tab() {
        assert!(
            AppleTerminal
                .find(&tab_env(), &lineage(&tab_table(), 50))
                .is_none()
        );
        // Without Terminal's variable, the same processes are something
        // else.
        assert!(
            AppleTerminal
                .find(&Env::new(), &lineage(&tab_table(), 40))
                .is_none()
        );
    }

    #[test]
    fn terminal_sometimes_restores_its_own_tabs() {
        assert_eq!(
            super::super::restores_its_own_tabs("apple-terminal"),
            Restores::Sometimes
        );
    }

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

    #[test]
    fn a_plain_tab_goes_to_its_folder() {
        assert_eq!(
            new_window_arguments(&tab("/Users/demo/code/it's my 프로젝트", &[])),
            [r"cd -- '/Users/demo/code/it'\''s my 프로젝트'"]
        );
    }

    #[test]
    fn an_agent_tab_resumes_its_session_in_its_folder() {
        assert_eq!(
            new_window_arguments(&tab(
                "/Users/demo/code/api-server",
                &["claude", "--resume", ID]
            )),
            [format!(
                "cd -- /Users/demo/code/api-server && claude --resume {ID}"
            )]
        );
    }
}