the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
fix: probe windows remote hosts before /bin/sh (#5275)
JJ Liebig916fcf8de029
diff --git a/src/remote/attach.rs b/src/remote/attach.rsindex a94debe01..c3122a5a2 100644--- a/src/remote/attach.rs+++ b/src/remote/attach.rs@@ -556,6 +556,11 @@ fn posix_remote_output_command(command: &str) -> String {}fn windows_powershell_script_command(script: &str) -> String {+ let encoded = windows_powershell_encoded_script(script);+ format!("powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand {encoded}")+}++fn windows_powershell_encoded_script(script: &str) -> String {// `$ProgressPreference = 'SilentlyContinue'` stops PowerShell from// serializing progress records (for example module auto-loading's// "Preparing modules for first use.") into the stderr CLIXML stream that@@ -567,8 +572,7 @@ fn windows_powershell_script_command(script: &str) -> String {.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<_>>();- let encoded = base64::engine::general_purpose::STANDARD.encode(utf16);- format!("powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand {encoded}")+ base64::engine::general_purpose::STANDARD.encode(utf16)}#[derive(Debug, Clone, Deserialize)]@@ -1698,6 +1702,18 @@ pub(super) fn discover_remote_api_metadata(}fn detect_remote_platform(ssh: &RemoteSsh) -> io::Result<DetectedRemotePlatform> {+ // Interactive setup forwards SSH stderr to the terminal, so a Windows host+ // whose default shell is PowerShell would print a raw+ // `CommandNotFoundException` for the POSIX `/bin/sh` probe below. Probe for+ // Windows first there so such hosts never receive a `/bin/sh` command.+ // Background bridges capture stderr instead, so they keep the POSIX-first+ // probe to avoid an extra round trip on Unix hosts.+ if !ssh.noninteractive {+ if let Some(platform) = detect_windows_remote_platform(ssh, true)? {+ return Ok(platform);+ }+ }+let output = ssh.sh_output("uname -s\nuname -m\n")?;let mut windows_uname_hint = false;let posix_error = if output.status.success() {@@ -1721,30 +1737,50 @@ fn detect_remote_platform(ssh: &RemoteSsh) -> io::Result<DetectedRemotePlatform>command_failed("remote platform detection failed", &output)};- if !should_try_windows_probe(+ // A POSIX-compatible shell on Windows (MINGW/MSYS/Cygwin) reports a Windows+ // `uname`; retry the direct probe for hosts the first attempt could not+ // confirm so the hint is not lost.+ if should_try_windows_probe(output.status.success(),output.status.code(),windows_uname_hint,+ ssh.noninteractive,) {- return Err(posix_error);+ if let Some(platform) = detect_windows_remote_platform(ssh, !windows_uname_hint)? {+ return Ok(platform);+ }}- let windows_output = match ssh.framed_user_shell_output(&windows_platform_probe_command()) {- Ok(output) if output.status.success() => output,- _ => return Err(posix_error),- };- match parse_windows_platform_probe(&String::from_utf8_lossy(&windows_output.stdout)) {- Ok(Some(platform)) => Ok(platform),- Ok(None) => Err(posix_error),- Err(message) => Err(io::Error::other(message)),+ Err(posix_error)+}++fn detect_windows_remote_platform(+ ssh: &RemoteSsh,+ native_shell_only: bool,+) -> io::Result<Option<DetectedRemotePlatform>> {+ // Capture a Unix login shell's expected "command not found" in stdout;+ // an ordinary failed probe is discarded without printing that diagnostic.+ let command = format!("{} 2>&1", windows_platform_probe_command(native_shell_only));+ // Propagate cancellation, spawn failures, and SSH transport failures (exit+ // 255) rather than retrying them against the POSIX probe, which would repeat+ // an authentication failure. An ordinary command failure means "not Windows".+ let output = ssh.framed_user_shell_output(&command)?;+ if output.status.code() == Some(255) {+ return Err(command_failed("remote platform detection failed", &output));}+ if !output.status.success() {+ return Ok(None);+ }+ parse_windows_platform_probe(&String::from_utf8_lossy(&output.stdout)).map_err(io::Error::other)}fn should_try_windows_probe(success: bool,exit_code: Option<i32>,windows_uname_hint: bool,+ noninteractive: bool,) -> bool {- (success && windows_uname_hint) || (!success && exit_code.is_some_and(|code| code != 255))+ (success && windows_uname_hint)+ || (noninteractive && !success && exit_code.is_some_and(|code| code != 255))}fn looks_like_windows_uname(os: &str) -> bool {@@ -1754,9 +1790,17 @@ fn looks_like_windows_uname(os: &str) -> bool {.any(|prefix| os.starts_with(prefix))}-fn windows_platform_probe_command() -> String {- windows_powershell_script_command(- "$arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }; [Console]::Out.WriteLine('herdr-windows:' + $arch); exit 0",+fn windows_platform_probe_command(native_shell_only: bool) -> String {+ let script = "$arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }; [Console]::Out.WriteLine('herdr-windows:' + $arch); exit 0";+ if !native_shell_only {+ return windows_powershell_script_command(script);+ }+ // Expand in the SSH login shell, before launching Windows PowerShell:+ // PowerShell yields Windows_NT|%OS%, cmd yields $env:OS|Windows_NT,+ // and POSIX/fish retain :OS|%OS%, including WSL on Windows-mounted drives.+ let encoded = windows_powershell_encoded_script(script);+ format!(+ "powershell.exe -NoLogo -NoProfile -NonInteractive -Command \"if ('$env:OS|%OS%' -ne 'Windows_NT|%OS%' -and '$env:OS|%OS%' -ne ([string][char]36 + 'env:OS|Windows_NT')) {{ exit 1 }}; & ([ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('{encoded}'))))\"")}@@ -4803,17 +4847,19 @@ mod tests {#[test]fn windows_probe_preserves_transport_and_unsupported_unix_failures() {let cases = [- (true, Some(0), false, false),- (true, Some(0), true, true),- (false, Some(255), false, false),- (false, None, false, false),- (false, Some(1), false, true),+ (true, Some(0), false, false, false),+ (true, Some(0), true, false, true),+ (false, Some(255), false, false, false),+ (false, Some(255), false, true, false),+ (false, None, false, true, false),+ (false, Some(1), false, false, false),+ (false, Some(1), false, true, true),];- for (success, exit_code, windows_uname_hint, expected) in cases {+ for (success, exit_code, windows_uname_hint, noninteractive, expected) in cases {assert_eq!(- should_try_windows_probe(success, exit_code, windows_uname_hint),+ should_try_windows_probe(success, exit_code, windows_uname_hint, noninteractive),expected,- "success={success}, exit_code={exit_code:?}, windows_uname_hint={windows_uname_hint}"+ "success={success}, exit_code={exit_code:?}, windows_uname_hint={windows_uname_hint}, noninteractive={noninteractive}");}@@ -4958,7 +5004,7 @@ mod tests {let commands = [("platform probe",- windows_platform_probe_command(),+ windows_platform_probe_command(false),"$arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }; [Console]::Out.WriteLine('herdr-windows:' + $arch); exit 0",),(@@ -5015,6 +5061,59 @@ mod tests {}}+ #[cfg(windows)]+ #[test]+ fn windows_platform_probe_distinguishes_native_and_posix_login_shells() {+ use std::os::windows::process::CommandExt;++ let probe = format!("{} 2>&1", windows_platform_probe_command(true));+ let mut powershell = Command::new("powershell.exe");+ powershell.args([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ &probe,+ ]);+ let mut cmd = Command::new("cmd.exe");+ cmd.args(["/d", "/s", "/c"]).raw_arg(format!("\"{probe}\""));+ for mut command in [powershell, cmd] {+ crate::platform::configure_background_command(&mut command);+ let output = normalize_remote_output(command.output().unwrap()).unwrap();+ assert!(output.status.success(), "{output:?}");+ assert!(output.stderr.is_empty(), "{output:?}");+ assert!(+ parse_windows_platform_probe(&String::from_utf8_lossy(&output.stdout))+ .unwrap()+ .is_some(),+ "{output:?}"+ );+ }++ // Git's real POSIX shell launches the same Windows PowerShell executable+ // from a Windows directory, reproducing WSL's mounted-drive ambiguity.+ let git = Command::new("git").arg("--exec-path").output().unwrap();+ assert!(git.status.success(), "{git:?}");+ let exec_path = String::from_utf8(git.stdout).unwrap();+ let shell = Path::new(exec_path.trim())+ .ancestors()+ .nth(3)+ .unwrap()+ .join("usr/bin/sh.exe");+ for env in ["", "Windows_NT", "$env"] {+ let mut command = Command::new(&shell);+ command.args(["-c", &probe]).env("env", env);+ crate::platform::configure_background_command(&mut command);+ let output = command.output().unwrap();+ assert_eq!(output.status.code(), Some(1), "{env}: {output:?}");+ assert!(output.stderr.is_empty(), "{env}: {output:?}");+ assert!(+ !String::from_utf8_lossy(&output.stdout).contains("herdr-windows:"),+ "{env}: {output:?}"+ );+ }+ }+#[test]fn windows_remote_commands_suppress_powershell_progress_records() {// PowerShell serializes progress records (such as module auto-loading'sdiff --git a/tests/machine_setup.rs b/tests/machine_setup.rsindex 649ba7c0a..b4cbe86a7 100644--- a/tests/machine_setup.rs+++ b/tests/machine_setup.rs@@ -15,11 +15,21 @@ for arg dolast=$argif [ "$arg" = 'StrictHostKeyChecking=yes' ]; then strict_host_key_check=yes; fidone+case "$*" in+ *powershell.exe*) echo windows >>"$FAKE_ROOT/command-order" ;;+ *'/bin/sh -s'*) echo posix-probe >>"$FAKE_ROOT/command-order" ;;+esacif [ "$FAKE_STRICT_HOST_KEY_FAILURE" = yes ] && [ "$strict_host_key_check" = yes ]; thenecho 'No RSA host key is known for fake-host and you have requested strict checking.' >&2echo 'Host key verification failed.' >&2exit 255fi+case "$*" in+ *powershell.exe*)+ if [ "$FAKE_WINDOWS_TRANSPORT_FAILURE" = yes ]; then echo 'ssh: connect to host fake-host port 22: Connection refused' >&2; exit 255; fi+ if [ "$FAKE_WINDOWS" = yes ]; then printf '\n%s\n%s\n' 'herdr-remote-output-ready:1' 'herdr-windows:AMD64'; exit 0; fi+ exit 1 ;;+esacif [ "$last" = 'command -v herdr' ]; thenif [ "$FAKE_INSTALLED" != missing ]; then echo /home/remote/.local/bin/herdr; fiexit 0@@ -74,6 +84,7 @@ struct SetupResult {prompts: usize,success: bool,probes: String,+ command_order: String,start_command: String,}@@ -83,6 +94,8 @@ struct SetupOptions<'a> {selection: &'a [u8],explicit_session: Option<&'a str>,noninteractive: bool,+ windows: bool,+ windows_transport_failure: bool,}fn setup(installed: &str, answer: &str, handoff: bool) -> SetupResult {@@ -173,6 +186,15 @@ fn setup_options("FAKE_STRICT_HOST_KEY_FAILURE",if strict_host_key_failure { "yes" } else { "no" },);+ command.env("FAKE_WINDOWS", if options.windows { "yes" } else { "no" });+ command.env(+ "FAKE_WINDOWS_TRANSPORT_FAILURE",+ if options.windows_transport_failure {+ "yes"+ } else {+ "no"+ },+ );command.env("FAKE_CLIENT_STATUS",String::from_utf8(status.stdout).unwrap(),@@ -252,6 +274,7 @@ fn setup_options(reading.join().unwrap();let actions = fs::read_to_string(root.join("actions")).unwrap_or_default();let probes = fs::read_to_string(root.join("probes")).unwrap_or_default();+ let command_order = fs::read_to_string(root.join("command-order")).unwrap_or_default();let start_command = fs::read_to_string(root.join("start-command")).unwrap_or_default();// Every scenario either cancels or reaches the intentionally failed startup.let saved = root@@ -271,6 +294,7 @@ fn setup_options(prompts,success: status.success(),probes,+ command_order,start_command,}}@@ -341,6 +365,53 @@ fn machine_add_fresh_host_offers_installation_and_cancellation_saves_nothing() {assert!(result.actions.is_empty(), "{}", result.output);}+#[test]+fn machine_setup_accepts_a_native_windows_probe_without_a_posix_probe() {+ // A successful Windows probe must short-circuit so a native Windows host+ // never falls through to the POSIX `/bin/sh` probe.+ let result = setup_options(+ "new",+ "n\n",+ false,+ false,+ SetupOptions {+ windows: true,+ ..Default::default()+ },+ );+ let order: Vec<&str> = result.command_order.lines().collect();+ assert_eq!(order.first().copied(), Some("windows"), "{}", result.output);+ assert!(!order.contains(&"posix-probe"), "{}", result.output);+ assert!(+ result.output.contains("installation cancelled"),+ "{}",+ result.output+ );+}++#[test]+fn machine_setup_windows_transport_failure_is_not_retried() {+ let result = setup_options(+ "new",+ "",+ false,+ false,+ SetupOptions {+ windows_transport_failure: true,+ ..Default::default()+ },+ );+ assert!(!result.success, "{}", result.output);+ assert_eq!(result.prompts, 0, "{}", result.output);+ assert!(result.actions.is_empty(), "{}", result.output);+ assert_eq!(result.command_order, "windows\n", "{}", result.output);+ assert!(+ result.output.contains("Connection refused"),+ "{}",+ result.output+ );+}+#[test]fn machine_add_discovers_sessions_once_and_prepares_the_selected_session() {for (sessions, selection, expected) in [diff --git a/tests/remote_attach.rs b/tests/remote_attach.rsindex 2af61c772..0487beaef 100644--- a/tests/remote_attach.rs+++ b/tests/remote_attach.rs@@ -75,6 +75,9 @@ fn check_authentication_output(framed_shell: bool) {&ssh_path,format!(r#"#!/bin/sh+case "$*" in+ *powershell.exe*) exit 1 ;;+esacauthenticate() {{: > "$FAKE_SSH_STARTED"printf '/bin/sh: expected probe noise\n%s\n%s' '{CHECK_NOTICE}' '{CHECK_URL}' >&2