Skip to content

fix(grok): stop SessionStart orca-status hook hanging for 10s - #20090

Merged
nwparker merged 2 commits into
stablyai:mainfrom
bjornrun:fix/grok-session-start-hook-timeout
Sep 14, 2026
Merged

nwparker merged 2 commits into
stablyai:mainfrom
bjornrun:fix/grok-session-start-hook-timeout

Conversation

@bjornrun

@bjornrun bjornrun commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

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

  • POSIX hook payload capture reads stdin with a small Python program using json.JSONDecoder().raw_decode, returning the moment a complete JSON value has arrived, instead of cat-ing to an EOF that never comes.
  • Decoding is incremental (codecs.getincrementaldecoder("utf-8")("replace") held across reads), so a multi-byte character split across two os.read calls cannot raise.
  • The whole program is guarded so a non-zero exit implies stdin was never read — which is what makes the python3 || python || cat fallback chain sound.
  • The payload is emitted byte-for-byte via os.write (no re-serialisation, no locale-dependent stdout encoder).
  • Two separate timeouts: 5s for the writer's first byte, 1.5s of idle thereafter.
  • New regression tests: posix-hook-json-stdin-reader.test.ts and grok-hook-stdin-no-eof.test.ts.

Why

Reproduced: printf '{"hook_event_name":"session_start"}' | grok-hook.sh is fine when stdin is closed, but writing the same JSON and not closing stdin leaves payload=$(cat) blocked until Grok kills the hook at timeout: 10. PreToolUse often closes stdin; SessionStart does not.

Confirmed against the pre-change reader — every case hangs until killed:

ascii / stdin open               exit=null  12004ms  KILLED stdout=""
CJK+emoji byte-by-byte / open    exit=null  12004ms  KILLED stdout=""
CJK mid-char / stdin CLOSED      exit=0     13ms     stdout="{...\"cwd\":\"/漢字\"}"
slow writer 2.5s / open          exit=null  12002ms  KILLED stdout=""

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 the except caught only json.JSONDecodeError. UnicodeDecodeError is a ValueError but not a JSONDecodeError, so a multi-byte character straddling two reads killed the interpreter — which fell through to cat and reinstated the exact 10s hang this PR exists to remove:

BEFORE                                                          AFTER
ascii / stdin open               exit=0    319ms   "{...}"      exit=0  62ms   "{...}"
CJK+emoji byte-by-byte / open    exit=null 12009ms KILLED  <--  exit=0  387ms  "{...\"cwd\":\"/tmp/漢字\",\"tool\":\"🚀\"}"
CJK mid-char, 2 chunks / open    exit=0    76ms    rewritten<-- exit=0  41ms   "{...\"cwd\":\"/漢字\"}"
invalid UTF-8 byte / open        exit=null 12006ms KILLED  <--  exit=0  32ms   "{\"a\":\"�\"}"  (correct `replace`)
leading newline / open           exit=0    1576ms  idle-path    exit=0  32ms   "{...}"
slow writer 2.5s / open          exit=0    1574ms  DROPPED <--  exit=0  2504ms "{...}"

Input handling. The python3 || python || cat chain has an unstated invariant: a reader that already consumed bytes cannot be retried. python3 crashed after reading, and cat resumed mid-stream:

BEFORE: exit=0 809ms captured=4B      written=200058B  parseable JSON: false  head: "��\"}"
AFTER:  exit=0 417ms captured=200057B written=200058B  parseable JSON: true

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.ts was failing on the rebased head — two 10s timeouts. Root cause, measured:

real HOME                        72ms
HOME=/home/dev (nonexistent)   6375ms     <-- on its own overruns Grok's 10s budget
HOME unset                       54ms

macOS ships /usr/bin/python3 as 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 the payload=$(...) subshell, so the hook's own HOME is untouched.

Linked Issue

Fixes the user-visible:

