From b09bb70970ce50d1311c7c1c2484cb7a0f82cd9e Mon Sep 17 00:00:00 2001 From: Marc Hansen Date: Mon, 7 Sep 2026 00:54:48 -0700 Subject: [PATCH 1/2] test(agent-hooks): spawn the registered hook the way a shell consumer does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both Windows cmd legs ran the registered command as `spawn('cmd.exe', ['/d','/c', command])`. Node applies MSVCRT quoting to an args array, escaping any `"` in the command as `\"`. cmd.exe does not decode backslash escapes, so a quoted command reaches it with four quotes on the line, trips its "old behaviour" strip (leading quote and last quote removed), and dispatches a token beginning with a backslash. That fails — and the launcher's own `|| echo {}` still prints `{}` and exits 0, so the leg reports a pass for a command that never ran. No consumer spawns cmd that way. `shell: true` derives ComSpec and applies `/d /s /c ""` verbatim itself, which is what a shell-spawning consumer does, so the harness cannot drift from the consumer the way a hand-rolled argv can. Claude Code's own path is `bash -c -l ""` (#18905), unchanged here. No behaviour change: green before and after, verified against origin/main with the shape change stashed. The false pass this removes is unreachable on main today, because every path the gate admits is space-free and so no quoted command is ever produced — it becomes reachable in the next commit. Co-Authored-By: Claude Opus 5 --- .../managed-hook-stdin-lifecycle.test.ts | 24 +++++++++++++++---- .../windows-hook-payload-delivery.test.ts | 20 ++++++++++++---- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts b/src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts index af70f6f54f0e..62638a4e17d9 100644 --- a/src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts +++ b/src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts @@ -156,10 +156,15 @@ type HookRun = { function runHookProcess( executable: string, args: string[], - env: NodeJS.ProcessEnv + env: NodeJS.ProcessEnv, + options: { shell?: boolean } = {} ): Promise { return new Promise((resolve, reject) => { - const child = spawn(executable, args, { env, stdio: ['pipe', 'pipe', 'pipe'] }) + const child = spawn(executable, args, { + env, + stdio: ['pipe', 'pipe', 'pipe'], + shell: options.shell ?? false + }) const stdinErrors: NodeJS.ErrnoException[] = [] let stderr = '' let stdout = '' @@ -425,9 +430,16 @@ describe('Windows managed hook stdin structure', () => { // Why: MSYS rewrites switches and paths, so the command must survive both shells (#14815). const gitBash = findGitBash() + // Why (#19187): the cmd leg used to be `spawn('cmd.exe', ['/d','/c', entry.command])`. + // Node MSVCRT-quotes an args array, escaping any `"` in the command as `\"`; cmd.exe does + // not decode backslash escapes, so a quoted command trips its "old behaviour" quote strip + // and dispatches a token beginning with a backslash. That fails, and the launcher's own + // `|| echo {}` still prints `{}` and exits 0 — so the leg reports a pass for a command + // that never ran. `shell: true` spawns it as a shell-spawning consumer does + // (`%ComSpec% /d /s /c ""`, verbatim), which cannot drift from the consumer. const shells = [ - { name: 'cmd.exe', executable: 'cmd.exe', args: ['/d', '/c', entry.command] }, - { name: 'Git Bash', executable: gitBash, args: ['-c', entry.command] } + { name: 'cmd.exe', executable: entry.command, args: [] as string[], shell: true }, + { name: 'Git Bash', executable: gitBash, args: ['-c', entry.command], shell: false } ] // Why: cover guard exit, reached curl, and the launcher's missing-script fallback. const environments = [ @@ -453,7 +465,9 @@ describe('Windows managed hook stdin structure', () => { for (const shell of shells) { for (const environment of environments) { const label = `${shell.name} / ${environment.name}` - const result = await runHookProcess(shell.executable, shell.args, environment.env) + const result = await runHookProcess(shell.executable, shell.args, environment.env, { + shell: shell.shell + }) expect(result.exitCode, `${label} exit code`).toBe(0) expect(result.stderr, `${label} stderr`).toBe('') expect(() => JSON.parse(result.stdout.trim()), `${label} stdout is JSON`).not.toThrow() diff --git a/src/main/agent-hooks/windows-hook-payload-delivery.test.ts b/src/main/agent-hooks/windows-hook-payload-delivery.test.ts index 79d9f4f60aed..d77d3614a444 100644 --- a/src/main/agent-hooks/windows-hook-payload-delivery.test.ts +++ b/src/main/agent-hooks/windows-hook-payload-delivery.test.ts @@ -87,12 +87,14 @@ type HookRun = { exitCode: number | null; stdout: string; stderr: string; timedO function runHookCommand( executable: string, args: string[], - env: NodeJS.ProcessEnv + env: NodeJS.ProcessEnv, + options: { shell?: boolean } = {} ): Promise { return new Promise((resolve, reject) => { const child = spawn(executable, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, + shell: options.shell ?? false, env }) let stdout = '' @@ -193,13 +195,23 @@ describe.skipIf(process.platform !== 'win32')('Windows managed hook payload deli ORCA_PANE_KEY: PANE_KEY }) + // Why (#19187): the cmd leg used to be `spawn('cmd.exe', ['/d','/c', registeredCommand])`. + // Node applies MSVCRT quoting to an args array, escaping any `"` in the command as `\"`; + // cmd.exe does not decode backslash escapes, so a quoted command arrives with four quotes on + // the line, trips cmd's "old behaviour" strip (leading quote and last quote removed) and + // dispatches a token starting with a backslash. That fails, and the launcher's own + // `|| echo {}` reports exit 0 — a false pass for any quoted command. `shell: true` spawns it + // the way a shell-spawning consumer does (`%ComSpec% /d /s /c ""`, verbatim), so the + // harness cannot drift from the consumer the way a hand-rolled argv can. const shells = [ - { name: 'cmd.exe', executable: 'cmd.exe', args: ['/d', '/c', registeredCommand] }, - { name: 'Git Bash', executable: findGitBash(), args: ['-c', registeredCommand] } + { name: 'cmd.exe', executable: registeredCommand, args: [] as string[], shell: true }, + { name: 'Git Bash', executable: findGitBash(), args: ['-c', registeredCommand], shell: false } ] for (const shell of shells) { const before = listener.posts.length - const result = await runHookCommand(shell.executable, shell.args, env) + const result = await runHookCommand(shell.executable, shell.args, env, { + shell: shell.shell + }) expect(result.timedOut, `${shell.name} timed out`).toBe(false) expect(result.exitCode, `${shell.name} exit code`).toBe(0) From cda6ba98e6935bedd3b4792be4e3b516cf2bd0bf Mon Sep 17 00:00:00 2001 From: Marc Hansen Date: Mon, 7 Sep 2026 01:07:18 -0700 Subject: [PATCH 2/2] fix(hooks): carry a spaced profile path on the direct Windows hook (#19187) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `WINDOWS_CMD_SAFE_PATH` has no space in its character class, so for a script at `C:\Users\First Last\.orca\agent-hooks\claude-hook.cmd` — an ordinary Windows profile — `wrapWindowsDirectCmdHookCommand` returned null and `getWindowsManagedLifecycleHook` fell back to the encoded PowerShell launcher. Those users got none of #18875: the per-event interpreter start-up and the stdout-holding orphan it leaves behind when the hook's timeout kill lands were both still there. Quote the emitted path instead. Measured on Windows 10 19045 against a real `C:\Users\` path, marker-based so a failed dispatch masked by `|| echo {}` cannot pass: invocation quoted, script present bash -c (Claude Code's host, #18905) PASS cmd /d /s /c "", verbatim PASS cmd /d /c , verbatim PASS spawn(cmd, { shell: true }) PASS spawn('cmd.exe', ['/d','/c', cmd]) FAIL — see previous commit The unquoted shape fails both hosts on a spaced path (`{}`, exit 0 — the hook silently never runs), which is why widening the character class alone is not enough and the quoting is the substance of the fix. Quoting is unconditional rather than space-triggered. TEMP is profile-scoped, so a space-triggered branch would make the emitted shape depend on whether the runner's own profile has a space — the fix would then never execute in CI or on an unspaced maintainer box, and only ever run on the machines of the people who reported the bug. One shape keeps every existing test on the fixed path. Everything the class already excluded stays excluded: quoting cannot rescue `%` or `!`, which cmd expands inside double quotes. The `WINDOWS_CMD_QUOTABLE_PATH` class is local to this module rather than a widening of the shared one, which has other callers. Precedent for the shape: `runtime-home-hook-command.ts` already spells its Windows script path always-quoted, and its hazard list (`& ^ ( ) ; , = % !`) likewise does not include the space. Tests: - a caller-level assertion that a spaced profile registers the direct shape and not `-EncodedCommand`; it needs no platform gate because `gitBashAvailable` is injectable, so it guards the reported defect on every CI leg. - the live both-hosts legs now cover a deliberately spaced temp directory, and assert a marker the `|| echo {}` fallback cannot fake. Asserting `{}` alone could not tell "the script ran" from "dispatch failed" — which is how a spaced path passed this suite while the hook never executed. - four `WINDOWS_CMD_SAFE_PATH` gates in the install-level tests now ask the module whether it serves the path. They previously skipped on a spaced TEMP, so the direct shape went unasserted on exactly the machines that had the bug. - an upgrade test: installing over an existing unquoted entry for the same path leaves exactly one quoted entry and no duplicate. Every current Windows user takes that path, and a same-path check comparing commands by string equality would either strand them or double-register the hook. - the encoded-launcher fallback test is repointed from a spaced path to one carrying `%`, and renamed: a space is no longer what the shells cannot carry. Co-Authored-By: Claude Opus 5 --- .../windows-direct-cmd-hook-command.test.ts | 163 ++++++++++++------ .../windows-direct-cmd-hook-command.ts | 35 +++- .../windows-hook-payload-delivery.test.ts | 9 +- src/main/claude/hook-service.test.ts | 109 ++++++++++-- 4 files changed, 248 insertions(+), 68 deletions(-) diff --git a/src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts b/src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts index acb4bf2d46de..1c531eb283c7 100644 --- a/src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts +++ b/src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts @@ -2,46 +2,73 @@ // pins the two things that make that safe — the shape carries nothing MSYS or cmd.exe rewrites, // and it still answers with neutral JSON when the script is gone. The live legs run the string // through BOTH hosts Claude Code can pick, because the shape has to parse in either. +// +// Why (#19187): two defects in those live legs let a spaced profile through. (a) `canRunLive` +// gated on the temp path being cmd-safe, so on `C:\Users\First Last` the legs skipped entirely +// and nothing exercised a spaced path through a real host. (b) They asserted only that stdout +// was `{}` — which is exactly what `|| echo {}` prints when dispatch FAILS, so a hook that never +// ran passed. Both are fixed below: a dedicated spaced-path directory, and a marker the fallback +// cannot fake. import { describe, expect, it } from 'vitest' -import { execFileSync } from 'node:child_process' +import { execFileSync, spawnSync } from 'node:child_process' import { existsSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import { WINDOWS_CMD_SAFE_PATH } from './installer-utils' import { wrapWindowsDirectCmdHookCommand } from './windows-direct-cmd-hook-command' import { findGitBash } from './windows-git-bash-path.test-fixture' const SAFE_PATH = 'C:\\Users\\alice\\.orca\\agent-hooks\\claude-hook.cmd' +const SPACED_PATH = 'C:\\Users\\Bob Smith\\.orca\\agent-hooks\\claude-hook.cmd' describe('wrapWindowsDirectCmdHookCommand', () => { it('emits the script path with forward slashes and a neutral-JSON fallback', () => { expect(wrapWindowsDirectCmdHookCommand(SAFE_PATH)).toBe( - 'C:/Users/alice/.orca/agent-hooks/claude-hook.cmd || echo {}' + '"C:/Users/alice/.orca/agent-hooks/claude-hook.cmd" || echo {}' + ) + }) + + // Why (#19187): a spaced profile is the case #18875 could not serve. It is quoted, not declined. + it('carries a spaced path instead of declining it', () => { + expect(wrapWindowsDirectCmdHookCommand(SPACED_PATH)).toBe( + '"C:/Users/Bob Smith/.orca/agent-hooks/claude-hook.cmd" || echo {}' ) }) it('spells nothing either shell would rewrite or reinterpret', () => { - const command = wrapWindowsDirectCmdHookCommand(SAFE_PATH)! - - // Why: MSYS rewrites `/c`-shaped tokens into drive paths — a literal `cmd.exe /d /c ` - // does not survive Git Bash (measured), which is why no interpreter is spelled at all. - expect(command).not.toMatch(/ \/[a-zA-Z]+( |$)/) - expect(command).not.toMatch(/\\/) - expect(command).not.toMatch(/["']/) - expect(command).not.toMatch(/powershell|cmd\.exe|conhost/i) - // Why: `2>nul` writes a literal file named `nul` into the cwd under MSYS (measured), and no - // stderr sink parses in both hosts. The missing-script line is left on stderr deliberately. - expect(command).not.toContain('2>') + for (const command of [ + wrapWindowsDirectCmdHookCommand(SAFE_PATH)!, + wrapWindowsDirectCmdHookCommand(SPACED_PATH)! + ]) { + // Why: MSYS rewrites `/c`-shaped tokens into drive paths — a literal `cmd.exe /d /c ` + // does not survive Git Bash (measured), which is why no interpreter is spelled at all. + expect(command).not.toMatch(/ \/[a-zA-Z]+( |$)/) + expect(command).not.toMatch(/\\/) + expect(command).not.toMatch(/powershell|cmd\.exe|conhost/i) + // Why (#19187): this used to forbid quoting outright. Double quotes around the whole path + // are the one form both hosts agree on, so what is actually hazardous is narrower — a + // single quote (cmd treats `'` as a literal filename character), a backslash-escaped space + // (bash-only), and a caret (cmd-only). Forbid those, and require the command to open with + // exactly one token that is either fully double-quoted or bare. + expect(command).not.toMatch(/'/) + expect(command).not.toMatch(/\\ |\^/) + expect(command).toMatch(/^(?:"[^"]+"|[^\s"]+) \|\| echo \{\}$/) + // Why: `2>nul` writes a literal file named `nul` into the cwd under MSYS (measured), and no + // stderr sink parses in both hosts. The missing-script line is left on stderr deliberately. + expect(command).not.toContain('2>') + } }) - it('declines any path the shells cannot carry bare', () => { + it('declines any path the shells cannot carry', () => { for (const path of [ - 'C:\\Users\\Bob Smith\\.orca\\agent-hooks\\claude-hook.cmd', + // Why (#19187): quoting cannot save these. cmd expands `%VAR%` inside double quotes, and + // `!VAR!` too under delayed expansion, so they must stay on the encoded launcher. 'C:\\Users\\%name%\\.orca\\agent-hooks\\claude-hook.cmd', + 'C:\\Users\\a!b\\.orca\\agent-hooks\\claude-hook.cmd', 'C:\\Users\\a^b\\.orca\\agent-hooks\\claude-hook.cmd', 'C:\\Users\\a&b\\.orca\\agent-hooks\\claude-hook.cmd', 'C:\\Users\\a(b)\\.orca\\agent-hooks\\claude-hook.cmd', + 'C:\\Users\\a"b\\.orca\\agent-hooks\\claude-hook.cmd', 'C:\\Users\\rené\\.orca\\agent-hooks\\claude-hook.cmd', '/home/alice/.orca/agent-hooks/claude-hook.sh', // Why: WINDOWS_CMD_SAFE_PATH admits a UNC profile, but `//server/share/...` is not a @@ -64,17 +91,28 @@ describe.skipIf(process.platform !== 'win32')('direct hook command, run by both } })() + // Why (#19187): the previous cmd leg was `execFileSync('cmd.exe', ['/d','/c', command])`. + // libuv applies MSVCRT quoting to that argument, turning the command's own `"` into `\"`; + // cmd.exe does not decode backslash escapes, so with four quotes on the line its `/C` rule + // falls to "old behaviour" (strip the leading quote and the last quote) and the command token + // ends up starting with a backslash. Dispatch then fails and `|| echo {}` reports exit 0 — a + // false FAIL for any quoted command. No real consumer invokes cmd that way: Node's own + // `shell: true` emits `cmd.exe /d /s /c ""` with a verbatim command line, which is + // what this uses. `/s` makes the outer-quote strip unconditional; `/c` alone only tolerates a + // single quoted token and breaks the moment a second one appears. function runInCmd(command: string, cwd: string): { stdout: string; status: number } { - return runCapture('cmd.exe', ['/d', '/c', command], cwd) + const result = spawnSync(process.env.COMSPEC ?? 'cmd.exe', ['/d', '/s', '/c', `"${command}"`], { + cwd, + input: '{"hook_event_name":"PreToolUse"}', + encoding: 'utf8', + windowsVerbatimArguments: true + }) + return { stdout: result.stdout ?? '', status: result.status ?? 1 } } function runInBash(command: string, cwd: string): { stdout: string; status: number } { - return runCapture(gitBash!, ['-c', command], cwd) - } - - function runCapture(file: string, args: string[], cwd: string) { try { - const stdout = execFileSync(file, args, { + const stdout = execFileSync(gitBash!, ['-c', command], { cwd, input: '{"hook_event_name":"PreToolUse"}', encoding: 'utf8', @@ -87,17 +125,28 @@ describe.skipIf(process.platform !== 'win32')('direct hook command, run by both } } - // Why: a runner whose TEMP sits under a profile with a space is the encoded-launcher case, - // so these legs skip rather than assert a contract that shape never claimed. - const tempIsCmdSafe = WINDOWS_CMD_SAFE_PATH.test(join(tmpdir(), 'orca-direct-hook-x', 'x.cmd')) - const canRunLive = Boolean(gitBash) && tempIsCmdSafe + // Why (#19187): this used to require the temp path to be cmd-safe, which skipped every + // spaced-profile runner — the exact configuration that was broken, so a space must no longer + // disqualify. A TEMP carrying something outside the quotable class (`%`, a caret, non-ASCII) + // genuinely is the encoded-launcher case and this shape never claimed to serve it, so that + // still skips — but per prefix, and visibly, rather than by asserting inside the body. + const canRunLive = Boolean(gitBash) + + function prefixIsSupported(prefix: string): boolean { + return ( + wrapWindowsDirectCmdHookCommand(join(tmpdir(), `${prefix}probe`, 'claude-hook.cmd')) !== null + ) + } - function withTempDir(run: (dir: string, scriptPath: string, command: string) => void): void { - const dir = mkdtempSync(join(tmpdir(), 'orca-direct-hook-')) + function withTempDir( + prefix: string, + run: (dir: string, scriptPath: string, command: string) => void + ): void { + const dir = mkdtempSync(join(tmpdir(), prefix)) try { const scriptPath = join(dir, 'claude-hook.cmd') const command = wrapWindowsDirectCmdHookCommand(scriptPath) - expect(command, 'precondition: temp path must be cmd-safe').not.toBeNull() + expect(command, `precondition: ${scriptPath} must be supported`).not.toBeNull() run(dir, scriptPath, command!) } finally { // Why: cmd.exe/bash have just exited in this tree; a raw recursive rm throws EPERM on @@ -106,38 +155,50 @@ describe.skipIf(process.platform !== 'win32')('direct hook command, run by both } } - it.skipIf(!canRunLive)('answers {} and exit 0 in both hosts when the script exists', () => { - withTempDir((dir, scriptPath, command) => { - writeFileSync(scriptPath, '@echo off\r\necho {}\r\nexit /b 0\r\n', 'utf8') - for (const result of [runInCmd(command, dir), runInBash(command, dir)]) { - expect(result.stdout.trim()).toBe('{}') - expect(result.status).toBe(0) - } + // Why (#19187): `ORCA_RAN`, not `{}`. Asserting `{}` cannot tell "the script ran and printed + // neutral JSON" from "dispatch failed and the fallback fired" — which is how a spaced path + // passed this suite while the hook never executed. + const MARKER_SCRIPT = '@echo off\r\necho ORCA_RAN\r\nexit /b 0\r\n' + + for (const [label, prefix] of [ + ['a cmd-safe path', 'orca-direct-hook-'], + ['a path with a space', 'orca direct hook '] + ] as const) { + const skipPrefix = !canRunLive || !prefixIsSupported(prefix) + + it.skipIf(skipPrefix)(`runs the script in both hosts, on ${label}`, () => { + withTempDir(prefix, (dir, scriptPath, command) => { + writeFileSync(scriptPath, MARKER_SCRIPT, 'utf8') + for (const result of [runInCmd(command, dir), runInBash(command, dir)]) { + expect(result.stdout.trim()).toBe('ORCA_RAN') + expect(result.status).toBe(0) + } + }) }) - }) - it.skipIf(!canRunLive)( - 'still answers {} and exit 0 in both hosts when the script is gone', - () => { + it.skipIf(skipPrefix)(`answers {} in both hosts when the script is gone, on ${label}`, () => { // Why: compat consumers require neutral JSON even with no managed script (#14818). The // encoded launcher did this with a Test-Path; `|| echo {}` does it with no interpreter. - withTempDir((dir, scriptPath, command) => { + withTempDir(prefix, (dir, scriptPath, command) => { expect(existsSync(scriptPath)).toBe(false) for (const result of [runInCmd(command, dir), runInBash(command, dir)]) { expect(result.stdout.trim()).toBe('{}') expect(result.status).toBe(0) } }) + }) + } + + it.skipIf(!canRunLive || !prefixIsSupported('orca direct hook '))( + 'leaves no stray `nul` file behind in the working directory', + () => { + // Why this is worth a test: adding `2>nul` to silence the missing-script line looks like + // tidy-up, but under MSYS it creates a real file named `nul` in the cwd — which is the + // user's repo. Measured on Windows 11. Keep stderr unredirected. + withTempDir('orca direct hook ', (dir, _scriptPath, command) => { + runInBash(command, dir) + expect(readdirSync(dir)).not.toContain('nul') + }) } ) - - it.skipIf(!canRunLive)('leaves no stray `nul` file behind in the working directory', () => { - // Why this is worth a test: adding `2>nul` to silence the missing-script line looks like - // tidy-up, but under MSYS it creates a real file named `nul` in the cwd — which is the - // user's repo. Measured on Windows 11. Keep stderr unredirected. - withTempDir((dir, _scriptPath, command) => { - runInBash(command, dir) - expect(readdirSync(dir)).not.toContain('nul') - }) - }) }) diff --git a/src/main/agent-hooks/windows-direct-cmd-hook-command.ts b/src/main/agent-hooks/windows-direct-cmd-hook-command.ts index f7646f195786..c1782081605c 100644 --- a/src/main/agent-hooks/windows-direct-cmd-hook-command.ts +++ b/src/main/agent-hooks/windows-direct-cmd-hook-command.ts @@ -1,9 +1,18 @@ -import { WINDOWS_CMD_SAFE_PATH } from './installer-utils' - // Why: a drive-letter path only. WINDOWS_CMD_SAFE_PATH also admits a UNC profile, and // `//server/share/...` is not a command cmd.exe reliably starts. const WINDOWS_DRIVE_LETTER_PATH = /^[A-Za-z]:\\/ +// Why (#19187): WINDOWS_CMD_SAFE_PATH excludes the space, so `C:\Users\First Last` — an ordinary +// profile shape — returned null and kept the encoded launcher #18875 removed, with none of that +// fix's benefit. A space is the one character a surrounding pair of double quotes fixes in both +// hosts; everything the shared class already excluded (`%`, `!`, `^`, `&`, `(`, `)`, quotes, +// non-ASCII) stays excluded, because quoting cannot save those — cmd expands `%VAR%` inside +// double quotes, and `!VAR!` too under delayed expansion. Local to this file rather than a +// widening of the shared class, which has other callers. +// Precedent: `runtime-home-hook-command.ts` already spells its Windows script path +// always-quoted, and its hazard list (`& ^ ( ) ; , = % !`) likewise does not include the space. +const WINDOWS_CMD_QUOTABLE_PATH = /^[A-Za-z0-9_.:\\~ -]+$/ + /** * Shortest launcher for a managed Windows `.cmd` hook: the script path itself (#18875). * @@ -15,16 +24,34 @@ const WINDOWS_DRIVE_LETTER_PATH = /^[A-Za-z]:\\/ * Returns null when the caller must keep the encoded launcher: a path either shell would mangle. */ export function wrapWindowsDirectCmdHookCommand(scriptPath: string): string | null { - if (!WINDOWS_CMD_SAFE_PATH.test(scriptPath) || !WINDOWS_DRIVE_LETTER_PATH.test(scriptPath)) { + if (!WINDOWS_DRIVE_LETTER_PATH.test(scriptPath) || !WINDOWS_CMD_QUOTABLE_PATH.test(scriptPath)) { return null } // Why: forward slashes are the one separator both hosts read, and no token here is a switch // MSYS can rewrite — a literal `cmd.exe /d /c ` does not survive Git Bash (measured). const invocation = scriptPath.replaceAll('\\', '/') + // Why (#19187): quote unconditionally rather than only when a space is present. One emitted + // shape means the harnesses and the tests see the same string on every machine; quoting only + // spaced paths makes the emitted shape depend on whether the runner's own profile has a space + // (TEMP is profile-scoped), which turns a deterministic contract into a per-box coin flip. + // + // Double quotes are inert here for a path this class admits: bash expands `$`, a backtick or a + // `\` inside double quotes and the class permits none of them by this line (the backslashes it + // does permit are forward slashes above), and cmd needs the quotes precisely to keep a spaced + // path one token. + // + // One measured exception, so this is not overclaimed: the quoted form does NOT survive + // `execFileSync('cmd.exe', ['/d','/c', command])`. libuv MSVCRT-quotes that argument (`"` -> + // `\"`), cmd.exe does not decode backslash escapes, and with four quotes on the line its `/C` + // rule falls to "old behaviour" — strip the leading quote and the last quote — leaving a + // command token that starts with a backslash. Dispatch then fails and `|| echo {}` reports + // exit 0. No consumer spawns cmd that way: a shell (`shell: true` -> `%ComSpec% /d /s /c + // ""`, verbatim) and `bash -c` both run it correctly, and both are measured green. + const invocationToken = `"${invocation}"` // Why: neutral JSON when the script is missing (#14818), with no interpreter to Test-Path with. // Valid in bash and cmd.exe; PowerShell 5.1 rejects `||`, which is what gates this on Git Bash. // It also fires when cmd.exe itself exits non-zero (a failing AutoRun), printing `{}` twice — // on that same box the encoded launcher exited 1 instead, so neither shape is clean there. // Stderr stays unredirected: `2>nul` writes a literal `nul` file into the cwd under MSYS. - return `${invocation} || echo {}` + return `${invocationToken} || echo {}` } diff --git a/src/main/agent-hooks/windows-hook-payload-delivery.test.ts b/src/main/agent-hooks/windows-hook-payload-delivery.test.ts index d77d3614a444..1cc6f4c5082f 100644 --- a/src/main/agent-hooks/windows-hook-payload-delivery.test.ts +++ b/src/main/agent-hooks/windows-hook-payload-delivery.test.ts @@ -32,7 +32,7 @@ vi.mock('os', async (importOriginal) => { }) import { ClaudeHookService } from '../claude/hook-service' -import { WINDOWS_CMD_SAFE_PATH } from './installer-utils' +import { wrapWindowsDirectCmdHookCommand } from './windows-direct-cmd-hook-command' import { getConfigPath, getWindowsManagedLifecycleHook } from '../claude/hook-settings' import { findGitBash } from './windows-git-bash-path.test-fixture' @@ -179,9 +179,12 @@ describe.skipIf(process.platform !== 'win32')('Windows managed hook payload deli // Why: assert nothing about the launcher's shape here — this test's whole value is // that it fails for any launcher that loses the payload, named conhost or not. const registeredCommand = settings.hooks.PreToolUse[0].hooks[0].command - // ...with one exception: a cmd-safe profile must reach the script with no interpreter in + // ...with one exception: a supported profile must reach the script with no interpreter in // front of it, or #18875's per-event PowerShell start-up has quietly come back. - if (WINDOWS_CMD_SAFE_PATH.test(join(home, '.orca', 'agent-hooks', 'claude-hook.cmd'))) { + // Why (#19187): this gate was `WINDOWS_CMD_SAFE_PATH`, which excluded a space — so on a + // profile-scoped, spaced TEMP the no-PowerShell assertion silently dropped, on exactly the + // machines where the launcher had come back. Ask the module whether it serves the path. + if (wrapWindowsDirectCmdHookCommand(join(home, '.orca', 'agent-hooks', 'claude-hook.cmd'))) { expect(registeredCommand).not.toMatch(/powershell|-EncodedCommand/i) } diff --git a/src/main/claude/hook-service.test.ts b/src/main/claude/hook-service.test.ts index a4e48c98120b..01e2750b2425 100644 --- a/src/main/claude/hook-service.test.ts +++ b/src/main/claude/hook-service.test.ts @@ -24,7 +24,8 @@ vi.mock('../git-bash', async (importOriginal) => ({ })) import type { SFTPWrapper } from 'ssh2' -import { createManagedCommandMatcher, WINDOWS_CMD_SAFE_PATH } from '../agent-hooks/installer-utils' +import { createManagedCommandMatcher } from '../agent-hooks/installer-utils' +import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' import { WINDOWS_HOOK_STDIN_DRAIN_LABEL } from '../agent-hooks/hook-stdin-contract' import { ClaudeHookService } from './hook-service' import { @@ -50,6 +51,7 @@ function hasManagedCommand(hook: TestHook, matcher: (command: string | undefined describe('getWindowsManagedLifecycleHook', () => { const SAFE_SCRIPT_PATH = 'C:\\Users\\alice\\.orca\\agent-hooks\\claude-hook.cmd' const UNSAFE_SCRIPT_PATH = 'C:\\Users\\%name%\\a^b&c\\.orca\\agent-hooks\\claude-hook.cmd' + const SPACED_SCRIPT_PATH = 'C:\\Users\\Bob Smith\\.orca\\agent-hooks\\claude-hook.cmd' it('registers the script itself, with no interpreter in front of it (#18875)', () => { // Why this is the whole point: the encoded launcher spent a PowerShell start-up per hook @@ -58,13 +60,27 @@ describe('getWindowsManagedLifecycleHook', () => { const hook = getWindowsManagedLifecycleHook(SAFE_SCRIPT_PATH, { gitBashAvailable: true }) expect(hook.args).toBeUndefined() - expect(hook.command).toBe('C:/Users/alice/.orca/agent-hooks/claude-hook.cmd || echo {}') + expect(hook.command).toBe('"C:/Users/alice/.orca/agent-hooks/claude-hook.cmd" || echo {}') expect(hook.command).not.toMatch(/powershell|-EncodedCommand|conhost/i) // Why: Git Bash/MSYS mangles backslash paths and rewrites slash-prefixed switches. expect(hook.command).not.toMatch(/\\/) expect(hook.command).not.toMatch(/ \/[a-zA-Z]+( |$)/) }) + // Why (#19187): this is the assertion that pins the reported defect at the layer users feel. + // `WINDOWS_CMD_SAFE_PATH` excluded the space, so every `C:\Users\First Last` profile fell + // through to the encoded launcher and got none of #18875's benefit — the per-event PowerShell + // start-up and its stdout-holding orphan were still there. It needs no platform gate because + // `gitBashAvailable` is injectable, so it runs on the POSIX CI legs too. + it('registers the direct shape for a spaced profile, not the encoded launcher (#19187)', () => { + const hook = getWindowsManagedLifecycleHook(SPACED_SCRIPT_PATH, { gitBashAvailable: true }) + + expect(hook.args).toBeUndefined() + expect(hook.command).toBe('"C:/Users/Bob Smith/.orca/agent-hooks/claude-hook.cmd" || echo {}') + expect(hook.command).not.toMatch(/powershell|-EncodedCommand|conhost/i) + expect(hook.command).not.toMatch(/\\/) + }) + it('falls back to the encoded launcher when the profile path is not cmd-safe', () => { const hook = getWindowsManagedLifecycleHook(UNSAFE_SCRIPT_PATH, { gitBashAvailable: true }) @@ -410,9 +426,15 @@ describe('ClaudeHookService.install', () => { }) it.skipIf(process.platform !== 'win32')( - 'pins the encoded-launcher fallback for a profile path the shells cannot carry bare', + 'pins the encoded-launcher fallback for a profile path quoting cannot rescue', () => { - const tmpHome = mkdtempSync(join(tmpdir(), 'orca claude home with spaces ')) + // Why (#19187): this used to use a spaced home, because a space was believed to be + // uncarryable. It is not — double quotes keep a spaced path one token in both hosts, and a + // spaced profile now takes the direct shape (asserted below). What quoting genuinely cannot + // rescue is `%`: cmd expands `%VAR%` *inside* double quotes, so such a path must stay on the + // encoded launcher. That is what this test pins now — the fallback still exists, for the + // paths that actually need it. + const tmpHome = mkdtempSync(join(tmpdir(), 'orca claude %home% ')) vi.stubEnv('HOME', tmpHome) vi.stubEnv('USERPROFILE', tmpHome) try { @@ -443,7 +465,7 @@ describe('ClaudeHookService.install', () => { ) it.skipIf(process.platform !== 'win32')( - 'installs the bare script path on every event when the profile path is cmd-safe (#18875)', + 'installs the direct script path on every event when the profile path is supported (#18875)', () => { const tmpHome = mkdtempSync(join(tmpdir(), 'orca-claude-direct-')) vi.stubEnv('HOME', tmpHome) @@ -451,7 +473,10 @@ describe('ClaudeHookService.install', () => { const scriptPath = join(tmpHome, '.orca', 'agent-hooks', CLAUDE_SCRIPT_FILE_NAME) // Why: a runner whose tmpdir carries a space (a profile-scoped TEMP) belongs to the // fallback case above, not this one; skip rather than assert the wrong contract. - if (!WINDOWS_CMD_SAFE_PATH.test(scriptPath)) { + // Why (#19187): this gate used to be `WINDOWS_CMD_SAFE_PATH`, which excluded a space — so on + // a profile-scoped, spaced TEMP these tests skipped, and the direct shape went unasserted on + // exactly the machines that had the bug. Ask the module itself whether it serves the path. + if (wrapWindowsDirectCmdHookCommand(scriptPath) === null) { vi.unstubAllEnvs() rmSync(tmpHome, { recursive: true, force: true }) return @@ -463,7 +488,7 @@ describe('ClaudeHookService.install', () => { readFileSync(join(tmpHome, '.claude', 'settings.json'), 'utf-8') ) as { hooks: Record } - const expected = `${scriptPath.replaceAll('\\', '/')} || echo {}` + const expected = `"${scriptPath.replaceAll('\\', '/')}" || echo {}` for (const { eventName } of CLAUDE_EVENTS) { const hook = settings.hooks[eventName]?.[0]?.hooks?.[0] expect(hook?.args, eventName).toBeUndefined() @@ -479,6 +504,64 @@ describe('ClaudeHookService.install', () => { } ) + it.skipIf(process.platform !== 'win32')( + 'upgrades an existing unquoted entry for the same path in place (#19187)', + () => { + // Why: this is the path every current Windows user takes on upgrade, and the one most + // likely to ship looking correct while fixing nothing. The stale entry names the SAME + // script path as the new one and differs only by the quotes, so a same-path check that + // compares commands by string equality either leaves it alone (user stays broken) or + // appends a second entry (the hook fires twice). Neither is visible from the unit tests. + const tmpHome = mkdtempSync(join(tmpdir(), 'orca-claude-upgrade-')) + vi.stubEnv('HOME', tmpHome) + vi.stubEnv('USERPROFILE', tmpHome) + const scriptPath = join(tmpHome, '.orca', 'agent-hooks', CLAUDE_SCRIPT_FILE_NAME) + if (wrapWindowsDirectCmdHookCommand(scriptPath) === null) { + vi.unstubAllEnvs() + rmSync(tmpHome, { recursive: true, force: true }) + return + } + try { + const settingsPath = join(tmpHome, '.claude', 'settings.json') + mkdirSync(join(tmpHome, '.claude'), { recursive: true }) + // The exact string #18905 shipped: same path, no quotes. + const unquoted = `${scriptPath.replaceAll('\\', '/')} || echo {}` + writeFileSync( + settingsPath, + JSON.stringify({ + hooks: Object.fromEntries( + CLAUDE_EVENTS.map(({ eventName }) => [ + eventName, + [{ hooks: [{ type: 'command', command: unquoted, timeout: 10 }] }] + ]) + ) + }), + 'utf-8' + ) + + expect(new ClaudeHookService().install().state).toBe('installed') + + const settings = JSON.parse(readFileSync(settingsPath, 'utf-8')) as { + hooks: Record + } + const expected = `"${scriptPath.replaceAll('\\', '/')}" || echo {}` + for (const { eventName } of CLAUDE_EVENTS) { + const hooks = settings.hooks[eventName].flatMap((definition) => definition.hooks) + const managed = hooks.filter((hook) => hook.command.includes(CLAUDE_SCRIPT_FILE_NAME)) + expect(managed, `${eventName}: exactly one managed entry, not a duplicate`).toHaveLength( + 1 + ) + expect(managed[0].command, eventName).toBe(expected) + } + expect(JSON.stringify(settings.hooks), 'no unquoted leftover').not.toContain(unquoted) + expect(new ClaudeHookService().getStatus().state).toBe('installed') + } finally { + vi.unstubAllEnvs() + rmSync(tmpHome, { recursive: true, force: true }) + } + } + ) + it.skipIf(process.platform !== 'win32')( 'sweeps a previously installed encoded launcher on reinstall, keeping user hooks', () => { @@ -486,7 +569,10 @@ describe('ClaudeHookService.install', () => { vi.stubEnv('HOME', tmpHome) vi.stubEnv('USERPROFILE', tmpHome) const scriptPath = join(tmpHome, '.orca', 'agent-hooks', CLAUDE_SCRIPT_FILE_NAME) - if (!WINDOWS_CMD_SAFE_PATH.test(scriptPath)) { + // Why (#19187): this gate used to be `WINDOWS_CMD_SAFE_PATH`, which excluded a space — so on + // a profile-scoped, spaced TEMP these tests skipped, and the direct shape went unasserted on + // exactly the machines that had the bug. Ask the module itself whether it serves the path. + if (wrapWindowsDirectCmdHookCommand(scriptPath) === null) { vi.unstubAllEnvs() rmSync(tmpHome, { recursive: true, force: true }) return @@ -535,7 +621,10 @@ describe('ClaudeHookService.install', () => { vi.stubEnv('HOME', tmpHome) vi.stubEnv('USERPROFILE', tmpHome) const scriptPath = join(tmpHome, '.orca', 'agent-hooks', CLAUDE_SCRIPT_FILE_NAME) - if (!WINDOWS_CMD_SAFE_PATH.test(scriptPath)) { + // Why (#19187): this gate used to be `WINDOWS_CMD_SAFE_PATH`, which excluded a space — so on + // a profile-scoped, spaced TEMP these tests skipped, and the direct shape went unasserted on + // exactly the machines that had the bug. Ask the module itself whether it serves the path. + if (wrapWindowsDirectCmdHookCommand(scriptPath) === null) { vi.unstubAllEnvs() rmSync(tmpHome, { recursive: true, force: true }) return @@ -563,7 +652,7 @@ describe('ClaudeHookService.install', () => { } expect(JSON.stringify(settings.hooks)).not.toContain('someone-else') expect(settings.hooks.PreToolUse[0].hooks[0].command).toBe( - `${scriptPath.replaceAll('\\', '/')} || echo {}` + `"${scriptPath.replaceAll('\\', '/')}" || echo {}` ) expect(new ClaudeHookService().getStatus().state).toBe('installed') } finally {