Repository navigation
fix(grok): stop the Windows status hook from spawning two interpreters per event - #15595
Conversation
…s per event (#14828) Grok runs a hook `command` containing a space as `pwsh -Command <cmd>`. Orca registered the encoded PowerShell launcher, whose command line is full of spaces, so every status event walked grok.exe -> pwsh.exe -> powershell.exe -> cmd.exe -> curl.exe before reaching a script whose entire job is one loopback POST. Measured against Grok 1.0.5's own dispatcher on Windows 11, that is 518-719ms per event (mean 607ms). The same script registered as its bare path is spawned directly as `grok.exe -> cmd.exe` and costs 43-213ms (mean 114ms). Orca installs nine Grok events, and a single one-tool-call prompt dispatches roughly ten of them, so this is the difference between a hook chain that is continuously resident during a turn and one that is not. It is also how long the console the agent allocates for a hook can stay on screen, which is the mechanism #15520 fixed for Antigravity -- Grok was worse, paying two interpreters rather than one. Use the shared `wrapWindowsCmdHookCommand`, the same registration Codex, Devin and Antigravity already use (#8430). A profile path that is not cmd-safe still falls back to the encoded launcher, so #6078 stays covered. Tradeoff carried over from those agents: a bare path cannot hold the launcher's missing-script guard, so a deleted script surfaces as a per-event `command not found` in Grok's log rather than a silent stdin drain. Verified that Grok fails open there -- the tool still runs, including on PreToolUse, which Grok declares a blocking event. Verified end to end against the real Grok CLI: 9/9 status posts delivered with full payloads through the bare path, and 12/12 in a controlled A/B spawning both shapes the way Grok does. Also confirmed Grok creates hook processes with CREATE_NO_WINDOW rather than DETACHED_PROCESS, which is the mode where a bare .cmd would have been worse than the launcher.
📝 WalkthroughWalkthroughWindows Grok hooks now use a cmd-safe command wrapper, with encoded PowerShell fallback for paths that contain spaces. POSIX command handling remains unchanged. A test helper exposes generated managed commands. Tests now cover launcher generation, managed event installation, stale launcher replacement, retired event cleanup, user hook preservation, and platform-independent command matching. Merge Risk: 🔵 Low · up to The Windows hook change is narrowly scoped and improves launch performance, but the upgrade-path tests can accept unrelated commands because they match by substring rather than exact command identity. This is a bounded test-correctness risk that should receive owner follow-up. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/grok/hook-service.ts (1)
105-113: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten the explanatory comments.
Keep each comment to the non-obvious rationale only.
src/main/grok/hook-service.ts#L105-L113: reduce the launcher-chain and benchmark explanation to one concise reason.src/main/grok/windows-hook-launcher-chain.test.ts#L1-L6: remove benchmark and dispatch-detail commentary that the test name does not need.src/main/grok/hook-service.test.ts#L28-L30: reduce the fallback description to one line.As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3dfa8ba2-6df9-4811-9040-efb5d562c1c1
📒 Files selected for processing (3)
src/main/grok/hook-service.test.tssrc/main/grok/hook-service.tssrc/main/grok/windows-hook-launcher-chain.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| function registersManagedGrokScript(command: string): boolean { | ||
| return command.includes(GROK_SCRIPT_FILE_NAME) || WINDOWS_POWERSHELL_LAUNCHER.test(command) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Match the expected managed command exactly.
command.includes(GROK_SCRIPT_FILE_NAME) accepts user commands such as echo grok-hook.sh. WINDOWS_POWERSHELL_LAUNCHER also accepts unrelated encoded PowerShell hooks. Lines 263 and 372 can pass when no managed hook is installed. Derive the expected command from the known script path, then compare commands for equality.
|
Thanks for taking this on. Closing #15506 in favor of this PR. |
…s per event (stablyai#15595) (cherry picked from commit 8b60a1e)
ELI5
On Windows, Grok runs any hook command that contains a space by handing it to PowerShell 7
(
pwsh -Command …). Orca registered its Grok status hook as an encodedpowershell.exe …command line, which is full of spaces — so every status event started two interpreters
before it reached a script whose whole job is one loopback POST:
Orca now registers the script's own path, the same way Codex, Devin and Antigravity hooks are
already registered. Grok spawns it directly, the two interpreters disappear, and the status
posts are byte-for-byte the same.
What Changed
src/main/grok/hook-service.ts— the Windows managed command comes from the sharedwrapWindowsCmdHookCommand(scriptPath)instead ofwrapWindowsHookCommand(scriptPath). Thathelper returns the bare path when it is cmd-safe and otherwise falls back to the same encoded
PowerShell launcher as before, so [Bug]: Codex hooks fail on Windows when user path contains spaces #6078 (space in the profile path) stays covered.
src/main/grok/windows-hook-launcher-chain.test.ts— new. Pins the launch shape: theregistered command is the script path itself, names a real file, contains no whitespace (the
sole trigger for Grok's
pwshwrapper), and carries no interpreter. Also covers the upgradesweep and the non-cmd-safe fallback. Split into synthetic-path cases that run on every CI
leg and install-based cases gated to win32 — only
process.platformcan be mocked, notpath.join, so a real install on a POSIX runner yields a/-separated path that routes tothe [Bug]: Codex hooks fail on Windows when user path contains spaces #6078 fallback by design (same gating and reason as
installer-utils.test.ts:692).src/main/grok/hook-service.ts— smallgetManagedCommandForTestsseam, so theplatform-independent cases assert the decision this PR makes rather than the shared helper.
src/main/grok/hook-service.test.ts— the two assertions that hard-coded the PowerShelllauncher now accept either registration; which branch applies is pinned by the new file.
No change to the script body, the POSIX script, the remote/SSH installer, the WSL relay path,
or any other agent.
Why
#14828reports a console flash and focus steal on every Grok tool call. Three reportersposted the same process tree —
grok.exe -> pwsh.exe/powershell.exe -> cmd.exe. I reproducedthat tree exactly by instrumenting a managed hook to log its own ancestor chain while the real
Grok CLI ran in a real ConPTY:
Grok's own debug log names the mechanism:
xai_grok_config::shell: Windows shell: pwsh.Measured with Grok 1.0.5's own dispatcher timing, both variants registered in the same session,
running a byte-identical copy of the real
grok-hook.cmdagainst a live listener:.cmdpathA controlled A/B outside Grok (12 spawns each, both delivering 12/12 posts) reproduces the
ratio: 215 ms vs 49 ms.
Orca installs nine Grok events, and one single-tool-call prompt dispatched ten of them. This is
the mechanism the merged Antigravity fix (#15520) already established for this class of bug —
Orca cannot suppress the console the agent allocates for a hook, but it controls how long that
console lives. Grok was the worse case, paying two interpreters rather than one.
What I could not reproduce
I could not make a visible console window appear from the Grok hook path on this hardware
(Windows 11 26200, Orca
main, Grok 1.0.5), in either shape, across ~30 real hook events with a5 ms window sampler running. The reason is measurable: Grok creates hook processes with
CREATE_NO_WINDOW. Verified by discriminating the flags from inside a hook —CREATE_NO_WINDOWconsole=NONEDETACHED_PROCESSconsole=2361644 visible=True class=PseudoConsoleWindowGrok's hooks report
console=NONEat every level of the chain, so they have a console with nowindow and every child inherits it. This is also the check that says the change is safe:
DETACHED_PROCESSis the one mode where a bare.cmdwould be worse than the PowerShelllauncher (cmd.exe must allocate a console; PowerShell does not), and Grok demonstrably does not
use it.
So I am not claiming this makes a window I observed go away. I am claiming it removes the
interpreter chain that determines how long such a window can exist, on the same reasoning and
in the same shape as the fix already merged for Antigravity.
Community PRs
Two open PRs target this issue. I took neither, but both contributed to the diagnosis:
commandthatcontains a space as
pwsh -Command …". That is the load-bearing insight here and myinstrumentation confirms it. Their fix ships a new GUI-subsystem
orca-grok-hook.exeplus anative build step and packaging changes; registering the existing
.cmdremoves the samepwshwrapper with no new binary in the shipped build.keeps the encoded PowerShell wrapper and replaces
& $scriptPathwithProcessStartInfo+CreateNoWindow, which leaves both interpreters and the ~607 ms in place. Their statedpremise — that the
.cmdhas no console to inherit so Windows creates one — is theDETACHED_PROCESScase above, which I could not reproduce under Grok's actual flags.Not this issue, but found while looking
node-pty's ConPTY teardown forks
conpty_console_list_agentwith nowindowsHide(
windowsPtyAgent.js:184). From a host with no console that pops a focus-stealing WindowsTerminal window on every
kill()— reproduced 3/3, with 0/2 on natural exit. Orca is notaffected because it pins
useConptyDll: true, which skips that branch entirely (verified 0/3).Recording it on the issue rather than changing anything here.
Linked Issue
Fixes #14828
Visual Proof
N/Afor rendered Orca UI — no Orca view, layout, or in-app control changes. The subject is anOS console belonging to the agent's own process tree, so the evidence is process-level and
lives in Why: measured ancestor chains, Grok's own dispatcher timings, and the creation-flag
discriminator.
Testing
src/main/grok/— 29 passed. Verified as a real guard, not a tautology: against thepre-fix code the new suite fails and names the defect (
expected 'C:/WINDOWS/…powershell.exe -NoProfile…' to be 'C:\…\grok-hook.cmd'), including thesynthetic-path case that runs on the POSIX legs.
src/main/agent-hooks/+src/main/grok/— 649 passed, 6 failures that are pre-existing onthis box: 3 ×
installer-utilssymlink, 2 × Claudemanaged-hook-stdin-lifecycle, 1 ×Claude
windows-hook-payload-delivery. Confirmed identical on a cleanHEADworktree — same6, none in
src/main/grok/, none touching this change. (Same set fix(agent-hooks): stop Antigravity's Windows hook from spawning PowerShell on every event #15520 recorded.)pnpm typecheckclean.oxlint --deny-warningsclean.oxfmt --checkclean on the contentGit stores (the local checkout is CRLF, which flags files this PR does not touch).
Live Windows, real Grok CLI: installed the fixed shape and ran a two-tool-call prompt —
9/9 status posts delivered with full payloads (607–1538 bytes), hook events completing in
43–121 ms.
Missing-script behaviour (the one contract the encoded launcher provided and a bare path
cannot): registered a nonexistent script and ran a tool call. Grok fails open — logs
hook failed … hook_failure=command not found: …atelapsed_ms=0and the tool stillruns, including for
pre_tool_use, which Grok declares a blocking event. Same postureCodex/Devin/Antigravity already have, and
install()writes the script and the configtogether.
I manually tested these changes locally
Automated tests added/updated
Review
Ran
/code-review highover the branch. It raised three findings; all are addressed:HIGH — the cmd-safe cases would fail on the Linux CI shard. Correct, and I had reached
the same conclusion independently: only
process.platformis mockable, sopath.joinstillproduces
/tmp/…, which is not cmd-safe and takes the fallback. Restructured as described inWhat Changed.
MEDIUM — no cross-platform pin on the launch shape. Fixed by the
getManagedCommandForTestsseam; the pin now runs on every leg and is verified to fail against the pre-fix code.
LOW — the bare path drops the launcher's missing-script guard. Real, and now stated in the
code comment, the commit message, and Testing above, with the fail-open behaviour measured
rather than assumed.
Upgrade path:
installManagedAgentHookscallsinstall()unconditionally behind the CLIpresence gate, and
createManagedCommandMatcherdecodes encoded commands before matching, soan existing
-EncodedCommandentry is swept and replaced — including in retired events.Covered by a test.
Security: the registered value is an absolute path under the user's own profile,
constrained by
WINDOWS_CMD_SAFE_PATHand spawned as argv[0], not through a shell, so there isno command line to quote or inject into. No secret moves onto a command line. No new binary,
dependency, install hook, or network sink.
Cross-platform: POSIX branch untouched.
installRemotestill writes the POSIX.shoverSFTP; WSL uses the POSIX script via the relay. Windows validated on hardware.
Known gap (unchanged by this PR, worth stating): a profile path that is not cmd-safe —
spaces, or non-ASCII characters — still takes the encoded-launcher fallback and keeps the old
cost. That is the shared helper's existing behaviour for Codex/Devin/Antigravity too;
widening the character class would change those three agents and is deliberately out of scope.
Performance: strictly better — two fewer processes and ~490 ms less per hook event, ~10
events per tool-calling turn.
Provider neutrality / UI / mobile / persisted state / wire format: untouched.
Agent skill upstream boundary
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)