session_start hook (global/orca-status) failed, ignored: timed out after 10000ms

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

  • I manually tested these changes locally
  • Automated tests added/updated
  • pnpm typecheck — exit 0
  • oxlint — exit 0; pnpm run check:code-quality:changed — 0 new findings
  • vitest src/main/agent-hooks src/main/grok — 95 files, 951 passed / 27 skipped; 11 further agent-hook dirs — 2892 passed
  • Python 2.7.18 (docker) python leg — {"cwd":"/tmp/漢字","t":"🚀"} rc=0
  • Full CI green — 22/22, including managed hooks on Node 18, e2e / localhost SSH terminal and hooks, and package (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

  • Not applicable — copies no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Cross-platform: POSIX hook only. Windows path untouched — it already uses the missing-env early exit from [Bug]: Codex managed hook leaves persistent cmd.exe windows outside Orca on Windows #11549 and 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.
  • SSH/remote: same generated script via installRemote, covered by the lifecycle matrix and the localhost SSH terminal and hooks e2e job. The installer content-compares and atomically rewrites, so existing installs upgrade automatically.
  • Remote wire: no RPC params, no stream opcodes. The payload is now byte-identical to what the agent sent — strictly closer to the original cat behaviour than the first version of this fix was.
  • Transcript requirement: does not apply. This reads a hook's stdin pipe and matches nothing against terminal output; no readiness detection is touched.

Residual risk

  1. Still one Python spawn per hook event (~30–60ms warm); Grok hooks fire on every tool use.
  2. Hosts with neither python3 nor python fall back to cat and keep the 10s hang — unchanged, but not fixed for them.
  3. The 1.5s idle timeout can truncate a non-JSON payload whose writer stalls >1.5s with stdin held open. JSON is unaffected — chunks reset the timer and completion is exact.
  4. The python 2.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 main and 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.

⚠️ Anyone pushing here: bare pnpm format reformats the whole repo with a different oxfmt result than what is checked in.

@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The 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 0c8b5

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the Grok hook hang and the 10-second timeout that this pull request fixes.
Description check ✅ Passed The description is complete and directly explains the problem, implementation, rationale, testing, platform scope, residual risks, and review considerations. It includes the required visual-proof stat…
  • 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.

@coderabbitai coderabbitai 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.

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.ts
  • src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts
  • src/main/grok/grok-hook-script.ts
  • src/main/grok/grok-hook-stdin-no-eof.test.ts
  • src/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"))'

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.

🩺 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.

@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 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 — buildPosixHookPayloadCapture gains an optional stdinReader, and Grok now captures its payload with a Python raw_decode reader instead of cat, so it exits as soon as one JSON object is complete rather than waiting for EOF.
  • Regression test — grok-hook-stdin-no-eof.test.ts writes session_start JSON and keeps stdin open, asserting the hook exits 0 in under 1.5s; the plain cat reader would hang and fail this.
  • Lifecycle/service test updates — the cross-agent lifecycle test and hook-service.test.ts assert the JSON reader is the one wired into the generated script.

ℹ️ Nitpicks

  • The 1.5s select ceiling means a payload written more than 1.5s after spawn (or in chunks gapped >1.5s) is silently truncated, where cat waited indefinitely. Fine for the write-immediately SessionStart contract, but worth a sentence in the Why: comment so the timeout reads as load-bearing rather than a guard against empty stdin.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

bjornrun and others added 2 commits September 14, 2026 00:56
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.
@nwparker
nwparker force-pushed the fix/grok-session-start-hook-timeout branch from f6d248e to 0c8b526 Compare September 14, 2026 07:58
@nwparker

Copy link
Copy Markdown
Contributor

Picked this up @bjornrun — rebased onto main (539d4d1f32b), your commit preserved, fix added on top as 0c8b526.

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 holds

Grok's SessionStart writes one JSON object and then waits for the hook to exit without closing stdin, so payload=$(cat) waits for an EOF that never comes. Confirmed against the pre-PR reader — every case hangs until Grok's timeout: 10 kills it:

ascii / stdin open               exit=null  12004ms  KILLED stdout=""
CJK+emoji byte-by-byte / open    exit=null  12004ms  KILLED stdout=""
CJK mid-char / stdin CLOSED      exit=0     13ms     stdout="{...\"cwd\":\"/漢字\"}"
slow writer 2.5s / open          exit=null  12002ms  KILLED stdout=""

Split UTF-8: reproduced, and it was worse than "corruption"

b.decode() is strict and was re-run over the whole buffer each chunk, while the except caught only json.JSONDecodeError. UnicodeDecodeError is a ValueError but not a JSONDecodeError, so a multi-byte character straddling two os.read calls killed the interpreter — which dropped through to cat and reinstated the exact 10s hang this PR exists to remove:

BEFORE (PR as submitted)
ascii / stdin open               exit=0     319ms    stdout="{...}"
CJK+emoji byte-by-byte / open    exit=null  12009ms  KILLED               <-- hang
CJK mid-char, 2 chunks / open    exit=0     76ms     "...\"/\\u6f22\\u5b57\"}"  <-- payload rewritten
invalid UTF-8 byte / open        exit=null  12006ms  KILLED               <-- hang
slow writer 2.5s / open          exit=0     1574ms   stdout=""            <-- payload DROPPED

AFTER
CJK+emoji byte-by-byte / open    exit=0     387ms    "{...\"cwd\":\"/tmp/漢字\",\"tool\":\"🚀\"}"
CJK mid-char, 2 chunks / open    exit=0     41ms     "{...\"cwd\":\"/漢字\"}"
invalid UTF-8 byte / open        exit=0     32ms     "{\"a\":\"�\"}"  (correct `replace`)
slow writer 2.5s / open          exit=0     2504ms   "{...}"

Input handling: reproduced

The python3 || python || cat chain has an invariant nobody stated: a reader that already consumed bytes cannot be retried. python3 crashed after reading, and cat resumed mid-stream:

BEFORE: exit=0 809ms captured=4B written=200058B   parseable JSON: false   head: "��\"}"
AFTER:  exit=0 417ms captured=200057B written=200058B  parseable JSON: true

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 || chain sound in the first place. Also fixed: the 1.5s timeout applied to the first byte, silently dropping payloads from a writer that was merely late; first-byte wait (5s) is now separate from idle wait (1.5s).

Separate bug: this branch was red on main's existing suite

managed-hook-stdin-lifecycle.test.ts was failing on the rebased head — two 10s timeouts. Root cause, measured:

real HOME                        72ms
HOME=/home/dev (nonexistent)   6375ms     <-- on its own overruns Grok's 10s budget
HOME unset                       54ms

macOS ships /usr/bin/python3 as an Xcode stub that re-runs its full tool lookup whenever it can't reach a cache under $HOME. Fixed with { [ -d "${HOME:-}" ] || unset HOME; } inside the capture subshell → ~95ms. That also explains the apparent flakiness: 6.6s + overhead only crosses 10s under load.

Verification

pnpm tc                              -> exit 0
pnpm exec oxlint                     -> exit 0
pnpm run check:code-quality:changed  -> 0 new findings (6 files)
vitest src/main/agent-hooks src/main/grok -> 95 files, 951 passed | 27 skipped
vitest (11 other agent-hook dirs)         -> 2892 passed
python 2.7.18 (docker) `python` leg       -> {"cwd":"/tmp/漢字","t":"🚀"} rc=0

New tests fail against the submitted decoder and pass against the fix (5 failed → 9 passed). Two unrelated failures in the wide sweep: claude-structured-real-cli.test.ts fails identically on origin/main (pre-existing, needs the real CLI), and codex-tui-resume-real-binary.integration.test.ts is flaky under parallel load (temp-dir collision), passing in isolation.

Residual risk

  1. Still one Python spawn per Grok hook event (~30–60ms warm); Grok hooks fire on every tool use.
  2. Hosts with neither python3 nor python still fall back to cat and keep the 10s hang — unchanged, but not fixed for them.
  3. The 1.5s idle timeout can truncate a non-JSON payload whose writer stalls >1.5s with stdin held open. JSON is unaffected — chunks reset the timer and completion is exact.
  4. The python 2.x leg is verified by a docker run, not by CI.

The lever for lower risk is (1)/(2) — 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. I deliberately didn't guess it.

Note for anyone pushing here: bare pnpm format reformats the whole repo with a different oxfmt result than what's checked in. I reverted the 3 unrelated files it touched.

@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

  • Incremental UTF-8 decoding in the JSON reader — replaced per-chunk strict bytes.decode() plus json.dump re-serialisation with codecs.getincrementaldecoder("utf-8")("replace") and a raw os.write of 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_decode so 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.ts runs 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.

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

@coderabbitai coderabbitai 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.

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.ts
  • src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts
  • src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts
  • src/main/grok/grok-hook-script.ts
  • src/main/grok/grok-hook-stdin-no-eof.test.ts
  • src/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', () => {

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.

🩺 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 nwparker 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.

Verified: rebased, evidence-backed, full CI green. Approving.

@nwparker
nwparker merged commit 01f8aa8 into stablyai:main Sep 14, 2026
34 checks passed
GhostFlying pushed a commit to GhostFlying/orca that referenced this pull request Sep 15, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants