Skip to content

Commit f3981db

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
fix(discovery): spawn PowerShell install commands natively on Windows (#2750)
## Problem On Windows, `install_shell_command` wraps every install command in Git Bash `-l -c`, including the Windows-specific `powershell.exe … irm https://chatgpt.com/codex/install.ps1 | iex` command. A Git Bash login shell prepends its POSIX dirs (`C:\Program Files\Git\usr\bin`) to PATH, so when Codex's `install.ps1` shells out to bare `tar -xzf C:\…`, it resolves Git's GNU tar (`/usr/bin/tar`) instead of Windows bundled bsdtar. GNU tar parses `C:` as a remote host: ``` tar (child): Cannot connect to C: resolve failed gzip: stdin: unexpected end of file /usr/bin/tar: Child returned status 128 /usr/bin/tar: Error is not recoverable: exiting now Downloaded Codex package archive did not contain the expected package layout. ``` Claude's installer doesn't hit the same failure because it doesn't shell out to `tar`. ## Solution On Windows, detect `powershell.exe` install commands and spawn them natively (`Command::new("powershell.exe")`) instead of routing them through Git Bash. The discriminator is a case-insensitive prefix check on the first whitespace-delimited token — minimal and precise. The native spawn preserves everything `install_shell_command` provides that applies: - `NPM_CONFIG_*` / `COREPACK` env strip + managed npm prefix env - PATH composed from managed Buzz dirs + inherited process PATH (no POSIX login-shell dirs) - `CREATE_NO_WINDOW` so no console flash - stdin null, piped-drain in `run_install_command` - The retry/backoff/annotate logic is fully shared The `-Command` body is split correctly at the boundary (case-insensitive) and passed as a single argument to preserve pipes and spaces inside the installer script call. Non-PowerShell commands (e.g. `npm install -g …` adapter steps) continue through the existing Git Bash path unchanged. ## Tests 6 unit tests: 1. `is_powershell_command` detection (positive + negative) 2. Routing: PowerShell → native spawn on Windows, non-PowerShell → Git Bash 3. Unix: non-Windows path returns the shell command unchanged (compile-time cfg) 4. `-Command` body preservation (no bash args in native spawn; body is single arg) Full `just desktop-tauri-test` suite: 1627/1627 passing. Windows CI will validate end-to-end. --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent 3bd3a01 commit f3981db

2 files changed

Lines changed: 316 additions & 23 deletions

File tree

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,11 @@ const overrides = new Map([
494494
// +53: pass 2 — three cfg(windows) install shell tests (resolve succeeds with
495495
// Git, error hint content, install_shell_command succeeds).
496496
// +8: install_shell_from pure seam extracted for deterministic testing.
497-
["src-tauri/src/commands/agent_discovery.rs", 1523],
497+
// +287: is_powershell_command + install_powershell_command + build_install_command
498+
// route PowerShell CLI installs natively on Windows (bypasses Git Bash PATH
499+
// poisoning that resolved GNU tar instead of bsdtar → Codex install failure).
500+
// Includes unit tests for detection, routing, and -Command body preservation.
501+
["src-tauri/src/commands/agent_discovery.rs", 1810],
498502
// draft-persistence predicate: submit-time `loadDraft` check + inline comment
499503
// + deps-array entry in submitMessage closes the never-persisted-boundary
500504
// defect (Thufir Pass-3 finding). Load-bearing correctness fix; queued to

‎desktop/src-tauri/src/commands/agent_discovery.rs‎

Lines changed: 311 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -552,21 +552,8 @@ fn install_shell_command(command: &str) -> Result<std::process::Command, String>
552552
let mut cmd = std::process::Command::new(&shell);
553553
cmd.args(["-l", "-c", command]);
554554

555-
// Strip hermit env vars so npm/node use the user's normal registry rather
556-
// than the project-local hermit-managed paths, then give npm defaults for
557-
// Buzz-owned app data. Adapter install commands also pass --prefix
558-
// explicitly; these env vars keep subprocesses/cache/corepack aligned.
559-
cmd.env_remove("NPM_CONFIG_PREFIX");
560-
cmd.env_remove("NPM_CONFIG_CACHE");
561-
cmd.env_remove("COREPACK_HOME");
562-
563-
if let Some(prefix) = crate::managed_agents::buzz_managed_npm_prefix() {
564-
cmd.env("NPM_CONFIG_PREFIX", &prefix);
565-
cmd.env("npm_config_prefix", &prefix);
566-
cmd.env("COREPACK_HOME", prefix.join("corepack"));
567-
cmd.env("NPM_CONFIG_CACHE", prefix.join("cache"));
568-
cmd.env("npm_config_cache", prefix.join("cache"));
569-
}
555+
// Strip hermit vars and set managed npm paths (see apply_npm_env).
556+
apply_npm_env(&mut cmd);
570557

571558
// Compose the PATH for the install shell using the same kernel as the
572559
// runtime/probe path so the two can never drift. managed entries first
@@ -615,12 +602,7 @@ fn install_shell_command(command: &str) -> Result<std::process::Command, String>
615602
}
616603

617604
// Suppress the console window on Windows.
618-
#[cfg(windows)]
619-
{
620-
use std::os::windows::process::CommandExt;
621-
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
622-
cmd.creation_flags(CREATE_NO_WINDOW);
623-
}
605+
apply_no_window(&mut cmd);
624606

625607
Ok(cmd)
626608
}
@@ -721,8 +703,161 @@ fn annotate_retry_attempts(mut result: InstallStepResult, attempts: u32) -> Inst
721703
result
722704
}
723705

