Skip to content

fix(hooks): carry a spaced profile path on the direct Windows hook (#19187) - #19255

Closed
marcdhansen wants to merge 2 commits into
stablyai:mainfrom
marcdhansen:fix/windows-hook-spaced-path
Closed

marcdhansen wants to merge 2 commits into
stablyai:mainfrom
marcdhansen:fix/windows-hook-spaced-path

Conversation

@marcdhansen

Copy link
Copy Markdown
Contributor

Fixes #19187.

What was wrong

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 returns null and getWindowsManagedLifecycleHook falls back to the encoded PowerShell launcher.

Those users got zero benefit from #18905. The per-event PowerShell start-up and the stdout-holding orphan it leaves when the hook's timeout kill lands are both still there. On my box that reached 8,731 orphaned conhost.exe (9,073 processes, 1.38M handles) and process creation itself took tens of seconds; claude would not launch from a terminal. After reaping them: 364 processes and claude --version went from a 120 s timeout to 55 ms.

The fix

Quote the emitted path. Measured on Windows 10 19045 against a real C:\Users\<first last> path, marker-based so a failed dispatch masked by || echo {} cannot pass:

invocation quoted, script present
bash -c — Claude Code's host per #18905 PASS
cmd /d /s /c "<cmd>", verbatim PASS
cmd /d /c <cmd>, verbatim PASS
spawn(cmd, { shell: true }) PASS
spawn('cmd.exe', ['/d','/c', cmd]) FAIL — harness artifact, see commit 1

The unquoted shape fails both hosts on a spaced path ({}, exit 0 — the hook silently never runs), so widening the character class alone is not sufficient; the quoting is the substance.

Two commits, reviewable separately

1 — test(agent-hooks): spawn the registered hook the way a shell consumer does. Both Windows cmd legs ran the registered command as spawn('cmd.exe', ['/d','/c', command]). Node MSVCRT-quotes an args array, escaping " as \"; cmd.exe does not decode backslash escapes, so a quoted command arrives with four quotes, trips cmd's "old behaviour" strip, and dispatches a token starting with a backslash — which fails while || echo {} still reports {} and exit 0. shell: true derives ComSpec and applies /d /s /c "<cmd>" verbatim, so the harness cannot drift from the consumer. Verified green before and after against origin/main with commit 2 stashed — no behaviour change, and the false pass it removes is unreachable on main today because no path the gate admits produces a quoted command.

If you would rather review that as its own PR, say the word and I will split it out.

2 — fix(hooks): carry a spaced profile path on the direct Windows hook. The behaviour change plus its tests. Touches no harness.

Design notes

Quoting is unconditional, not 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 never execute in CI or on an unspaced maintainer box, and would only ever run on the machines of the people who reported the bug. One shape puts every existing test on the fixed path. Happy to switch to conditional if you prefer the byte-identical output for unspaced profiles; it is a small change.

Everything the class excluded stays excluded. Quoting cannot rescue % or ! — cmd expands those inside double quotes — so those still take the encoded launcher.

WINDOWS_CMD_QUOTABLE_PATH is local to the module rather than a widening of the shared WINDOWS_CMD_SAFE_PATH, 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. This makes the two launchers agree.

Tests

  • A caller-level assertion that a spaced profile registers the direct shape and not -EncodedCommand. No platform gate needed — 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 (ORCA_RAN) the || echo {} fallback cannot fake. Asserting {} alone could not distinguish "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 on upgrade, 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.

Verified the new tests fail against the pre-fix module (6 of 9 in windows-direct-cmd-hook-command.test.ts), so they genuinely guard the behaviour.

Local test state — please let CI arbitrate

src/main/agent-hooks + src/main/claude/hook-service.test.ts: 703 passed, 6 failed, and those same 6 fail identically on clean origin/main in my environment, so this branch adds no failures.

I have to be straight about those 6, though: I installed with ELECTRON_SKIP_BINARY_DOWNLOAD=1 pnpm install --ignore-scripts because a full install was impractical here, and I initially assumed unbuilt native deps explained them. Their failure mode is assertion-level (expected null to be +0, expected [ 'EPIPE', 'ECONNRESET' ] to include 'EOF'), not module-load, so that explanation does not obviously fit and I have not root-caused them. They are: hook-script-outside-orca.test.ts ×4, spool.test.ts ×1, managed-hook-stdin-lifecycle "exits 0 for every local script…" ×1. The last is in a file this PR touches, so if CI shows it red please don't assume my environmental theory.

installer-utils.test.ts also has 2 failures (caret literally, wrapRuntimeHomeHookCommand) — I ran it with and without this change and the results are identical, so they are pre-existing.

Not fixed here, worth knowing

A .cmd has no loader, so executing it always means a cmd.exe interpreting it, and child.kill() is TerminateProcess on the immediate child only — Windows has no process-group signal. #18875 and this PR remove an interpreter and its start-up cost, but they do not change the orphan class; the structural fix is a tree kill / Job object in the agent's hook runner. Worth not closing orphan reports on the strength of the direct shape alone.

Separately, the null return is silent — a declined path slides into the encoded launcher with nothing logged, which is how #18905 shipped inert for spaced profiles without anyone noticing. A log line there is the change that would have caught this class of bug on its own; I left it out to keep this PR to one thing, but happy to add it.

🤖 Generated with Claude Code

marcdhansen and others added 2 commits September 7, 2026 00:54
… does

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 "<command>"` 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 "<command>"` (stablyai#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 <noreply@anthropic.com>
…tablyai#19187)

`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 stablyai#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\<first last>` path, marker-based so a failed dispatch masked by
`|| echo {}` cannot pass:

  invocation                                  quoted, script present
  bash -c (Claude Code's host, stablyai#18905)        PASS
  cmd /d /s /c "<cmd>", verbatim              PASS
  cmd /d /c <cmd>, 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 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 207d5c3a-f812-4ec0-9e2d-1afcd0413037

📥 Commits

Reviewing files that changed from the base of the PR and between ffff6ea and cda6ba9.

📒 Files selected for processing (5)
  • src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts
  • src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts
  • src/main/agent-hooks/windows-direct-cmd-hook-command.ts
  • src/main/agent-hooks/windows-hook-payload-delivery.test.ts
  • src/main/claude/hook-service.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Windows direct hook commands now accept quotable drive paths with spaces and always quote the normalized script path. Shell execution tests now use Node shell mode for cmd.exe and direct execution for Git Bash. Managed hook tests pass shell settings through to spawn and validate marker output. Claude hook tests cover quoted entries, spaced paths, fallback paths, and upgrades from existing unquoted entries.

Merge Risk: ⚪ Minimal · up to cda6b

Windows hooks can now run directly from profile paths containing spaces while paths with unsafe shell characters retain the existing fallback behavior. The change includes coverage for command execution and existing-hook upgrades, with no current merge-blocking risk identified.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: enabling direct Windows hooks for profile paths containing spaces.
Description check ✅ Passed The description is detailed and covers the problem, solution, linked issue, design decisions, testing, limitations, and AI disclosure. It does not explicitly use every template heading or include the …
Linked Issues check ✅ Passed The changes satisfy issue #19187 by allowing spaced Windows profile paths, always quoting the direct command path, preserving exclusions for unsafe characters, correcting shell-consumer test coverage,…
Out of Scope Changes check ✅ Passed The implementation and test changes remain focused on direct Windows hook registration for spaced profile paths, shell-compatible execution, fallback coverage, and upgrade behavior. No unrelated code …
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Spaced-profile fix — wrapWindowsDirectCmdHookCommand now quotes the emitted invocation unconditionally and gates on a new local WINDOWS_CMD_QUOTABLE_PATH class that is exactly WINDOWS_CMD_SAFE_PATH plus the space, so a C:\Users\First Last profile takes the direct .cmd hook instead of falling back to the encoded PowerShell launcher.
  • Quoting hazard scope — %, !, ^, &, (, ), quotes, and non-ASCII stay excluded (cmd expands %VAR%/!VAR! inside double quotes), and the widened class is kept local so wrapWindowsCmdHookCommand's bare argv[0] consumers are unaffected.
  • Test-harness correction — Windows cmd legs now spawn via shell: true (and /d /s /c) instead of a hand-rolled argv array, and the live both-hosts legs assert an ORCA_RAN marker that || echo {} cannot fake, so a spaced path can no longer pass without the hook executing.
  • Install-level gates + upgrade test — four tests now ask wrapWindowsDirectCmdHookCommand whether it serves the path (instead of WINDOWS_CMD_SAFE_PATH), and a new upgrade test pins that an existing unquoted entry is replaced by a single quoted entry with no duplicate.
  • Fallback repoint — the encoded-launcher fallback test moved from a spaced path to a %-path, matching what quoting genuinely cannot rescue.

The character-class widening is exactly one character (space), the unconditional-quoting decision keeps the emitted shape deterministic, and the upgrade path is exercised against real production sweep logic (createManagedCommandMatcher matches both quoted and unquoted entries). The author's measured exception (spawn('cmd.exe', ['/d','/c', command])) is documented as a non-consumer path, consistent with the gitBashAvailable gate on the direct command.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor

Thanks @marcdhansen! The spaced-profile fix landed via #33364 (credited with Co-authored-by). A quoted path breaks when Claude falls back to PowerShell to run hooks, so it registers Claude's exec form ({command, args}) instead. Closing as superseded.

nwparker added a commit that referenced this pull request Oct 25, 2026
…#33364)

Windows Claude hooks for profile paths with a space register in Claude's exec form (orca-agent-hook.exe + args) instead of the slow encoded-PowerShell fallback (~650ms → ~15ms per event); the script path in args lets older Orca builds recognise and replace the entry. Older Claude keeps the PowerShell launcher. Fixes #19187. Supersedes #19255.

Co-authored-by: marcdhansen <7607160+marcdhansen@users.noreply.github.com>
@nwparker nwparker closed this Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants