kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Warp. On Windows, it runs all of its windows and tabs in one `warp.exe`
//! process, and starts each tab's shell as a direct child of it. On macOS,
//! its app starts a terminal server, a program of its own, which starts the
//! shells. It sets `TERM_PROGRAM=WarpTerminal` and
//! `WARP_TERMINAL_SESSION_UUID`, an id for the tab that stays the same when
//! Warp restores the tab after it closed. Warp restores its own tabs, so kaeru
//! doesn't reopen them; it resumes the agent session in the restored tab.

use std::path::Path;

use anyhow::{Result, bail};

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

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

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

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

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

    fn find(&self, env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
        // Programs started from a Warp tab inherit these variables, so a
        // tab's shell is also a direct child of Warp.
        if env.get("TERM_PROGRAM").map(String::as_str) != Some("WarpTerminal") {
            return None;
        }
        lineage.get(1).filter(|parent| is_warp(parent)).cloned()
    }

    fn tab_id(&self, env: &Env) -> Option<String> {
        env.get("WARP_TERMINAL_SESSION_UUID").cloned()
    }

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

    fn reopen(&self, _exe: Option<&Path>, _tabs: &[TabToOpen]) -> Result<()> {
        bail!("Warp reopens its own tabs, and kaeru resumes their agent sessions there")
    }
}

/// Returns whether a process is Warp: `warp.exe` on Windows, or on macOS,
/// a program of a `Warp` app, which is named after Warp's channel, such as
/// `stable`. On macOS, a tab's shell runs under Warp's terminal server,
/// which is such a program too.
fn is_warp(process: &ProcInfo) -> bool {
    if process.name.eq_ignore_ascii_case("warp.exe") || process.name.eq_ignore_ascii_case("warp") {
        return true;
    }
    let Some(exe) = &process.exe else {
        return false;
    };
    let folders: Vec<String> = exe
        .iter()
        .map(|part| part.to_string_lossy().into_owned())
        .collect();
    folders.windows(3).any(|window| {
        window[0].starts_with("Warp")
            && window[0].ends_with(".app")
            && window[1] == "Contents"
            && window[2] == "MacOS"
    })
}

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

    fn warp_env() -> Env {
        Env::from([
            ("TERM_PROGRAM".to_string(), "WarpTerminal".to_string()),
            (
                "WARP_TERMINAL_SESSION_UUID".to_string(),
                "00000000000040008000000000000004".to_string(),
            ),
        ])
    }

    #[test]
    fn a_shell_that_warp_started_is_a_tab_with_warp_s_id() {
        let table = FakeTable::new(&[
            (20, Some(10), "powershell.exe", Some(200)),
            (10, None, "warp.exe", Some(100)),
        ]);
        let found = Warp.find(&warp_env(), &lineage(&table, 20));
        assert_eq!(found.map(|process| process.pid), Some(10));
        assert_eq!(
            Warp.tab_id(&warp_env()).as_deref(),
            Some("00000000000040008000000000000004")
        );
    }

    #[test]
    fn a_shell_that_warp_s_terminal_server_started_on_macos_is_a_tab() {
        let app = "/Applications/Warp.app/Contents/MacOS/stable";
        let table = FakeTable::new(&[
            (30, Some(20), "zsh", Some(300)),
            (20, Some(10), "stable", Some(200)),
            (10, Some(1), "stable", Some(100)),
        ])
        .with_exe(20, app)
        .with_exe(10, app);
        let found = Warp.find(&warp_env(), &lineage(&table, 30));
        assert_eq!(found.map(|process| process.pid), Some(20));
        // A program named stable that isn't Warp's is something else.
        let other = FakeTable::new(&[
            (30, Some(20), "zsh", Some(300)),
            (20, None, "stable", Some(200)),
        ])
        .with_exe(20, "/Applications/Other.app/Contents/MacOS/stable");
        assert!(Warp.find(&warp_env(), &lineage(&other, 30)).is_none());
    }

    #[test]
    fn a_shell_inside_a_warp_tab_is_not_a_tab() {
        let table = FakeTable::new(&[
            (30, Some(20), "pwsh.exe", Some(300)),
            (20, Some(10), "powershell.exe", Some(200)),
            (10, None, "warp.exe", Some(100)),
        ]);
        assert!(Warp.find(&warp_env(), &lineage(&table, 30)).is_none());
        // Without Warp's variable, a warp.exe is some other program.
        let table = FakeTable::new(&[
            (20, Some(10), "powershell.exe", Some(200)),
            (10, None, "warp.exe", Some(100)),
        ]);
        assert!(Warp.find(&Env::new(), &lineage(&table, 20)).is_none());
    }
}