kaeru 0.1.1

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Windows Terminal. It runs all of its windows and tabs in one
//! `WindowsTerminal.exe` process, starts each tab's shell as a direct child
//! of that process, and sets `WT_SESSION` and `WT_PROFILE_ID` in the tab's
//! environment.

use std::path::{Path, PathBuf};

use anyhow::Result;

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

/// The adapter for Windows Terminal.
pub struct WindowsTerminal;

impl TerminalAdapter for WindowsTerminal {
    fn id(&self) -> &'static str {
        "windows-terminal"
    }

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

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

    fn find(&self, env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
        // Programs started from a tab inherit WT_SESSION, so the variable
        // alone doesn't make a shell a tab. A tab's shell is a direct child
        // of the terminal; a shell inside another program in the tab, such
        // as a nested shell or an editor, isn't a tab of its own.
        env.get("WT_SESSION")?;
        lineage
            .get(1)
            .filter(|parent| parent.name.eq_ignore_ascii_case("WindowsTerminal.exe"))
            .cloned()
    }

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

    fn reopen(&self, exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()> {
        if tabs.is_empty() {
            return Ok(());
        }
        launch(&wt_exe(exe), &wt_arguments(tabs))
    }
}

/// Starts `wt.exe` with a command line that is passed on as it is, because
/// `wt.exe` splits its command line itself, at `;`.
#[cfg(windows)]
fn launch(wt: &Path, arguments: &str) -> Result<()> {
    use std::os::windows::process::CommandExt;

    use anyhow::Context;

    std::process::Command::new(wt)
        .raw_arg(arguments)
        .spawn()
        .with_context(|| format!("can't start {}", wt.display()))?;
    Ok(())
}

/// Fails, because Windows Terminal runs only on Windows.
#[cfg(not(windows))]
fn launch(_wt: &Path, _arguments: &str) -> Result<()> {
    anyhow::bail!("Windows Terminal runs only on Windows")
}

/// Returns the `wt.exe` to run: the one next to the terminal's executable, so
/// that the tabs open in the same copy, such as a portable one. The Microsoft
/// Store's copy is in a folder that can't be run from, so for it, and when
/// there is no `wt.exe` next to the executable, it is the `wt.exe` command
/// that Windows provides.
fn wt_exe(terminal: Option<&Path>) -> PathBuf {
    terminal
        .filter(|exe| {
            !exe.to_string_lossy()
                .to_ascii_lowercase()
                .contains(r"\windowsapps\")
        })
        .and_then(Path::parent)
        .map(|folder| folder.join("wt.exe"))
        .filter(|wt| wt.is_file())
        .unwrap_or_else(|| PathBuf::from("wt.exe"))
}
/// Returns the command line for `wt.exe` that opens the given tabs, in the
/// most recently used window (`-w 0`). kaeru passes one tab at a time.
/// the most recently used window (`-w 0`).
fn wt_arguments(tabs: &[TabToOpen]) -> String {
    let commands: Vec<String> = tabs.iter().map(new_tab).collect();
    format!("-w 0 {}", commands.join(" ; "))
}

/// Returns the `new-tab` command for one tab. A plain tab starts its
/// profile's own shell. A tab that runs something starts PowerShell, which
/// goes to the folder and runs it.
fn new_tab(tab: &TabToOpen) -> String {
    let mut command = format!("new-tab --title {}", quote(&tab.title));
    if let Some(profile) = &tab.profile {
        command.push_str(&format!(" -p {}", quote(profile)));
    }
    command.push_str(&format!(" -d {}", quote(&tab.cwd)));
    if !tab.run.is_empty() {
        let script = base64(&utf16_le(&tab_script(&tab.cwd, &tab.run)));
        let powershell = powershell(tab.shell.as_deref());
        command.push_str(&format!(" {powershell} -NoExit -EncodedCommand {script}"));
    }
    command
}

/// Returns the PowerShell executable for a tab's shell. The script that the
/// tab runs is PowerShell, so a shell other than PowerShell 7 gets Windows
/// PowerShell.
fn powershell(shell: Option<&str>) -> &'static str {
    if shell.is_some_and(|shell| shell.eq_ignore_ascii_case("pwsh")) {
        "pwsh.exe"
    } else {
        "powershell.exe"
    }
}

