kaeru 0.1.8

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! mintty, the terminal of Git Bash, MSYS2 and Cygwin. Each window is its own
//! `mintty.exe` process with one shell. mintty starts the shell through an
//! MSYS fork, so Windows doesn't record mintty as the shell's parent, and the
//! bash snippet tells `kaeru shell start` with `--parent`.

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 mintty.
pub struct Mintty;

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

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

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

    fn find(&self, _env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
        // The window's shell is mintty's child; a shell inside another
        // program in the window isn't a window of its own.
        lineage
            .get(1)
            .filter(|parent| {
                parent.name.eq_ignore_ascii_case("mintty.exe")
                    || parent.name.eq_ignore_ascii_case("mintty")
            })
            .cloned()
    }

    fn gives_a_console(&self) -> bool {
        false
    }

    fn reopen(&self, exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()> {
        let mintty = exe.map_or_else(|| PathBuf::from("mintty.exe"), Path::to_path_buf);
        let git_bash = git_bash_of(&mintty).filter(|git_bash| git_bash.is_file());
        for tab in tabs {
            if !tab.run.is_empty() && tab.rcfile.is_none() {
                anyhow::bail!("mintty reopens an agent session only in bash");
            }
            launch(
                &mintty,
                &mintty_arguments(git_bash.as_deref(), tab),
                git_bash.is_some(),
            )?;
        }
        Ok(())
    }
}

/// Returns where Git Bash's own launcher, `git-bash.exe`, is for a mintty of
/// Git for Windows, which is `usr\bin\mintty.exe` in Git's folder. It may not
/// exist, as for MSYS2's mintty.
fn git_bash_of(mintty: &Path) -> Option<PathBuf> {
    let bin = mintty.parent()?;
    let usr = bin.parent()?;
    let name_is = |path: &Path, name: &str| {
        path.file_name()
            .is_some_and(|file| file.eq_ignore_ascii_case(name))
    };
    (name_is(bin, "bin") && name_is(usr, "usr"))
        .then(|| usr.parent())?
        .map(|git| git.join("git-bash.exe"))
}

/// Returns the arguments for `mintty.exe` that open one tab as a window: in
/// its folder, with the user's login shell, or with bash and the file that
/// kaeru wrote for the tab's agent session. For Git Bash, the window gets
/// Git Bash's icon and taskbar group, as when Git Bash's own shortcut opens
/// it.
fn mintty_arguments(git_bash: Option<&Path>, tab: &TabToOpen) -> Vec<String> {
    let mut arguments = Vec::new();
    if let Some(git_bash) = git_bash {
        let git_bash = git_bash.display().to_string();
        arguments.extend([
            "-i".into(),
            git_bash.clone(),
            "-o".into(),
            "AppID=GitForWindows.Bash".into(),
            "-o".into(),
            "AppName=Git Bash".into(),
            "-o".into(),
            format!("AppLaunchCmd={git_bash}"),
        ]);
    }
    arguments.extend(["--dir".into(), tab.cwd.clone()]);
    match &tab.rcfile {
        Some(rcfile) => arguments.extend([
            "-e".into(),
            "/usr/bin/bash".into(),
            "--rcfile".into(),
            rcfile.replace('\\', "/"),
            "-i".into(),
        ]),
        None => arguments.push("-".into()),
    }
    arguments
}

/// Starts mintty with these arguments. Git Bash's own launchers set
/// `MSYSTEM`, which Git's login files need to put Git's programs on the
/// PATH, so for Git Bash, kaeru sets it the same way when it isn't set.
#[cfg(windows)]
fn launch(mintty: &Path, arguments: &[String], git_bash: bool) -> Result<()> {
    use anyhow::Context;

    let mut command = std::process::Command::new(mintty);
    command.args(arguments);
    if git_bash && std::env::var_os("MSYSTEM").is_none() {
        command.env("MSYSTEM", "MINGW64");
    }
    command
        .spawn()
        .with_context(|| format!("can't start {}", mintty.display()))?;
    Ok(())
}

/// Fails, because kaeru supports mintty only on Windows.
#[cfg(not(windows))]
fn launch(_mintty: &Path, _arguments: &[String], _git_bash: bool) -> Result<()> {
    anyhow::bail!("kaeru supports mintty only on Windows")
}

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

    fn tab(cwd: &str) -> TabToOpen {
        TabToOpen {
            title: "api-server".into(),
            cwd: cwd.into(),
            profile: None,
            shell: Some("bash".into()),
            ..TabToOpen::default()
        }
    }

    #[test]
    fn a_shell_whose_parent_is_mintty_is_a_window() {
        // The bash snippet passed mintty as the shell's parent.
        let table = FakeTable::new(&[
            (20, Some(10), "bash.exe", Some(200)),
            (10, None, "mintty.exe", Some(100)),
        ]);
        let found = Mintty.find(&Env::new(), &lineage(&table, 20));
        assert_eq!(found.map(|process| process.pid), Some(10));
    }

    #[test]
    fn programs_in_mintty_get_no_console() {
        assert!(!super::super::gives_a_console("mintty"));
        assert!(super::super::gives_a_console("windows-terminal"));
        assert!(super::super::gives_a_console("some-future-terminal"));
    }

    #[test]
    fn a_shell_inside_a_window_s_shell_is_not_a_window() {
        let table = FakeTable::new(&[
            (30, Some(20), "bash.exe", Some(300)),
            (20, Some(10), "bash.exe", Some(200)),
            (10, None, "mintty.exe", Some(100)),
        ]);
        assert!(Mintty.find(&Env::new(), &lineage(&table, 30)).is_none());
    }

    // Windows paths have parent folders only on Windows.
    #[cfg(windows)]
    #[test]
    fn git_bash_is_found_next_to_its_mintty() {
        assert_eq!(
            git_bash_of(Path::new(r"C:\Program Files\Git\usr\bin\mintty.exe")),
            Some(PathBuf::from(r"C:\Program Files\Git").join("git-bash.exe"))
        );
        assert_eq!(git_bash_of(Path::new(r"C:\tools\mintty.exe")), None);
    }

    #[test]
    fn a_window_opens_in_its_folder_with_the_login_shell() {
        let folder = r"C:\Users\demo\code\모바일 앱";
        assert_eq!(mintty_arguments(None, &tab(folder)), ["--dir", folder, "-"]);
    }

    #[test]
    fn an_agent_window_starts_bash_with_kaeru_s_file() {
        let mut agent = tab(r"C:\code");
        agent.run = vec!["claude".into()];
        agent.rcfile = Some(r"C:\Users\demo\kaeru\run\kaeru-run-1.sh".into());
        assert_eq!(
            mintty_arguments(None, &agent),
            [
                "--dir",
                r"C:\code",
                "-e",
                "/usr/bin/bash",
                "--rcfile",
                "C:/Users/demo/kaeru/run/kaeru-run-1.sh",
                "-i"
            ]
        );
    }

    #[test]
    fn a_git_bash_window_looks_like_git_bash() {
        let git_bash = Path::new(r"C:\Program Files\Git\git-bash.exe");
        let arguments = mintty_arguments(Some(git_bash), &tab(r"C:\code"));
        assert_eq!(arguments[..2], ["-i", r"C:\Program Files\Git\git-bash.exe"]);
        assert!(arguments.contains(&"AppID=GitForWindows.Bash".to_string()));
        assert!(arguments.ends_with(&["--dir".into(), r"C:\code".into(), "-".into()]));
    }
}