Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(host-core): keep PowerShell output and native exit codes intact (#1685)
AR307b7e01ffcdf09
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex 4a77ec1db..7f39a4fde 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -4999,6 +4999,103 @@ mod tests {.await;assert_eq!(native.content["exitCode"], 7);}++ #[cfg(windows)]+ async fn run_windows_powershell(workspace: &Path, command: &str) -> ToolsExecuteResult {+ let options = BashExecutionOptions {+ session_id: "powershell-output-session".into(),+ tool_call_id: "powershell-output-call".into(),+ command_shell_id: shell::WINDOWS_POWERSHELL_ID.into(),+ timeout_ms: Some(30_000),+ cancellation: None,+ output_tx: None,+ extra_env: Vec::new(),+ };+ execute_tool_with_options(+ Some(workspace),+ None,+ "Bash",+ &serde_json::json!({ "command": command }),+ Some(30_000),+ Some(options),+ )+ .await+ }++ #[cfg(windows)]+ #[tokio::test]+ async fn powershell_formats_pipeline_objects_like_the_console() {+ // Cmdlets return objects. The agent must read them the way a console+ // shows them, not as the bare type names that string conversion gives.+ let workspace = tempfile::tempdir().unwrap();+ let output = run_windows_powershell(+ workspace.path(),+ "[pscustomobject]@{ PiName = 'alpha'; PiSize = 42 } | Format-Table; \+ @{ piKey = 'piValue' }; 1, 2, 3 | Measure-Object -Sum",+ )+ .await;+ assert!(output.ok, "PowerShell output failed: {:?}", output.content);+ let stdout = output.content["stdout"].as_str().unwrap_or_default();+ let has_line = |predicate: &dyn Fn(&str) -> bool| stdout.lines().any(predicate);+ assert!(+ has_line(&|line| line.contains("alpha") && line.contains("42")),+ "Format-Table row missing: {stdout:?}"+ );+ assert!(+ has_line(&|line| line.contains("piKey") && line.contains("piValue")),+ "hashtable entry missing: {stdout:?}"+ );+ assert!(+ has_line(&|line| line.starts_with("Sum") && line.trim_end().ends_with(": 6")),+ "Measure-Object sum missing: {stdout:?}"+ );+ for type_name in [+ "Microsoft.PowerShell.Commands.Internal.Format",+ "System.Collections.Hashtable",+ "GenericMeasureInfo",+ ] {+ assert!(+ !stdout.contains(type_name),+ "{type_name} replaced real output: {stdout:?}"+ );+ }+ }++ #[cfg(windows)]+ #[tokio::test]+ async fn powershell_native_stderr_keeps_the_native_exit_code() {+ // Git, cargo, npm and most build tools write progress to stderr. That+ // text stays on stderr, but only the command's own exit code decides+ // whether it failed.+ let workspace = tempfile::tempdir().unwrap();+ let progress = run_windows_powershell(+ workspace.path(),+ "cmd /c \"(echo first progress line 1>&2) & (echo second progress line 1>&2)\"",+ )+ .await;+ assert!(+ progress.ok,+ "successful command failed: {:?}",+ progress.content+ );+ assert_eq!(progress.content["exitCode"], 0);+ let stderr = progress.content["stderr"].as_str().unwrap_or_default();+ assert!(+ stderr.contains("first progress line") && stderr.contains("second progress line"),+ "stderr was {stderr:?}"+ );++ let failure = run_windows_powershell(+ workspace.path(),+ "cmd /c \"echo native failure 1>&2 & exit 3\"",+ )+ .await;+ assert_eq!(failure.content["exitCode"], 3, "{:?}", failure.content);+ assert!(failure.content["stderr"]+ .as_str()+ .unwrap_or_default()+ .contains("native failure"));+ }#[tokio::test]async fn edit_move_to_self_preserves_source_bytes() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/host-core/src/tools/shell.rs b/crates/host-core/src/tools/shell.rsindex 9aa28d15a..2bcfbb460 100644--- a/crates/host-core/src/tools/shell.rs+++ b/crates/host-core/src/tools/shell.rs@@ -211,9 +211,16 @@ pub fn build_invocation_for_platform(ShellPlatform::Windows => match shell_id {// PowerShell 7 keeps the PowerShell 5.1 invocation contract, so the// same non-interactive script drives both generations.+ //+ // `2>&1` turns each stderr line of a native command into an+ // ErrorRecord whose id starts with `NativeCommandError`. Those lines+ // go to stderr, but only the native exit code decides failure; any+ // other ErrorRecord is a PowerShell error and fails the call.+ // Remaining output passes through `Out-String -Stream`, so objects+ // keep their console formatting instead of becoming type names.WINDOWS_POWERSHELL_ID | PWSH_ID => {let script = format!(- "$OutputEncoding = New-Object System.Text.UTF8Encoding($false); [Console]::OutputEncoding = $OutputEncoding; $ErrorActionPreference = 'Continue'; $ProgressPreference = 'SilentlyContinue'; $global:LASTEXITCODE = 0; $script:piPowerShellError = $false; & {{ {command} }} 2>&1 | ForEach-Object {{ if ($_ -is [System.Management.Automation.ErrorRecord]) {{ $script:piPowerShellError = $true; [Console]::Error.WriteLine($_.Exception.Message) }} else {{ [Console]::Out.WriteLine([string]$_) }} }}; $piNativeExitCode = $LASTEXITCODE; if ($script:piPowerShellError) {{ exit 1 }}; exit $piNativeExitCode"+ "$OutputEncoding = New-Object System.Text.UTF8Encoding($false); [Console]::OutputEncoding = $OutputEncoding; $ErrorActionPreference = 'Continue'; $ProgressPreference = 'SilentlyContinue'; $global:LASTEXITCODE = 0; $script:piPowerShellError = $false; & {{ {command} }} 2>&1 | ForEach-Object {{ if ($_ -is [System.Management.Automation.ErrorRecord]) {{ if ($_.FullyQualifiedErrorId -notlike 'NativeCommandError*') {{ $script:piPowerShellError = $true }}; [Console]::Error.WriteLine($_.Exception.Message) }} else {{ $_ }} }} | Out-String -Stream | ForEach-Object {{ [Console]::Out.WriteLine($_) }}; $piNativeExitCode = $LASTEXITCODE; if ($script:piPowerShellError) {{ exit 1 }}; exit $piNativeExitCode");vec!["-NoLogo".into(),@@ -851,6 +858,11 @@ mod tests {assert!(script.contains("UTF8Encoding"));assert!(script.contains("$LASTEXITCODE"));assert!(script.contains("Write-Output 'hello'"));+ // Windows behavior is proven by the PowerShell tests in tools::tests;+ // these guard the script where those tests do not run.+ assert!(script.contains("Out-String -Stream"));+ assert!(script.contains("NativeCommandError"));+ assert!(!script.contains("[string]$_"));let cmd = build_invocation_for_platform(ShellPlatform::Windows,diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex f930d3b62..e0ed51224 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -454,6 +454,12 @@ or executable path hash is accepted as shell identity.- No bash bundled in the installer: Git for Windows is the Windows prerequisite (the app requires git anyway)- Resolution failure returns stable `SHELL_NOT_FOUND` with install guidance- Windows PowerShell and cmd use their native non-interactive invocation.+- PowerShell output passes through PowerShell's own formatter, so objects+ (tables, lists, hashtables, `Measure-Object` results) reach the agent as a+ console shows them, not as type names. Stderr lines from native commands are+ forwarded to stderr and do not fail the call by themselves: the call reports+ the native exit code. Any other PowerShell error fails the call with exit+ code 1.- PowerShell 7 resolves `pwsh.exe` from `%ProgramFiles%\PowerShell\7` (or`ProgramW6432` when the host process is 32-bit), then PATH, which coversmachine-scope, Store, user-scope, and portable installs. The PATH probediff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.mdindex bc44ac87d..063922f8a 100644--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md@@ -377,6 +377,10 @@ tool/protocol 名称,请求中单独携带固定的 shell ID。- 安装程序中没有捆绑 bash:Windows 的 Git 是 Windows 的先决条件(无论如何,该应用程序都需要 git)- 解决失败返回稳定的 `SHELL_NOT_FOUND` 并提供安装指导- Windows PowerShell 和 cmd 使用其本机非交互式调用。+- PowerShell 输出经过 PowerShell 自身的格式化器,因此对象(表格、列表、哈希表、+ `Measure-Object` 结果)以控制台显示的形式交给 Agent,而不是类型名。原生命令+ 写入 stderr 的行会转发到 stderr,但本身不会使调用失败:调用报告原生命令的退出码。+ 其他 PowerShell 错误会使调用以退出码 1 失败。- PowerShell 7 先解析 `%ProgramFiles%\PowerShell\7`(宿主进程为 32 位时为`ProgramW6432`)下的 `pwsh.exe`,再回退到 PATH,覆盖机器级安装、Store、用户级与便携安装。它与 Windows PowerShell 5.1 共用同一调用契约,且从不被