kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! iTerm2, on macOS. It runs its tabs' shells in a server process of its
//! own, `iTermServer`, through `login`, so a tab's lineage is the shell,
//! `login`, the server, and while the iTerm2 that started the server runs,
//! iTerm2. When iTerm2 crashes, the server and the tabs' programs keep
//! running, and iTerm2 takes them back when it starts again. When you quit
//! it, they end. iTerm2 sets `TERM_PROGRAM=iTerm.app` and
//! `ITERM_SESSION_ID`, whose id stays the same when iTerm2 brings a tab back
//! by itself.

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 iTerm2.
pub struct ITerm2;

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

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

    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 the server started, and the server is the terminal:
        // it ends when iTerm2 quits, and it keeps running when iTerm2
        // crashes, together with the tabs' programs.
        if env.get("TERM_PROGRAM").map(String::as_str) != Some("iTerm.app") {
            return None;
        }
        let is_terminal = |process: &ProcInfo| {
            process.name.starts_with("iTermServer") || process.name == "iTerm2"
        };
        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> {
        // The variable looks like w0t1p0:<id>, where the part before the
        // colon is where the tab is, which changes when tabs move.
        let session = env.get("ITERM_SESSION_ID")?;
        let id = session
            .rsplit_once(':')
            .map_or(session.as_str(), |(_, id)| id);
        (!id.is_empty()).then(|| id.to_string())
    }

    fn profile(&self, env: &Env) -> Option<String> {
        env.get("ITERM_PROFILE").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_TAB, &new_tab_arguments(tab))?;
        }
        Ok(())
    }
}

/// The AppleScript that opens a tab in iTerm2's current window, or in a new
/// window when it has none, with the profile that `argv` names, or the
/// default one, and types the line that `argv` gives into the tab's shell.
/// The tab starts your login shell, as iTerm2's own tabs do, and the line
/// goes to the folder and resumes the agent session, as if you typed it.
const NEW_TAB: &str = r#"on run argv
    set profileName to item 1 of argv
    set typed to item 2 of argv
    with timeout of 30 seconds
        tell application id "com.googlecode.iterm2"
            set target to current window
            if target is missing value then
                try
                    set target to (create window with profile profileName)
                on error
                    set target to (create window with default profile)
                end try
                set newSession to current session of target
            else
                tell target
                    try
                        set newTab to (create tab with profile profileName)
                    on error
                        set newTab to (create tab with default profile)
                    end try
                end tell
                set newSession to current session of newTab
            end if
            tell newSession to write text typed
        end tell
    end timeout
end run"#;

/// Returns the arguments of [`NEW_TAB`] for one tab: its profile, or nothing
/// for the default one, and the line that goes to its folder and runs what
/// it runs.
fn new_tab_arguments(tab: &TabToOpen) -> Vec<String> {
    vec![
        tab.profile.clone().unwrap_or_default(),
        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(), "iTerm.app".to_string()),
            ("ITERM_SESSION_ID".to_string(), format!("w0t1p0:{ID}")),
            ("ITERM_PROFILE".to_string(), "Default".to_string()),
        ])
    }

    /// A tab's shell (40), login (30), the server (20) and iTerm2 (10), 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(10), "iTermServer-3.6.10", Some(200)),
            (10, Some(1), "iTerm2", Some(100)),
        ])
    }

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

    #[test]
    fn a_tab_whose_iterm2_crashed_still_has_its_server() {
        // The server outlives iTerm2, and the OS makes it a child of
        // launchd.
        let table = FakeTable::new(&[
            (40, Some(30), "zsh", Some(400)),
            (30, Some(20), "login", Some(300)),
            (20, Some(1), "iTermServer-3.6.10", Some(200)),
        ]);
        let found = ITerm2.find(&tab_env(), &lineage(&table, 40));
        assert_eq!(found.map(|process| process.pid), Some(20));
    }

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

    #[test]
    fn the_tab_id_leaves_out_where_the_tab_is() {
        assert_eq!(ITerm2.tab_id(&tab_env()).as_deref(), Some(ID));
        let moved = Env::from([("ITERM_SESSION_ID".to_string(), format!("w1t0p0:{ID}"))]);
        assert_eq!(ITerm2.tab_id(&moved).as_deref(), Some(ID));
        assert_eq!(ITerm2.tab_id(&Env::new()), None);
        assert_eq!(ITerm2.profile(&tab_env()).as_deref(), Some("Default"));
    }

    fn tab(cwd: &str, run: &[&str]) -> TabToOpen {
        TabToOpen {
            title: "mobile-app".into(),
            cwd: cwd.into(),
            profile: Some("Work".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() {
        let folder = "/Users/demo/code/it's my 프로젝트";
        assert_eq!(
            new_tab_arguments(&tab(folder, &[])),
            ["Work", r"cd -- '/Users/demo/code/it'\''s my 프로젝트'"]
        );
    }

    #[test]
    fn an_agent_tab_resumes_its_session_in_its_folder() {
        let mut agent = tab("/Users/demo/code/api-server", &["claude", "--resume", ID]);
        agent.profile = None;
        assert_eq!(
            new_tab_arguments(&agent),
            [
                String::new(),
                format!("cd -- /Users/demo/code/api-server && claude --resume {ID}")
            ]
        );
    }

    #[test]
    fn iterm2_sometimes_restores_its_own_tabs() {
        assert_eq!(
            super::super::restores_its_own_tabs("iterm2"),
            Restores::Sometimes
        );
    }
}