kaeru 0.1.7

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Terminal adapters: one small module per terminal app.
//! docs/adding-a-terminal.md explains how to add one.

pub mod apple_terminal;
mod applescript;
#[cfg(test)]
mod example;
pub mod ghostty;
pub mod gnome_terminal;
pub mod iterm2;
pub mod kitty;
mod launch;
pub mod mintty;
pub mod warp;
pub mod wezterm;
pub mod windows_terminal;

use std::collections::BTreeMap;
use std::path::Path;

use anyhow::Result;

use crate::engine::note::{ShellNote, TerminalRef};
use crate::engine::rules::TerminalShape;
use crate::procs::ProcInfo;

/// A shell's environment variables. They are passed in rather than read from
/// the current process, so that adapters can be tested.
pub type Env = BTreeMap<String, String>;

/// One tab to bring back.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TabToOpen {
    /// The tab's title.
    pub title: String,
    /// The folder the tab opens in.
    pub cwd: String,
    /// The terminal profile to open the tab with, if the terminal has
    /// profiles.
    pub profile: Option<String>,
    /// The shell to start, such as `powershell` or `bash`, or `None` for the
    /// terminal's or the profile's default.
    pub shell: Option<String>,
    /// What to run in the shell once it is in `cwd`, as separate arguments,
    /// such as `["claude", "--resume", "<id>"]`. Empty means just the shell.
    pub run: Vec<String>,
    /// The shell's executable, if known, so that the tab starts the same
    /// shell.
    pub shell_exe: Option<String>,
    /// For bash, a file that kaeru wrote, which goes to `cwd` and runs `run`,
    /// for bash to read with `--rcfile` instead of `~/.bashrc`. The tab
    /// then stays one bash process that you can type in afterwards.
    pub rcfile: Option<String>,
}

/// Whether a terminal brings back its own tabs after it closed, with the
/// same [`tab_id`](TerminalAdapter::tab_id) as before.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Restores {
    /// It doesn't, or a tab it brings back has a new id, so kaeru reopens
    /// its tabs.
    Never,
    /// It does after some ways of closing and not after others, such as
    /// after a crash but not after you quit it. kaeru resumes the agent
    /// sessions of the tabs that it brings back, in those tabs, and reopens
    /// the others.
    Sometimes,
    /// It always does, as Warp does, so kaeru never reopens its tabs, and
    /// resumes their agent sessions in them.
    Always,
}

/// What every terminal adapter provides.
pub trait TerminalAdapter {
    /// Returns the adapter's stable id, which notes store. It never changes
    /// after a release.
    fn id(&self) -> &'static str;

    /// Returns the terminal's name, as the picker shows it.
    fn name(&self) -> &'static str;

    /// Returns whether the terminal hosts many tabs in one process, or one
    /// shell per window.
    fn shape(&self) -> TerminalShape;

