kaeru 0.1.0

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.

#[cfg(test)]
mod example;
pub mod windows_terminal;

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

use anyhow::Result;

use crate::engine::note::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, 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>,
}

/// 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
    }

    /// 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)]
}

/// 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 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..])?)))
}

#[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());
    }
}