use std::path::{Path, PathBuf};
use anyhow::Result;
use super::{Env, TabToOpen, TerminalAdapter};
use crate::engine::rules::TerminalShape;
use crate::procs::ProcInfo;
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> {
env.get("WT_SESSION")?;
let is_terminal =
|process: &ProcInfo| process.name.eq_ignore_ascii_case("WindowsTerminal.exe");
match lineage.get(1) {
Some(parent) if is_terminal(parent) => Some(parent.clone()),
Some(parent) if is_git_bash_launcher(parent) => lineage
.get(2)
.filter(|process| is_terminal(process))
.cloned(),
_ => None,
}
}
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))
}
}
#[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(())
}
#[cfg(not(windows))]
fn launch(_wt: &Path, _arguments: &str) -> Result<()> {
anyhow::bail!("Windows Terminal runs only on Windows")
}
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"))
}
fn is_git_bash_launcher(process: &ProcInfo) -> bool {
let path = process
.exe
.as_ref()
.map(|exe| exe.to_string_lossy().into_owned())
.or_else(|| process.arguments.first().cloned())
.unwrap_or_default()
.to_ascii_lowercase()
.replace('/', "\\");
path.ends_with(r"\bin\bash.exe") && !path.ends_with(r"\usr\bin\bash.exe")
}
fn wt_arguments(tabs: &[TabToOpen]) -> String {
let commands: Vec<String> = tabs.iter().map(new_tab).collect();
format!("-w 0 {}", commands.join(" ; "))
}
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 let Some(rcfile) = &tab.rcfile {
let bash = bash(tab.shell_exe.as_deref());
command.push_str(&format!(
" {} --rcfile {} -i",
quote(&bash),
quote(&rcfile.replace('\\', "/"))
));
} else 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
}
fn bash(shell_exe: Option<&str>) -> String {
let Some(exe) = shell_exe else {
return "bash.exe".into();
};
let lower = exe.to_ascii_lowercase();
match lower.strip_suffix(r"\usr\bin\bash.exe") {
Some(git) => format!(r"{}\bin\bash.exe", &exe[..git.len()]),
None => exe.to_string(),
}
}
fn powershell(shell: Option<&str>) -> &'static str {
if shell.is_some_and(|shell| shell.eq_ignore_ascii_case("pwsh")) {
"pwsh.exe"
} else {
"powershell.exe"
}
}
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"\;"))
}
fn tab_script(cwd: &str, run: &[String]) -> String {
crate::shells::powershell_run_lines(cwd, run)
}
fn utf16_le(text: &str) -> Vec<u8> {
text.encode_utf16().flat_map(u16::to_le_bytes).collect()
}
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 git_bash_started_through_its_launcher_is_a_tab() {
let table = FakeTable::new(&[
(40, Some(30), "bash.exe", Some(400)),
(30, Some(20), "bash.exe", Some(300)),
(20, Some(10), "bash.exe", Some(200)),
(10, None, "WindowsTerminal.exe", Some(100)),
])
.with_exe(40, r"C:\Program Files\Git\usr\bin\bash.exe")
.with_exe(30, r"C:\Program Files\Git\usr\bin\bash.exe")
.with_exe(20, r"C:\Program Files\Git\bin\bash.exe");
let found = WindowsTerminal.find(&tab_env(), &lineage(&table, 30));
assert_eq!(found.map(|process| process.pid), Some(10));
assert!(
WindowsTerminal
.find(&tab_env(), &lineage(&table, 40))
.is_none()
);
}
#[test]
fn a_bash_that_the_terminal_didn_t_start_through_the_launcher_is_not_a_tab() {
let table = FakeTable::new(&[
(30, Some(20), "bash.exe", Some(300)),
(20, Some(10), "bash.exe", Some(200)),
(10, None, "WindowsTerminal.exe", Some(100)),
])
.with_exe(30, r"C:\Program Files\Git\usr\bin\bash.exe")
.with_exe(20, r"C:\Program Files\Git\usr\bin\bash.exe");
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(),
..TabToOpen::default()
}
}
#[test]
fn a_bash_agent_tab_starts_git_bash_with_kaeru_s_file() {
let mut agent = tab(r"C:\code", Some("bash"), &["claude"]);
agent.shell_exe = Some(r"C:\Program Files\Git\usr\bin\bash.exe".into());
agent.rcfile = Some(r"C:\Users\demo\kaeru\run\kaeru-run-1.sh".into());
assert!(new_tab(&agent).ends_with(
r#" -d "C:\code" "C:\Program Files\Git\bin\bash.exe" --rcfile "C:/Users/demo/kaeru/run/kaeru-run-1.sh" -i"#
));
}
#[test]
fn bash_is_git_s_launcher_for_git_bash_and_itself_otherwise() {
assert_eq!(
bash(Some(r"C:\Program Files\Git\usr\bin\bash.exe")),
r"C:\Program Files\Git\bin\bash.exe"
);
assert_eq!(
bash(Some(r"C:\msys64\bin\bash.exe")),
r"C:\msys64\bin\bash.exe"
);
assert_eq!(bash(None), "bash.exe");
}
#[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"));
}
}