    /// Returns this terminal's process from a shell's lineage (nearest
    /// first), or `None` when the shell doesn't run in this terminal.
    fn find(&self, env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo>;

    /// Returns the tab's id, if the terminal gives tabs an id that survives
    /// its own session restore.
    fn tab_id(&self, _env: &Env) -> Option<String> {
        None
    }

    /// Returns the terminal profile that the tab uses, if the terminal has
    /// profiles.
    fn profile(&self, _env: &Env) -> Option<String> {
        None
    }

    /// Returns whether the terminal reopens its own tabs after it closed,
    /// with the same [`tab_id`](TerminalAdapter::tab_id), so that kaeru
    /// doesn't reopen those tabs, and resumes their agent sessions in them
    /// instead.
    fn restores_its_own_tabs(&self) -> Restores {
        Restores::Never
    }

    /// Returns whether a Windows program that runs in the terminal's tabs
    /// gets a console, which kaeru's picker needs to draw. mintty gives it
    /// pipes instead.
    fn gives_a_console(&self) -> bool {
        true
    }

    /// Opens these tabs, in one window when the terminal supports it. `exe`
    /// is the terminal's executable from the notes, if they recorded it, so
    /// that the tabs open in the same copy of the terminal.
    fn reopen(&self, exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()>;
}

/// Returns every adapter kaeru knows. Terminals are added one at a time, and
/// the README roadmap lists them.
pub fn all() -> Vec<Box<dyn TerminalAdapter>> {
    vec![
        Box::new(windows_terminal::WindowsTerminal),
        Box::new(mintty::Mintty),
        Box::new(warp::Warp),
        Box::new(iterm2::ITerm2),
        Box::new(ghostty::Ghostty),
        Box::new(apple_terminal::AppleTerminal),
        Box::new(gnome_terminal::GnomeTerminal),
        Box::new(kitty::Kitty),
        Box::new(wezterm::WezTerm),
    ]
}

/// Returns the name of the terminal whose adapter has the id `adapter`, or
/// the id itself when this version of kaeru has no such adapter.
pub fn name_of(adapter: &str) -> String {
    all()
        .iter()
        .find(|known| known.id() == adapter)
        .map_or_else(|| adapter.to_string(), |known| known.name().to_string())
}

/// Returns whether the terminal whose adapter has the id `adapter` reopens
/// its own tabs. A terminal that this version of kaeru doesn't know is taken
/// not to.
pub fn restores_its_own_tabs(adapter: &str) -> Restores {
    all()
        .iter()
        .find(|known| known.id() == adapter)
        .map_or(Restores::Never, |known| known.restores_its_own_tabs())
}

/// Returns whether the terminal whose adapter has the id `adapter` gives the
/// programs in its tabs a console. A terminal that this version of kaeru
/// doesn't know is taken to give one.
pub fn gives_a_console(adapter: &str) -> bool {
    all()
        .iter()
        .find(|known| known.id() == adapter)
        .is_none_or(|known| known.gives_a_console())
}

/// Returns the terminal a shell runs in: the adapter whose process is nearest
/// to the shell. For example, a shell inside VS Code that was itself started
/// from Windows Terminal belongs to VS Code.
pub fn detect<'a>(
    adapters: &'a [Box<dyn TerminalAdapter>],
    env: &Env,
    lineage: &[ProcInfo],
) -> Option<(&'a dyn TerminalAdapter, ProcInfo)> {
    adapters
        .iter()
        .filter_map(|adapter| {
            let process = adapter.find(env, lineage)?;
            let depth = lineage.iter().position(|p| p.pid == process.pid)?;
            Some((depth, adapter.as_ref(), process))
        })
        .min_by_key(|(depth, _, _)| *depth)
        .map(|(_, adapter, process)| (adapter, process))
}

/// Returns what a note records about the terminal that a shell runs in, or
/// `None` when the terminal is unknown or its start time can't be read.
pub fn terminal_ref(
    adapters: &[Box<dyn TerminalAdapter>],
    env: &Env,
    lineage: &[ProcInfo],
) -> Option<TerminalRef> {
    let (adapter, process) = detect(adapters, env, lineage)?;
    Some(TerminalRef {
        adapter: adapter.id().into(),
        process: process.to_ref()?,
        shape: adapter.shape(),
        tab_id: adapter.tab_id(env),
        profile: adapter.profile(env),
        exe: process.exe.as_ref().map(|exe| exe.display().to_string()),
    })
}

/// Returns where the tab is in a lineage (nearest first): the index of the
/// first process that an adapter recognizes as a tab's shell, and the
/// terminal. The index is 0 when the lineage starts at the tab's shell.
/// `None` means that the processes don't run in a tab of a known terminal.
pub fn tab_of(
    adapters: &[Box<dyn TerminalAdapter>],
    env: &Env,
    lineage: &[ProcInfo],
) -> Option<(usize, TerminalRef)> {
    (0..lineage.len())
        .find_map(|index| Some((index, terminal_ref(adapters, env, &lineage[index..])?)))
}

/// Returns where the tab is in a lineage, as [`tab_of`] does, or else the
/// nearest process that has a note in `shells`, with that note's terminal.
/// The lineage doesn't always reach the terminal: Windows doesn't know the
/// parent of a shell that mintty started, so the lineage of a program
/// started in that shell ends at the shell.
pub fn tab_or_noted(
    adapters: &[Box<dyn TerminalAdapter>],
    env: &Env,
    lineage: &[ProcInfo],
    shells: &[ShellNote],
) -> Option<(usize, TerminalRef)> {
    tab_of(adapters, env, lineage).or_else(|| {
        lineage.iter().enumerate().find_map(|(index, process)| {
            let process = process.to_ref()?;
            let shell = shells.iter().find(|shell| shell.process == process)?;
            Some((index, shell.terminal.clone()?))
        })
    })
}

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

