Repository navigation
fix(grok): stop SessionStart orca-status hook hanging for 10s - #20090
Conversation
📝 WalkthroughWalkthroughThe change adds a POSIX JSON stdin reader that decodes one object without waiting for EOF. Payload capture can now receive a custom stdin reader. The Grok hook uses the JSON reader for exit payloads. Tests verify reader ordering, generated script output, UTF-8 handling, timeout behavior, and Grok hook completion when stdin remains open. Priority: ➖ Normal Merge Risk: 🔵 Low · up to This change fixes a real 10-second hang in the Grok status hook when stdin stays open, using a safer JSON-aware reader that has been shown to handle split multibyte characters correctly. The one remaining gap is limited to test infrastructure: on a CI machine without a Python interpreter, the new regression test could itself time out rather than being skipped, which is a low-risk, easily fixed test-hygiene issue rather than a production defect. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 666aa27c-78d7-43c7-9067-99dd034e6f65
📥 Commits
Reviewing files that changed from the base of the PR and between 94c2f96 and f6d248ecbc5840a984d66010915723eb12c07379.
📒 Files selected for processing (5)
src/main/agent-hooks/hook-stdin-contract.tssrc/main/agent-hooks/managed-hook-stdin-lifecycle.test.tssrc/main/grok/grok-hook-script.tssrc/main/grok/grok-hook-stdin-no-eof.test.tssrc/main/grok/hook-service.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| // returns as soon as the object is complete. Trailing-EOF / non-JSON still | ||
| // falls through so lifecycle tests that close stdin keep working. | ||
| const POSIX_HOOK_JSON_STDIN_PYTHON = | ||
| 'import json,os,select,sys;d=sys.stdin.buffer;b=b""\nwhile 1:\n r,_,_=select.select([d],[],[],1.5)\n if not r:break\n c=os.read(d.fileno(),65536)\n if not c:break\n b+=c\n try:\n o,_=json.JSONDecoder().raw_decode(b.decode());json.dump(o,sys.stdout,separators=(",",":"));raise SystemExit\n except json.JSONDecodeError:pass\nsys.stdout.write(b.decode("utf-8","replace"))' |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Handle partial UTF-8 input in POSIX_HOOK_JSON_STDIN_READER.
When python3 reads a multibyte character split across os.read calls, b.decode() raises UnicodeDecodeError. The python fallback then receives the remaining continuation bytes and can fail again. The final cat fallback waits for EOF while stdin remains open. GrokHookService captures this command output, so the Grok SessionStart hook can block until its 10-second timeout.
Catch UnicodeDecodeError and continue reading, or use an incremental UTF-8 decoder. Add a regression case that splits a multibyte character across writes while stdin remains open.
There was a problem hiding this comment.
ℹ️ No critical issues — the fix is correct and the regression test genuinely guards the SessionStart deadlock. One robustness edge below.
Reviewed changes
- JSON stdin reader for the POSIX Grok hook —
buildPosixHookPayloadCapturegains an optionalstdinReader, and Grok now captures its payload with a Pythonraw_decodereader instead ofcat, so it exits as soon as one JSON object is complete rather than waiting for EOF. - Regression test —
grok-hook-stdin-no-eof.test.tswritessession_startJSON and keeps stdin open, asserting the hook exits 0 in under 1.5s; the plaincatreader would hang and fail this. - Lifecycle/service test updates — the cross-agent lifecycle test and
hook-service.test.tsassert the JSON reader is the one wired into the generated script.
ℹ️ Nitpicks
- The 1.5s
selectceiling means a payload written more than 1.5s after spawn (or in chunks gapped >1.5s) is silently truncated, wherecatwaited indefinitely. Fine for the write-immediatelySessionStartcontract, but worth a sentence in theWhy:comment so the timeout reads as load-bearing rather than a guard against empty stdin.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Grok writes one JSON hook payload and waits for the process to exit without closing stdin. The POSIX hook used `cat`, which waits for EOF, so SessionStart deadlocked until Grok's 10s timeout: session_start hook (global/orca-status) failed, ignored: timed out after 10000ms Read one JSON object with raw_decode instead; return as soon as the object is complete. Fall back to cat when Python is missing.
The JSON stdin reader strict-decoded the whole accumulated buffer after every read and caught only json.JSONDecodeError. A multi-byte character split across two os.read calls therefore raised UnicodeDecodeError, which is a ValueError but not a JSONDecodeError, so the interpreter died — after consuming stdin. The `python3 || python || cat` chain then handed the next reader a truncated stream, and `cat` blocked on a pipe the caller never closes, reinstating the exact 10s SessionStart timeout this reader exists to avoid. Measured: a CJK+emoji payload written byte by byte hung until it was killed; a 200KB payload split mid-character arrived as 4 bytes. Hold the decoder across reads, treat any ValueError as "not complete yet", and guard the whole program so a non-zero exit implies stdin was never read — only then is the `||` fallback safe. Emit the object's own text rather than re-serialising it, which was rewriting non-ASCII as \uXXXX. Skip leading whitespace, which raw_decode does not. Separate the first-byte wait (5s) from the idle wait (1.5s) so a writer that is merely late is no longer dropped. Also unset a HOME that does not exist before spawning the interpreter: macOS resolves /usr/bin/python3 through an Xcode stub that re-runs its whole tool lookup without a reachable cache, costing 6.6s per spawn and overrunning Grok's budget on its own. This is what made the existing large-payload and empty-PATH lifecycle cases fail. The Python program now lives in a shell variable instead of being inlined twice, which halves the generated script and keeps it readable.
f6d248e to
0c8b526
Compare
|
Picked this up @bjornrun — rebased onto Your diagnosis was right, and the reader compatibility concerns raised in review were also right. Both are now settled with measurements rather than argument. The premise holdsGrok's Split UTF-8: reproduced, and it was worse than "corruption"
Input handling: reproducedThe 200,058 bytes in, 4 bytes out — and POSTed to the hook server. The whole program is now guarded so non-zero exit ⟹ stdin was never read, which is what makes the Separate bug: this branch was red on main's existing suite
macOS ships VerificationNew tests fail against the submitted decoder and pass against the fix (5 failed → 9 passed). Two unrelated failures in the wide sweep: Residual risk
The lever for lower risk is (1)/(2) — dropping the interpreter for a Note for anyone pushing here: bare |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Incremental UTF-8 decoding in the JSON reader — replaced per-chunk strict
bytes.decode()plusjson.dumpre-serialisation withcodecs.getincrementaldecoder("utf-8")("replace")and a rawos.writeof the captured text, so a split or invalid multi-byte payload neither raises nor gets rewritten. - Separate first-byte and idle timeouts — the reader now waits up to 5s for the writer's first byte, then switches to the 1.5s silence timeout, and strips leading whitespace before
raw_decodeso a padded payload returns promptly. - Reader prelude variable and HOME guard — the Python program is hoisted into
$orca_hook_json_stdin_py, set by a prelude emitted above the capture line, and a macOS Xcode-python HOME guard was added. - New executable reader suite —
posix-hook-json-stdin-reader.test.tsruns the embedded shell/Python reader end to end (split multibyte, no partial-consumption fallback, unchanged emission, whitespace, slow first byte, non-JSON EOF, missing HOME, clean stderr). - Regression and lifecycle test updates — the no-EOF test gained a split-multibyte case and the generated-script tests assert the prelude precedes the capture line.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 725434ae-e77c-4e4a-ac40-8cf19e27aaaf
📥 Commits
Reviewing files that changed from the base of the PR and between f6d248ecbc5840a984d66010915723eb12c07379 and 0c8b526.
📒 Files selected for processing (6)
src/main/agent-hooks/hook-stdin-contract.tssrc/main/agent-hooks/managed-hook-stdin-lifecycle.test.tssrc/main/agent-hooks/posix-hook-json-stdin-reader.test.tssrc/main/grok/grok-hook-script.tssrc/main/grok/grok-hook-stdin-no-eof.test.tssrc/main/grok/hook-service.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/grok/grok-hook-script.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| const GROK_HOOK_TIMEOUT_MS = 10_000 | ||
| const SESSION_START_BUDGET_MS = 1_500 | ||
|
|
||
| describe.skipIf(process.platform === 'win32')('Grok POSIX hook stdin without EOF', () => { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Skip this suite when Python is unavailable.
This suite skips only on Windows. On a POSIX host without python3 or python, the reader falls back to cat. The test leaves stdin open, so runHookWithoutEof waits 10 seconds and fails.
Use the same Python availability check as src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts.
🧰 Tools
🪛 ast-grep (0.45.3)
[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawn } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').
(detect-child-process-typescript)
nwparker
left a comment
There was a problem hiding this comment.
Verified: rebased, evidence-backed, full CI green. Approving.
…ai#20090) * fix(grok): stop SessionStart orca-status hook hanging for 10s Grok writes one JSON hook payload and waits for the process to exit without closing stdin. The POSIX hook used `cat`, which waits for EOF, so SessionStart deadlocked until Grok's 10s timeout: session_start hook (global/orca-status) failed, ignored: timed out after 10000ms Read one JSON object with raw_decode instead; return as soon as the object is complete. Fall back to cat when Python is missing. * fix(grok): decode the hook payload incrementally instead of per chunk The JSON stdin reader strict-decoded the whole accumulated buffer after every read and caught only json.JSONDecodeError. A multi-byte character split across two os.read calls therefore raised UnicodeDecodeError, which is a ValueError but not a JSONDecodeError, so the interpreter died — after consuming stdin. The `python3 || python || cat` chain then handed the next reader a truncated stream, and `cat` blocked on a pipe the caller never closes, reinstating the exact 10s SessionStart timeout this reader exists to avoid. Measured: a CJK+emoji payload written byte by byte hung until it was killed; a 200KB payload split mid-character arrived as 4 bytes. Hold the decoder across reads, treat any ValueError as "not complete yet", and guard the whole program so a non-zero exit implies stdin was never read — only then is the `||` fallback safe. Emit the object's own text rather than re-serialising it, which was rewriting non-ASCII as \uXXXX. Skip leading whitespace, which raw_decode does not. Separate the first-byte wait (5s) from the idle wait (1.5s) so a writer that is merely late is no longer dropped. Also unset a HOME that does not exist before spawning the interpreter: macOS resolves /usr/bin/python3 through an Xcode stub that re-runs its whole tool lookup without a reachable cache, costing 6.6s per spawn and overrunning Grok's budget on its own. This is what made the existing large-payload and empty-PATH lifecycle cases fail. The Python program now lives in a shell variable instead of being inlined twice, which halves the generated script and keeps it readable. --------- Co-authored-by: Neil <[email protected]> (cherry picked from commit 01f8aa8)

ELI5
Grok tells Orca "session started" by running a small hook and sending it a JSON blob. Grok then waits for that hook to finish, but never closes the pipe. The hook was waiting for the pipe to close. They waited on each other until Grok gave up after 10 seconds and printed this warning.
The hook now stops as soon as it has a complete JSON object, so session start no longer times out.
What Changed
json.JSONDecoder().raw_decode, returning the moment a complete JSON value has arrived, instead ofcat-ing to an EOF that never comes.codecs.getincrementaldecoder("utf-8")("replace")held across reads), so a multi-byte character split across twoos.readcalls cannot raise.python3 || python || catfallback chain sound.os.write(no re-serialisation, no locale-dependent stdout encoder).posix-hook-json-stdin-reader.test.tsandgrok-hook-stdin-no-eof.test.ts.Why
Reproduced:
printf '{"hook_event_name":"session_start"}' | grok-hook.shis fine when stdin is closed, but writing the same JSON and not closing stdin leavespayload=$(cat)blocked until Grok kills the hook attimeout: 10. PreToolUse often closes stdin; SessionStart does not.Confirmed against the pre-change reader — every case hangs until killed:
Reader compatibility (raised in review, now fixed)
Review flagged split-UTF-8 and input-handling problems in the first version of this fix. Both were real. Reproduced and fixed:
Split UTF-8.
b.decode()was strict and re-run over the whole buffer each chunk, while theexceptcaught onlyjson.JSONDecodeError.UnicodeDecodeErroris aValueErrorbut not aJSONDecodeError, so a multi-byte character straddling two reads killed the interpreter — which fell through tocatand reinstated the exact 10s hang this PR exists to remove:Input handling. The
python3 || python || catchain has an unstated invariant: a reader that already consumed bytes cannot be retried. python3 crashed after reading, andcatresumed mid-stream:200,058 bytes in, 4 bytes out — and POSTed to the hook server. Also fixed: the 1.5s timeout applied to the first byte, silently dropping payloads from a writer that was merely late.
Separate bug this branch was carrying
managed-hook-stdin-lifecycle.test.tswas failing on the rebased head — two 10s timeouts. Root cause, measured:macOS ships
/usr/bin/python3as an Xcode stub that re-runs its full tool lookup whenever it cannot reach a cache under$HOME. Fixed with{ [ -d "${HOME:-}" ] || unset HOME; }inside the capture subshell → ~95ms. That also explains the apparent flakiness: 6.4s + overhead only crosses 10s under load. Safe to mutate — the reader only ever runs inside thepayload=$(...)subshell, so the hook's ownHOMEis untouched.Linked Issue
Fixes the user-visible:
Related stdin-ownership contract:
#11549(Windows already refused to read-to-EOF when the caller may not close stdin). POSIX Grok SessionStart is the same deadlock.Visual Proof
N/A — no UI chrome. The session-start warning in the Grok TUI goes away.
Testing
pnpm typecheck— exit 0oxlint— exit 0;pnpm run check:code-quality:changed— 0 new findingsvitest src/main/agent-hooks src/main/grok— 95 files, 951 passed / 27 skipped; 11 further agent-hook dirs — 2892 passedpythonleg —{"cwd":"/tmp/漢字","t":"🚀"}rc=0managed hooks on Node 18,e2e / localhost SSH terminal and hooks, andpackage (windows)New tests fail against the first version of the decoder and pass against the fix (5 failed → 9 passed), so they catch the regression rather than merely restating the implementation.
AI Disclosure
Original implementation with Grok 4.6 (xAI) in a local coding session. Maintainer follow-up with Claude Opus 5.
Agent skill upstream boundary
Notes
more.com. The AGENTS.md EDR note on per-operation interpreter spawning is Windows-scoped; the shell variable also removes a duplicated ~600-char command line.installRemote, covered by the lifecycle matrix and thelocalhost SSH terminal and hookse2e job. The installer content-compares and atomically rewrites, so existing installs upgrade automatically.catbehaviour than the first version of this fix was.Residual risk
python3norpythonfall back tocatand keep the 10s hang — unchanged, but not fixed for them.python2.x leg is verified by a docker run, not by CI.The lever for (1)/(2) is dropping the interpreter for a
read-builtin fast path, but that needs a captured Grok payload transcript to confirm the framing is single-line and newline-terminated. Deliberately not guessed.Maintainer note: rebased onto current
mainand extended by @nwparker — @bjornrun's original commit preserved. The diagnosis was correct; the follow-up commit fixes the incremental decoding, the fallback-chain invariant, the first-byte/idle timeout split, and the$HOME/Xcode-stub slowdown.pnpm formatreformats the whole repo with a different oxfmt result than what is checked in.