/// Returns a value quoted for `wt.exe`. `wt.exe` splits commands at `;`, so a
/// `;` in the value is escaped. A trailing backslash would escape the closing
/// quote, so it is dropped, and a bare drive such as `C:` becomes `C:\.`.
fn quote(value: &str) -> String {
    let mut value = value.trim_end_matches('\\').to_string();
    if value.len() == 2 && value.ends_with(':') {
        value.push_str(r"\.");
    }
    format!("\"{}\"", value.replace(';', r"\;"))
}

/// Returns the PowerShell script that a tab runs: it goes to the folder, then
/// runs the command. Words that aren't plain are quoted.
fn tab_script(cwd: &str, run: &[String]) -> String {
    let words: Vec<String> = run.iter().map(|word| powershell_word(word)).collect();
    format!(
        "Set-Location -LiteralPath '{}'\n& {}",
        cwd.replace('\'', "''"),
        words.join(" ")
    )
}

/// Returns one word of a PowerShell command line: as it is when it holds only
/// letters, digits, `-`, `_` and `.`, and in single quotes otherwise.
fn powershell_word(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
    if plain {
        word.to_string()
    } else {
        format!("'{}'", word.replace('\'', "''"))
    }
}

/// Returns text as UTF-16 bytes, low byte first, which is how
/// `-EncodedCommand` expects a script before Base64.
fn utf16_le(text: &str) -> Vec<u8> {
    text.encode_utf16().flat_map(u16::to_le_bytes).collect()
}