706+
/// Returns `true` when `command` is a Windows-native PowerShell invocation
707+
/// (i.e. begins with `powershell.exe`). These commands must NOT be routed
708+
/// through Git Bash: the Bash login shell prepends POSIX dirs to PATH, so
709+
/// bare `tar` inside the PowerShell script resolves to GNU tar
710+
/// (`/usr/bin/tar`) instead of Windows bsdtar. GNU tar parses the drive
711+
/// letter in `C:\…` as a remote host and fails with "Cannot connect to C:
712+
/// resolve failed", which is the exact failure Will observed in the Codex
713+
/// PowerShell installer. Non-PowerShell commands (e.g. `npm install -g …`
714+
/// adapter steps) are unaffected.
715+
///
716+
/// The check is case-insensitive because Windows file-system conventions do
717+
/// not mandate casing, and the install command constants could change.
718+
#[cfg(windows)]
719+
fn is_powershell_command(command: &str) -> bool {
720+
command
721+
.split_ascii_whitespace()
722+
.next()
723+
.is_some_and(|tok| tok.eq_ignore_ascii_case("powershell.exe"))
724+
}
725+
726+
/// Apply the shared npm env cleanup and managed-prefix setup to an install child.
727+
/// Strips hermit-managed vars and establishes the Buzz-managed npm prefix so adapters
728+
/// installed via either path (shell or native PowerShell) land in the same location.
729+
fn apply_npm_env(cmd: &mut std::process::Command) {
730+
cmd.env_remove("NPM_CONFIG_PREFIX");
731+
cmd.env_remove("NPM_CONFIG_CACHE");
732+
cmd.env_remove("COREPACK_HOME");
733+
734+
if let Some(prefix) = crate::managed_agents::buzz_managed_npm_prefix() {
735+
cmd.env("NPM_CONFIG_PREFIX", &prefix);
736+
cmd.env("npm_config_prefix", &prefix);
737+
cmd.env("COREPACK_HOME", prefix.join("corepack"));
738+
cmd.env("NPM_CONFIG_CACHE", prefix.join("cache"));
739+
cmd.env("npm_config_cache", prefix.join("cache"));
740+
}
741+
}
742+
743+
/// Suppress the console window for an install child on Windows (no-op elsewhere).
744+
fn apply_no_window(_cmd: &mut std::process::Command) {
745+
#[cfg(windows)]
746+
{
747+
use std::os::windows::process::CommandExt;
748+
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
749+
_cmd.creation_flags(CREATE_NO_WINDOW);
750+
}
751+
}
752+
753+
/// Build a native `powershell.exe` [`Command`][std::process::Command] for the given command
754+
/// string, bypassing Git Bash so POSIX PATH entries never leak into the child.
755+
///
756+
/// Finds the first `-Command` token (case-insensitive, token-boundary match), passes preceding
757+
/// tokens as individual flags, and passes the rest as a single body arg. One outer double-quote
758+
/// pair is stripped from the body — the catalog strings (`discovery.rs:107`, `:138`) wrap it for
759+
/// Bash serialization; stripping here delivers the bare pipeline to PowerShell. Tokens with no
760+
/// `-Command` are forwarded individually. Only called from [`build_install_command`] on Windows.
761+
#[cfg(windows)]
762+
fn install_powershell_command(command: &str) -> std::process::Command {
763+
// Strip the leading `powershell.exe` token.
764+
let after_exe = command
765+
.split_once(|c: char| c.is_ascii_whitespace())
766+
.map(|(_, rest)| rest.trim())
767+
.unwrap_or("");
768+
769+
let mut cmd = std::process::Command::new("powershell.exe");
770+
771+
// Walk tokens to find -Command on a token boundary (not as a substring of
772+
// a preceding argument). The comparison is case-insensitive because
773+
// PowerShell itself is case-insensitive for parameters.
774+
let mut rest = after_exe;
775+
let mut found_command_flag = false;
776+
loop {
777+
let trimmed = rest.trim_start();
778+
if trimmed.is_empty() {
779+
break;
780+
}
781+
// Find the end of the current token.
782+
let tok_end = trimmed
783+
.find(|c: char| c.is_ascii_whitespace())
784+
.unwrap_or(trimmed.len());
785+
let tok = &trimmed[..tok_end];
786+
if tok.eq_ignore_ascii_case("-command") {
787+
// Everything after this token (trimmed) is the body.
788+
let body_raw = trimmed[tok_end..].trim();
789+
// Strip one matching outer double-quote pair inserted by the
790+
// Bash-layer catalog serialization. PowerShell does not need them.
791+
let body =
792+
if body_raw.starts_with('"') && body_raw.ends_with('"') && body_raw.len() >= 2 {
793+
&body_raw[1..body_raw.len() - 1]
794+
} else {
795+
body_raw
796+
};
797+
cmd.arg("-Command");
798+
if !body.is_empty() {
799+
cmd.arg(body);
800+
}
801+
found_command_flag = true;
802+
break;
803+
}
804+
cmd.arg(tok);
805+
rest = &trimmed[tok_end..];
806+
}
807+
808+
if !found_command_flag {
809+
// No -Command boundary — forward remaining tokens individually.
810+
for arg in rest.split_ascii_whitespace() {
811+
cmd.arg(arg);
812+
}
813+
}
814+
815+
apply_npm_env(&mut cmd);
816+
817+
// Compose PATH: managed Buzz dirs first, then inherited process PATH.
818+
// No login-shell path: login_shell_path() always returns None on Windows,
819+
// and we deliberately skip it here to avoid POSIX-shaped entries.
820+
let managed: Vec<std::path::PathBuf> = [
821+
crate::managed_agents::buzz_managed_node_bin_dir(),
822+
crate::managed_agents::buzz_managed_npm_bin_dir(),
823+
]
824+
.into_iter()
825+
.flatten()
826+
.collect();
827+
let inherited: Vec<std::path::PathBuf> = std::env::var_os("PATH")
828+
.map(|p| std::env::split_paths(&p).collect())
829+
.unwrap_or_default();
830+
// No login path → should_use_inherited returns true so inherited appended.
831+
let path_parts = crate::managed_agents::compose_path_entries(managed, vec![], inherited, true);
832+
if !path_parts.is_empty() {
833+
if let Ok(path) = std::env::join_paths(path_parts) {
834+
cmd.env("PATH", path);
835+
}
836+
}
837+
838+
apply_no_window(&mut cmd);
839+
cmd
840+
}
841+
842+
/// Select the right [`Command`][std::process::Command] builder for `command`.
843+
///
844+
/// On Windows, PowerShell-prefixed commands are spawned natively (via
845+
/// [`install_powershell_command`]) to avoid the Git Bash PATH poisoning that
846+
/// causes GNU `tar` to be resolved instead of Windows bsdtar. All other
847+
/// commands — including `npm install -g …` adapter steps — keep the existing
848+
/// Git Bash path via [`install_shell_command`].
849+
///
850+
/// On non-Windows this is always `install_shell_command`.
851+
fn build_install_command(command: &str) -> Result<std::process::Command, String> {
852+
#[cfg(windows)]
853+
if is_powershell_command(command) {
854+
return Ok(install_powershell_command(command));
855+
}
856+
install_shell_command(command)
857+
}
858+
724859
fn run_install_command(step: &str, command: &str) -> InstallStepResult {
725-
let mut cmd = match install_shell_command(command) {
860+
let mut cmd = match build_install_command(command) {
726861
Ok(cmd) => cmd,
727862
Err(hint) => {
728863
return InstallStepResult {
@@ -1386,6 +1521,160 @@ mod tests {
13861521
);
13871522
}
13881523

1524+
// ── PowerShell routing ────────────────────────────────────────────────────
1525+
1526+
/// Commands beginning with `powershell.exe` (any casing) must be identified
1527+
/// as PowerShell commands; all others must not.
1528+
#[cfg(windows)]
1529+
#[test]
1530+
fn test_is_powershell_command_detects_powershell_commands() {
1531+
assert!(
1532+
super::is_powershell_command(
1533+
r#"powershell.exe -NoProfile -NonInteractive -Command "irm https://chatgpt.com/codex/install.ps1 | iex""#
1534+
),
1535+
"canonical codex install command must be detected as PowerShell"
1536+
);
1537+
assert!(
1538+
super::is_powershell_command("POWERSHELL.EXE -Command foo"),
1539+
"is_powershell_command must be case-insensitive"
1540+
);
1541+
assert!(
1542+
!super::is_powershell_command("npm install -g @agentclientprotocol/claude-agent-acp"),
1543+
"npm commands must NOT be detected as PowerShell"
1544+
);
1545+
assert!(
1546+
!super::is_powershell_command(r"curl -fsSL https://example.com | bash"),
1547+
"bash pipe commands must NOT be detected as PowerShell"
1548+
);
1549+
assert!(
1550+
!super::is_powershell_command(""),
1551+
"empty string must not be detected as PowerShell"
1552+
);
1553+
}
1554+
1555+
/// On Windows, `build_install_command` must return a `Command` whose
1556+
/// program is `powershell.exe` (not `bash.exe`) for PowerShell commands.
1557+
#[cfg(windows)]
1558+
#[test]
1559+
fn test_build_install_command_uses_powershell_natively_on_windows() {
1560+
let ps_command = r#"powershell.exe -NoProfile -NonInteractive -Command "irm https://chatgpt.com/codex/install.ps1 | iex""#;
1561+
let result = super::build_install_command(ps_command);
1562+
assert!(
1563+
result.is_ok(),
1564+
"build_install_command must succeed for a PowerShell command; got: {:?}",
1565+
result.err()
1566+
);
1567+
let cmd = result.unwrap();
1568+
let program = cmd.get_program().to_string_lossy().to_lowercase();
1569+
assert!(
1570+
program.contains("powershell"),
1571+
"PowerShell install command must use powershell.exe, not bash; got: {program}"
1572+
);
1573+
assert!(
1574+
!program.contains("bash"),
1575+
"PowerShell install command must NOT go through bash; got: {program}"
1576+
);
1577+
}
1578+
1579+
/// On Windows, `build_install_command` must route non-PowerShell commands
1580+
/// through Git Bash (program must be bash.exe).
1581+
#[cfg(windows)]
1582+
#[test]
1583+
fn test_build_install_command_uses_git_bash_for_non_powershell_on_windows() {
1584+
let npm_command = "npm install -g @agentclientprotocol/claude-agent-acp";
1585+
let result = super::build_install_command(npm_command);
1586+
assert!(
1587+
result.is_ok(),
1588+
"build_install_command must succeed for an npm command on Windows with Git; got: {:?}",
1589+
result.err()
1590+
);
1591+
let cmd = result.unwrap();
1592+
let program = cmd.get_program().to_string_lossy().to_lowercase();
1593+
assert!(
1594+
program.contains("bash"),
1595+
"non-PowerShell install command must still use bash.exe on Windows; got: {program}"
1596+
);
1597+
}
1598+
1599+
/// On non-Windows, `build_install_command` must always use the Unix shell
1600+
/// (zsh or bash), never powershell.exe.
1601+
#[cfg(not(windows))]
1602+
#[test]
1603+
fn test_build_install_command_uses_unix_shell_on_non_windows() {
1604+
let command = r"curl -fsSL https://example.com/install.sh | bash";
1605+
let result = super::build_install_command(command);
1606+
assert!(
1607+
result.is_ok(),
1608+
"build_install_command must succeed on Unix; got: {:?}",
1609+
result.err()
1610+
);
1611+
let cmd = result.unwrap();
1612+
let program = cmd.get_program().to_string_lossy();
1613+
assert!(
1614+
program.contains("bash") || program.contains("zsh"),
1615+
"Unix install command must use bash or zsh, got: {program}"
1616+
);
1617+
}
1618+
1619+
/// On Windows, `install_powershell_command` must build an exact argv:
1620+
/// flags before `-Command` forwarded, body unquoted (outer catalog quotes stripped),
1621+
/// no bash flags, and `-Command` found on token boundary not as substring.
1622+
#[cfg(windows)]
1623+
#[test]
1624+
fn test_powershell_command_argv_exact() {
1625+
// Catalog format: body wrapped in one outer double-quote pair (Bash-layer serialization).
1626+
let body = "irm https://chatgpt.com/codex/install.ps1 | iex";
1627+
let cmd = super::install_powershell_command(&format!(
1628+
r#"powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "{body}""#
1629+
));
1630+
assert_eq!(
1631+
cmd.get_args()
1632+
.map(|a| a.to_string_lossy().into_owned())
1633+
.collect::<Vec<_>>(),
1634+
vec!["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", body],
1635+
"argv must be exact with outer quotes stripped"
1636+
);
1637+
}
1638+
1639+
/// Token that merely contains `-command` as a substring must not be treated
1640+
/// as the `-Command` boundary; only an exact token match (case-insensitive) counts.
1641+
#[cfg(windows)]
1642+
#[test]
1643+
fn test_powershell_command_token_boundary_not_substring() {
1644+
let cmd = super::install_powershell_command(
1645+
r#"powershell.exe -x-command-y -Command "echo hello""#,
1646+
);
1647+
assert_eq!(
1648+
cmd.get_args()
1649+
.map(|a| a.to_string_lossy().into_owned())
1650+
.collect::<Vec<_>>(),
1651+
vec!["-x-command-y", "-Command", "echo hello"],
1652+
"substring must not consume -Command boundary early"
1653+
);
1654+
}
1655+
1656+
/// Claude Code catalog command (discovery.rs:107) must dequote to the bare pipeline.
1657+
#[cfg(windows)]
1658+
#[test]
1659+
fn test_powershell_command_claude_catalog_dequoted() {
1660+
let cmd = super::install_powershell_command(
1661+
r#"powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "irm https://claude.ai/install.ps1 | iex""#,
1662+
);
1663+
assert_eq!(
1664+
cmd.get_args()
1665+
.map(|a| a.to_string_lossy().into_owned())
1666+
.collect::<Vec<_>>(),
1667+
vec![
1668+
"-NoProfile",
1669+
"-ExecutionPolicy",
1670+
"Bypass",
1671+
"-Command",
1672+
"irm https://claude.ai/install.ps1 | iex",
1673+
],
1674+
"Claude catalog command must be dequoted correctly"
1675+
);
1676+
}
1677+
13891678
// ── install retry ─────────────────────────────────────────────────────────
13901679

13911680
/// Build an `InstallStepResult` with just the fields the retry loop reads.

0 commit comments

Comments
 (0)