kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! kitty, on Linux. Each `kitty` process runs its own windows and tabs, and
//! starts each tab's shell directly. kitty sets `KITTY_PID`, its own process
//! id, and `KITTY_WINDOW_ID` in the tab, and it doesn't bring back its own
//! tabs, so kaeru reopens them. Other programs can open a tab in a running
//! kitty only when its remote control is turned on, which it isn't by
//! default, so each tab comes back as a window of a new kitty.

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 kitty.
pub struct Kitty;

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

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

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

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

    fn reopen(&self, exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()> {
        let program = exe.unwrap_or(Path::new("kitty"));
        for tab in tabs {
            launch::start(program, &new_window_arguments(tab))?;
        }
        Ok(())
    }
}

/// Returns the kitty process from a shell's lineage (nearest first), or
/// `None` when the shell isn't a tab of kitty. Programs started from a tab
/// inherit `KITTY_PID`, so the shell's parent has to be that kitty.
fn kitty_of(env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
    let kitty: u32 = env.get("KITTY_PID")?.parse().ok()?;
    lineage
        .get(1)
        .filter(|parent| parent.pid == kitty && parent.name == "kitty")
        .cloned()
}

/// Returns the arguments of `kitty` that open one tab as a window, in the
/// tab's folder.
fn new_window_arguments(tab: &TabToOpen) -> Vec<String> {
    let mut args = vec![format!("--directory={}", tab.cwd)];
    args.extend(launch::command(tab));
    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([("KITTY_PID".to_string(), "20".to_string())])
    }

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

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

    #[test]
    fn a_shell_inside_a_tab_or_of_another_kitty_is_not_a_tab() {
        assert!(kitty_of(&tab_env(), &lineage(&tab_table(), 50)).is_none());
        let other = Env::from([("KITTY_PID".to_string(), "30".to_string())]);
        assert!(kitty_of(&other, &lineage(&tab_table(), 40)).is_none());
        assert!(kitty_of(&Env::new(), &lineage(&tab_table(), 40)).is_none());
    }

    #[test]
    fn a_tab_opens_as_a_window_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("fish".into()),
            run: run.iter().map(|word| word.to_string()).collect(),
            ..TabToOpen::default()
        };
        assert_eq!(
            new_window_arguments(&tab(&[])),
            ["--directory=/home/demo/code/web ui"]
        );
        assert_eq!(
            new_window_arguments(&tab(&["codex", "resume", ID])),
            [
                "--directory=/home/demo/code/web ui".to_string(),
                "env".into(),
                format!("KAERU_RUN=cd -- '/home/demo/code/web ui' && codex resume {ID}"),
                "fish".into(),
            ]
        );
    }
}