    /// An adapter that recognizes its terminal by process name only.
    struct ByName(&'static str);

    impl TerminalAdapter for ByName {
        fn id(&self) -> &'static str {
            self.0
        }
        fn name(&self) -> &'static str {
            self.0
        }
        fn shape(&self) -> TerminalShape {
            TerminalShape::Tabs
        }
        fn find(&self, _env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
            lineage.iter().find(|p| p.name == self.0).cloned()
        }
        fn reopen(&self, _exe: Option<&Path>, _tabs: &[TabToOpen]) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn terminals_are_named_by_their_adapter() {
        assert_eq!(name_of("windows-terminal"), "Windows Terminal");
        assert_eq!(name_of("some-future-terminal"), "some-future-terminal");
    }

    #[test]
    fn the_nearest_terminal_wins() {
        let table = FakeTable::new(&[
            (30, Some(20), "bash", Some(300)),
            (20, Some(10), "inner-terminal", Some(200)),
            (10, Some(1), "outer-terminal", Some(100)),
        ]);
        let chain = lineage(&table, 30);
        let adapters: Vec<Box<dyn TerminalAdapter>> = vec![
            Box::new(ByName("outer-terminal")),
            Box::new(ByName("inner-terminal")),
        ];
        let (adapter, process) = detect(&adapters, &Env::new(), &chain).unwrap();
        assert_eq!(adapter.id(), "inner-terminal");
        assert_eq!(process.pid, 20);
    }

    #[test]
    fn a_terminal_ref_records_the_adapter_and_its_process() {
        let table = FakeTable::new(&[
            (20, Some(10), "powershell.exe", Some(2_000)),
            (10, None, "WindowsTerminal.exe", Some(1_000)),
        ])
        .with_exe(10, r"C:\tools\terminal\WindowsTerminal.exe");
        let env = Env::from([
            ("WT_SESSION".to_string(), "x".to_string()),
            ("WT_PROFILE_ID".to_string(), "{p}".to_string()),
        ]);
        let found = terminal_ref(&all(), &env, &lineage(&table, 20)).unwrap();
        assert_eq!(found.adapter, "windows-terminal");
        assert_eq!(found.process.pid, 10);
        assert_eq!(found.process.started_ms, 1_000);
        assert_eq!(found.shape, TerminalShape::Tabs);
        assert_eq!(found.profile.as_deref(), Some("{p}"));
        assert_eq!(
            found.exe.as_deref(),
            Some(r"C:\tools\terminal\WindowsTerminal.exe")
        );
    }

    #[test]
    fn the_tab_is_where_the_terminal_started_a_shell() {
        let table = FakeTable::new(&[
            (40, Some(30), "claude.exe", Some(4_000)),
            (30, Some(20), "pwsh.exe", Some(3_000)),
            (20, Some(10), "powershell.exe", Some(2_000)),
            (10, None, "WindowsTerminal.exe", Some(1_000)),
        ]);
        let env = Env::from([("WT_SESSION".to_string(), "x".to_string())]);
        let tab = |pid| tab_of(&all(), &env, &lineage(&table, pid)).map(|(index, _)| index);
        assert_eq!(tab(20), Some(0), "the tab's own shell");
        assert_eq!(tab(30), Some(1), "a shell inside the tab");
        assert_eq!(tab(40), Some(2), "an agent inside that shell");
        assert_eq!(tab_of(&all(), &Env::new(), &lineage(&table, 40)), None);
    }

    #[test]
    fn no_known_terminal_means_none() {
        let table = FakeTable::new(&[(30, None, "bash", Some(300))]);
        let adapters: Vec<Box<dyn TerminalAdapter>> = vec![Box::new(ByName("some-terminal"))];
        assert!(detect(&adapters, &Env::new(), &lineage(&table, 30)).is_none());
    }
}