kaeru 0.1.7

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! WezTerm, on Linux. Its GUI, `wezterm-gui`, runs the windows and tabs and
//! starts each tab's shell directly, as a login shell. It sets
//! `TERM_PROGRAM=WezTerm`, `WEZTERM_PANE`, an id for the pane, and
//! `WEZTERM_UNIX_SOCKET`, through which `wezterm cli` reaches the GUI. It
//! doesn't bring back its own tabs, so kaeru reopens them, with
//! `wezterm cli spawn`, which opens a tab in the window that the picker
//! runs in.

use std::path::Path;

use anyhow::Result;

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

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

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

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

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

    fn find(&self, env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
        // kaeru opens WezTerm's tabs only on Linux so far.
        if cfg!(target_os = "linux") {
            gui_of(env, lineage)
        } else {
            None
        }
    }

    fn reopen(&self, exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()> {
        let program = launch::beside(exe, "wezterm");
        for tab in tabs {
            // Outside WezTerm, the command can't reach a window, and the
            // tab comes back in a new one.
            if launch::run(&program, &spawn_arguments(tab)).is_err() {
                launch::start(&program, &start_arguments(tab))?;
            }
        }
        Ok(())
    }
}

/// Returns WezTerm's GUI from a shell's lineage (nearest first), or `None`
/// when the shell isn't one of its tabs. Programs started from a tab inherit
/// `TERM_PROGRAM`, so the shell's parent has to be the GUI.
fn gui_of(env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
    if env.get("TERM_PROGRAM").map(String::as_str) != Some("WezTerm") {
        return None;
    }
    lineage
        .get(1)
        .filter(|parent| parent.name == "wezterm-gui")
        .cloned()
}

/// Returns the arguments of `wezterm` that open one tab in the window that
/// the picker runs in, in the tab's folder. Without a GUI to reach, `cli`
/// would start a server of its own, with no window.
fn spawn_arguments(tab: &TabToOpen) -> Vec<String> {
    with_command(
        vec![
            "cli".into(),
            "--no-auto-start".into(),
            "spawn".into(),
            "--cwd".into(),
            tab.cwd.clone(),
        ],
        tab,
    )
}

/// Returns the arguments of `wezterm` that open one tab in a new window, in
/// the tab's folder.
fn start_arguments(tab: &TabToOpen) -> Vec<String> {
    with_command(vec!["start".into(), "--cwd".into(), tab.cwd.clone()], tab)
}

/// Returns `args`, followed by the command that the tab runs, if any.
fn with_command(mut args: Vec<String>, tab: &TabToOpen) -> Vec<String> {
    let command = launch::command(tab);
    if !command.is_empty() {
        args.push("--".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(), "WezTerm".to_string())])
    }

    /// A tab's shell (40), started by the GUI (20), and a shell inside the
    /// tab (50).
    fn tab_table() -> FakeTable {
        FakeTable::new(&[
            (50, Some(40), "zsh", Some(500)),
            (40, Some(20), "zsh", Some(400)),
            (20, Some(1), "wezterm-gui", Some(200)),
        ])
    }

    #[test]
    fn the_gui_that_started_a_tab_s_shell_is_the_terminal() {
        let found = gui_of(&tab_env(), &lineage(&tab_table(), 40));
        assert_eq!(found.map(|process| process.pid), Some(20));
        let tracked = WezTerm
            .find(&tab_env(), &lineage(&tab_table(), 40))
            .is_some();
        assert_eq!(tracked, cfg!(target_os = "linux"));
    }

    #[test]
    fn a_shell_inside_a_tab_or_outside_wezterm_is_not_a_tab() {
        assert!(gui_of(&tab_env(), &lineage(&tab_table(), 50)).is_none());
        assert!(gui_of(&Env::new(), &lineage(&tab_table(), 40)).is_none());
    }

    #[test]
    fn a_tab_opens_in_its_folder_with_its_agent_session() {
        let tab = |run: &[&str]| TabToOpen {
            title: "web-ui".into(),
            cwd: "/home/demo/code/web-ui".into(),
            shell: Some("zsh".into()),
            run: run.iter().map(|word| word.to_string()).collect(),
            ..TabToOpen::default()
        };
        assert_eq!(
            spawn_arguments(&tab(&[])),
            [
                "cli",
                "--no-auto-start",
                "spawn",
                "--cwd",
                "/home/demo/code/web-ui"
            ]
        );
        assert_eq!(
            start_arguments(&tab(&["claude", "--resume", ID])),
            [
                "start".to_string(),
                "--cwd".into(),
                "/home/demo/code/web-ui".into(),
                "--".into(),
                "env".into(),
                format!("KAERU_RUN=cd -- /home/demo/code/web-ui && claude --resume {ID}"),
                "zsh".into(),
            ]
        );
    }
}