Skip to content

The agent that grows with you

fix(desktop): harden every Windows SSH stdout parser against CLIXML pollution

Brooklyn Nicholson7f2271dee311
diff --git a/apps/desktop/electron/windows-remote-lifecycle.test.ts b/apps/desktop/electron/windows-remote-lifecycle.test.ts
index 42d5de1d33a..623c06d9d8c 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.test.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.test.ts
@@ -10,6 +10,7 @@ import {
connectWindowsRemote,
detectRemotePlatform,
encodedPowerShell,
+ helper,
helperCommand,
powerShellCommand,
probeWindowsRemote,
@@ -268,6 +269,71 @@ test('Windows probe still rejects output that is not platform JSON', async () =>
await assert.rejects(probeWindowsRemote(sshWith(async () => JSON.stringify({ os: 'Windows' })+'\n'+JSON.stringify({unrelated:true}) )))
})
+test('the update marker gate stays CLEAR when CLIXML lands after the final Write-Output', async () => {
+ // The gate is fail-closed: it only accepts a strict `CLEAR` from the last
+ // line. A progress record serialized after `Write-Output $result` used to win
+ // the .pop() and refuse SSH startup as 'update-in-progress' — a misleading
+ // safety verdict from a cosmetic stdout race, not an actual update.
+ for (const observation of [
+ `CLEAR\r\n${CLIXML_PROGRESS}`,
+ `${CLIXML_PROGRESS}\r\nCLEAR`,
+ `\uFEFFCLEAR\r\n${CLIXML_PROGRESS}\r\n${CLIXML_PROGRESS}`
+ ]) {
+ await assertWindowsRemoteInstallUpdateClear(sshWith(async () => observation), 'C:\\h')
+ }
+
+ // The verdict itself is untouched: a LIVE marker still pauses startup.
+ await assert.rejects(
+ assertWindowsRemoteInstallUpdateClear(sshWith(async () => `LIVE:4242\r\n${CLIXML_PROGRESS}`), 'C:\\h'),
+ (err: any) => err.kind === 'update-in-progress' && /4242/.test(err.message)
+ )
+})
+
+test('every parsed Windows PowerShell script silences the progress stream', async () => {
+ // The marker gate runs Add-Type (C# compilation) and the spawn/helper scripts
+ // import the remote hermes_cli module — both emit progress records the
+ // probe's Get-Item/Get-Command suppression knows nothing about, on the same
+ // stdout the parsers read.
+ const decode = (command: string) => Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')
+
+ const scripts: string[] = []
+ await assertWindowsRemoteInstallUpdateClear(
+ sshWith(async command => {
+ scripts.push(decode(command))
+
+ return 'CLEAR'
+ }),
+ 'C:\\h'
+ )
+ scripts.push(
+ decode(atomicWindowsSpawnCommand({ hermesHome: 'C:\\h', python: 'C:\\py\\python.exe' })),
+ decode(helperCommand({ python: 'C:\\py\\python.exe' }, 'inspect', []))
+ )
+
+ assert.equal(scripts.length, 3)
+
+ for (const script of scripts) {
+ assert.ok(script.indexOf('$ProgressPreference="SilentlyContinue"') >= 0, script.slice(0, 80))
+ assert.ok(script.indexOf('$ProgressPreference') < script.indexOf('$ErrorActionPreference'), script.slice(0, 80))
+ }
+})
+
+test('helper parsing ignores CLIXML progress blocks around its JSON line', async () => {
+ const payload = JSON.stringify({ supported: true, version: '1.2.3' })
+
+ for (const output of [`${CLIXML_PROGRESS}\r\n${payload}`, `\uFEFF${payload}\r\n${CLIXML_PROGRESS}`, `${payload}`]) {
+ const parsed = await helper(
+ sshWith(async () => output),
+ { python: 'C:\\py\\python.exe' },
+ 'inspect',
+ ['C:\\h\\hermes.exe']
+ )
+
+ assert.equal(parsed.supported, true)
+ assert.equal(parsed.version, '1.2.3')
+ }
+})
+
test('platform detection preserves POSIX and falls back to Windows PowerShell', async () => {
assert.deepEqual(await detectRemotePlatform(sshWith(async () => 'Linux\nx86_64\n')), { os: 'Linux', arch: 'x86_64' })
const calls: string[] = []
diff --git a/apps/desktop/electron/windows-remote-lifecycle.ts b/apps/desktop/electron/windows-remote-lifecycle.ts
index 4f7e4a895a3..2e259c95b3a 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.ts
@@ -20,6 +20,21 @@ function powerShellCommand(script) {
return `powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${encodedPowerShell(script)}`
}
+// Windows OpenSSH may serialize PowerShell's progress stream as
+// "#< CLIXML <Objs ...>...</Objs>" blocks into the captured stdout of ANY
+// PowerShell exec on the connection (module auto-load / Add-Type cold-start
+// racing the read) — not just the platform probe. Every stdout-parsing call
+// shares this normalizer: strip a leading BOM, drop every CLIXML block
+// (before, after, or on the same line as the payload), and keep only the
+// meaningful lines.
+function stripPowerShellNoise(stdout) {
+ return String(stdout || '')
+ .replace(/^\uFEFF/, '')
+ .replace(/#< CLIXML[\s\S]*?<\/Objs>/g, '')
+ .split(/\r?\n/)
+ .filter(line => line.trim() && !line.trimStart().startsWith('#< CLIXML'))
+}
+
async function probeWindowsRemote(ssh, explicitHermesPath = '') {
const explicit = psLiteral(explicitHermesPath)
@@ -73,16 +88,11 @@ async function probeWindowsRemote(ssh, explicitHermesPath = '') {
].join(';')
// Windows OpenSSH may serialize PowerShell's progress stream as
- // "#< CLIXML <Objs ...>...</Objs>" blocks into the same stdout channel the
- // probe reads, ahead of, after, or on the same line as the probe JSON
- // (module auto-load racing the exec read). Drop every block, then apply
- // the sibling helpers' convention: the JSON is the last meaningful line.
- const lines = String(await ssh.exec(powerShellCommand(script)))
- .replace(/^\uFEFF/, '')
- .replace(/#< CLIXML[\s\S]*?<\/Objs>/g, '')
- .trim()
- .split(/\r?\n/)
- .filter(line => line.trim() && !line.trimStart().startsWith('#< CLIXML'))
+ // "#< CLIXML <Objs ...>...</Objs>" blocks into the same stdout the
+ // probe parses, ahead of, after, or on the same line as the probe JSON
+ // (module auto-load racing the exec read). stripPowerShellNoise drops every
+ // block; the JSON is the last meaningful line.
+ const lines = stripPowerShellNoise(await ssh.exec(powerShellCommand(script)))
const parsed = JSON.parse(lines[lines.length - 1] || 'null')
@@ -95,6 +105,7 @@ async function probeWindowsRemote(ssh, explicitHermesPath = '') {
function windowsUpdateMarkerProbeCommand(hermesHome) {
const script = [
+ '$ProgressPreference="SilentlyContinue"',
'$ErrorActionPreference="Stop"',
`Add-Type -TypeDefinition @'
using System;
@@ -165,12 +176,10 @@ async function assertWindowsRemoteInstallUpdateClear(ssh, hermesHome) {
let observation = ''
try {
- observation =
- String(await ssh.exec(windowsUpdateMarkerProbeCommand(hermesHome)))
- .replace(/^\uFEFF/, '')
- .trim()
- .split(/\r?\n/)
- .pop() || ''
+ // Same stdout channel as the probe: a CLIXML progress block after the
+ // final `Write-Output $result` would otherwise win the .pop() and turn a
+ // CLEAR gate into a fail-closed 'update-in-progress' verdict.
+ observation = stripPowerShellNoise(await ssh.exec(windowsUpdateMarkerProbeCommand(hermesHome))).pop() || ''
} catch (cause) {
const error: any = new Error('Could not prove that the remote Hermes install is clear for SSH startup.')
error.kind = 'update-in-progress'
@@ -246,6 +255,7 @@ function helperCommand(runtime, operation, args = []) {
const argv = [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', operation, ...args]
const script = [
+ '$ProgressPreference="SilentlyContinue"',
'$ErrorActionPreference="Stop"',
`& ${argv.map(psLiteral).join(' ')}`,
'if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}'
@@ -257,11 +267,7 @@ function helperCommand(runtime, operation, args = []) {
async function helper(ssh, runtime, operation, args = [], stdinData?) {
const output = await ssh.exec(helperCommand(runtime, operation, args), stdinData == null ? {} : { stdinData })
- const lines = String(output || '')
- .replace(/^\uFEFF/, '')
- .trim()
- .split(/\r?\n/)
- .filter(Boolean)
+ const lines = stripPowerShellNoise(output)
const parsed = JSON.parse(lines[lines.length - 1] || 'null')
@@ -277,6 +283,7 @@ function atomicWindowsSpawnCommand(runtime, reservation: any = {}) {
const helper = operation => [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', operation]
const script = [
+ '$ProgressPreference="SilentlyContinue"',
'$ErrorActionPreference="Stop"',
`$hermesHome=${psLiteral(runtime.hermesHome)}`,
'$installRoot=$hermesHome',
@@ -317,11 +324,7 @@ function atomicWindowsSpawnCommand(runtime, reservation: any = {}) {
async function atomicWindowsSpawn(ssh, runtime, stdinData, reservation: any = {}) {
const output = await ssh.exec(atomicWindowsSpawnCommand(runtime, reservation), { stdinData })
- const lines = String(output || '')
- .replace(/^\uFEFF/, '')
- .trim()
- .split(/\r?\n/)
- .filter(Boolean)
+ const lines = stripPowerShellNoise(output)
const parsed = JSON.parse(lines[lines.length - 1] || 'null')
@@ -804,6 +807,7 @@ export {
probeWindowsRemote,
psLiteral,
reusableWindowsLock,
+ stripPowerShellNoise,
terminateOwnedWindowsDashboardForUpdate,
validLock
}