/// Returns `bytes` in Base64, with the standard alphabet and `=` padding.
fn base64(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut text = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let byte = |index: usize| u32::from(chunk.get(index).copied().unwrap_or(0));
        let group = (byte(0) << 16) | (byte(1) << 8) | byte(2);
        for index in 0..4 {
            if index <= chunk.len() {
                text.push(char::from(
                    ALPHABET[((group >> (18 - 6 * index)) & 63) as usize],
                ));
            } else {
                text.push('=');
            }
        }
    }
    text
}

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

    const SESSION: &str = "00000000-0000-4000-8000-000000000002";

    fn tab_env() -> Env {
        Env::from([("WT_SESSION".to_string(), SESSION.to_string())])
    }

    #[test]
    fn a_shell_started_by_the_terminal_is_a_tab() {
        let table = FakeTable::new(&[
            (20, Some(10), "powershell.exe", Some(200)),
            (10, Some(1), "WindowsTerminal.exe", Some(100)),
        ]);
        let found = WindowsTerminal.find(&tab_env(), &lineage(&table, 20));
        assert_eq!(found.map(|process| process.pid), Some(10));
    }

    #[test]
    fn the_terminal_name_is_matched_without_case() {
        let table = FakeTable::new(&[
            (20, Some(10), "pwsh.exe", Some(200)),
            (10, None, "windowsterminal.exe", Some(100)),
        ]);
        assert!(
            WindowsTerminal
                .find(&tab_env(), &lineage(&table, 20))
                .is_some()
        );
    }

    #[test]
    fn a_shell_inside_another_program_is_not_a_tab() {
        let table = FakeTable::new(&[
            (30, Some(20), "pwsh.exe", Some(300)),
            (20, Some(10), "powershell.exe", Some(200)),
            (10, None, "WindowsTerminal.exe", Some(100)),
        ]);
        assert!(
            WindowsTerminal
                .find(&tab_env(), &lineage(&table, 30))
                .is_none()
        );
    }

    #[test]
    fn a_shell_without_the_variable_is_not_a_tab() {
        let table = FakeTable::new(&[
            (20, Some(10), "powershell.exe", Some(200)),
            (10, None, "WindowsTerminal.exe", Some(100)),
        ]);
        assert!(
            WindowsTerminal
                .find(&Env::new(), &lineage(&table, 20))
                .is_none()
        );
    }

    #[test]
    fn the_profile_comes_from_the_environment() {
        let mut env = tab_env();
        env.insert(
            "WT_PROFILE_ID".into(),
            "{00000000-0000-4000-8000-000000000003}".into(),
        );
        assert_eq!(
            WindowsTerminal.profile(&env).as_deref(),
            Some("{00000000-0000-4000-8000-000000000003}")
        );
        assert_eq!(WindowsTerminal.profile(&tab_env()), None);
    }

    const PROFILE: &str = "{00000000-0000-4000-8000-000000000003}";
    const ID: &str = "00000000-0000-4000-8000-000000000001";

    fn tab(cwd: &str, shell: Option<&str>, run: &[&str]) -> TabToOpen {
        TabToOpen {
            title: "mobile-app".into(),
            cwd: cwd.into(),
            profile: Some(PROFILE.into()),
            shell: shell.map(String::from),
            run: run.iter().map(|word| word.to_string()).collect(),
        }
    }

    #[test]
    fn a_plain_tab_opens_with_its_profile_in_its_folder() {
        let plain = tab(r"C:\Users\demo\code\mobile-app", Some("powershell"), &[]);
        assert_eq!(
            wt_arguments(&[plain]),
            format!(
                r#"-w 0 new-tab --title "mobile-app" -p "{PROFILE}" -d "C:\Users\demo\code\mobile-app""#
            )
        );
    }

    #[test]
    fn an_agent_tab_runs_powershell_with_the_encoded_script() {
        let agent = tab(r"C:\code", Some("pwsh"), &["claude", "--resume", ID]);
        let script = base64(&utf16_le(&tab_script(r"C:\code", &agent.run)));
        assert!(wt_arguments(&[agent]).ends_with(&format!(
            r#"-d "C:\code" pwsh.exe -NoExit -EncodedCommand {script}"#
        )));
        assert_eq!(
            tab_script(r"C:\code", &["claude".into(), "--resume".into(), ID.into()]),
            format!("Set-Location -LiteralPath 'C:\\code'\n& claude --resume {ID}")
        );
    }

    #[test]
    fn several_tabs_open_in_one_command() {
        let tabs = [tab(r"C:\a", None, &[]), tab(r"C:\b", None, &[])];
        let arguments = wt_arguments(&tabs);
        assert!(arguments.starts_with("-w 0 new-tab "));
        assert_eq!(arguments.matches(" ; new-tab ").count(), 1);
    }

    #[test]
    fn values_are_quoted_the_way_wt_reads_them() {
        assert_eq!(quote(r"C:\my code\프로젝트"), r#""C:\my code\프로젝트""#);
        assert_eq!(quote(r"C:\odd;name"), r#""C:\odd\;name""#);
        assert_eq!(quote(r"C:\Users\demo\"), r#""C:\Users\demo""#);
        assert_eq!(quote("D:"), r#""D:\.""#);
        assert_eq!(quote(r"D:\"), r#""D:\.""#);
    }

    #[test]
    fn the_script_quotes_folders_and_odd_words() {
        let script = tab_script(
            r"C:\Users\demo\o'brien",
            &["my tool".into(), "--flag".into()],
        );
        assert_eq!(
            script,
            "Set-Location -LiteralPath 'C:\\Users\\demo\\o''brien'\n& 'my tool' --flag"
        );
    }

    #[test]
    fn other_shells_run_the_script_in_windows_powershell() {
        assert_eq!(powershell(Some("pwsh")), "pwsh.exe");
        assert_eq!(powershell(Some("powershell")), "powershell.exe");
        assert_eq!(powershell(Some("cmd")), "powershell.exe");
        assert_eq!(powershell(None), "powershell.exe");
    }

    #[test]
    fn base64_matches_the_standard_test_vectors() {
        for (input, output) in [
            ("", ""),
            ("f", "Zg=="),
            ("fo", "Zm8="),
            ("foo", "Zm9v"),
            ("foob", "Zm9vYg=="),
            ("fooba", "Zm9vYmE="),
            ("foobar", "Zm9vYmFy"),
        ] {
            assert_eq!(base64(input.as_bytes()), output);
        }
    }

    #[test]
    fn the_store_copy_uses_the_wt_command() {
        let store = Path::new(
            r"C:\Program Files\WindowsApps\Microsoft.WindowsTerminal_1.0.0.0_x64__0\WindowsTerminal.exe",
        );
        assert_eq!(wt_exe(Some(store)), PathBuf::from("wt.exe"));
        assert_eq!(wt_exe(None), PathBuf::from("wt.exe"));
    }

    #[test]
    fn a_portable_copy_uses_its_own_wt() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("wt.exe"), "").unwrap();
        let exe = dir.path().join("WindowsTerminal.exe");
        assert_eq!(wt_exe(Some(&exe)), dir.path().join("wt.exe"));
    }
}