Skip to content

fix(agent-hooks): exit Windows hook guards instead of draining a foreign stdin - #12069

Closed
nwparker wants to merge 2 commits into
stablyai:mainfrom
nwparker:nwparker/fix-11549-windows-hook-process-leak
Closed

nwparker wants to merge 2 commits into
stablyai:mainfrom
nwparker:nwparker/fix-11549-windows-hook-process-leak

Conversation

@nwparker

@nwparker nwparker commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #11549

ELI5

On Windows, Orca installs little script files that AI coding tools run whenever something happens. Because those scripts are installed for the whole user account, tools launched outside Orca run them too.

Each script started by checking "did Orca launch me?" — and when the answer was no, instead of just quitting, it jumped to a cleanup step that waits for the caller to finish sending data. A caller that isn't Orca never signals it's done, so that wait never ended: the script and a helper program sat there forever, along with a black console window. A new pair piled up on every event. The worst offender was Claude's status line script, which gets re-run several times a second while Claude is typing.

The fix is: when the Orca environment is missing, exit immediately instead of waiting. The waiting step is kept only where something can still reach it and Orca really did send data — one script, plus the wrappers that take over when the shared script is missing.

Root cause

buildWindowsHookEnvironmentGuardLines() emitted all three missing-env guards as goto :orca_agent_hook_drain_stdin:

if "%ORCA_AGENT_HOOK_PORT%"=="" goto :orca_agent_hook_drain_stdin
if "%ORCA_AGENT_HOOK_TOKEN%"=="" goto :orca_agent_hook_drain_stdin
if "%ORCA_PANE_KEY%"=="" goto :orca_agent_hook_drain_stdin

The epilogue at that label is "%SystemRoot%\System32\more.com" >nul 2>nul + exit /b 0. more.com blocks until stdin reaches EOF.

The drain exists to honor the EPIPE contract from #8430 (c3ab805d12). That contract explicitly covered ordinary launches with no Orca environment — but it assumed every caller eventually closes stdin, and where that failed it relied on "the existing config-level timeout terminates the hook". A caller that is not Orca has no Orca timeout and need not ever close the pipe, so the hook wedges forever, leaking a cmd.exe / more.com pair and a visible console window per hook event.

statusline-script.ts carried the identical ORCA_PANE_KEY guard. It is the highest-frequency leak because Claude re-invokes the statusline several times a second while streaming a response.

Two further paths reproduced the same leak class and were not addressed by simply changing the shared guard:

  • claude-hook.cmd emitted its DEVIN_PROJECT_DIR skip as a goto to the drain before any Orca-env validation, so a Windows Devin process outside Orca reached more.com first.
  • Every Antigravity event wrapper runs the drain command directly when the shared antigravity-hook.cmd is missing, so a stale or partially-removed install invoked outside Orca kept the same hang primitive.

Fix

  • Missing Orca env exits immediately (exit /b 0) in the shared guard builder and the statusline script.
  • Claude's guard order is inverted. Emission is now endpoint refresh → Orca-env guards → Devin skip → curl post → exit /b 0 → epilogue. The Devin skip is therefore reachable only when Orca invoked the hook — exactly when a payload was written and stdin will be closed — which makes its drain legitimate rather than a hang. Moving the endpoint refresh ahead of the skip is a setlocal-scoped no-op. OpenClaude uses the same template without the Devin skip, so it gets no epilogue.
  • Antigravity event wrappers are guarded before their standalone drain, placed after the echo {} protocol reply so Antigravity never stalls parsing stdout. A stale wrapper invoked outside Orca now exits; an Orca-invoked one still drains.
  • The epilogue is no longer emitted where nothing can jump to it — removed from the antigravity, codex, command-code, cursor, devin, droid, gemini and grok scripts and from the statusline, kept in claude-hook.cmd. WINDOWS_HOOK_STDIN_DRAIN_COMMAND, installer-utils.ts and wrapWindowsGitBashHookCommand are untouched.
  • The rationale is corrected in source. The previous comment claimed fix(agent-hooks): drain stdin before hook script early exits so agents never hit EPIPE #8430 covered only Orca-invoked hooks. It did not. The honest framing, now in hook-stdin-contract.ts, is that fix(agent-hooks): drain stdin before hook script early exits so agents never hit EPIPE #8430's assumption — every caller eventually closes stdin — does not hold for a foreign caller, and a transient broken pipe is the cheaper of the two failures.

Proof

Each fix verified by reverting only that production change.

Antigravity wrapper guards:

AssertionError: antigravity-post-invocation.cmd Orca env guard: expected -1 to be greater than -1
 ❯ src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts:353:58

Devin-guard reorder:

AssertionError: claude Devin skip after Orca guards: expected 3 to be greater than 6
 ❯ src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts:333:71

Dead epilogue (restored in grok only):

AssertionError: grok-hook.cmd drain epilogue reachable: expected true to be false
 ❯ src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts:315:73

Dead epilogue in statusline:

AssertionError: expected '@echo off\r\nsetlocal\r\nif "%ORCA_PA…' not to contain 'orca_agent_hook_drain_stdin'
 ❯ src/main/claude/statusline-script.test.ts:104:24

Original missing-env guards, against main:

     × exits missing-Orca-env batch guards without entering the drain
     × exits without reading stdin when the pane key is missing

AssertionError: claude-hook.cmd port guard: expected '@echo off\r\nsetlocal\r\nif not "%DEV…'
  to contain 'if "%ORCA_AGENT_HOOK_PORT%"=="" exit …'
AssertionError: expected -1 to be greater than -1

The structural tests now assert reachability, not text presence — expect(labelIndex > -1).toBe(jumpIndex > -1) per script, plus guard ordering — and the loop covers the Antigravity event wrappers instead of excluding them.

After — this branch:

$ npx vitest run --config config/vitest.config.ts \
    src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts \
    src/main/claude/statusline-script.test.ts \
    src/main/claude/hook-service.test.ts \
    src/main/agent-hooks/installer-utils.test.ts \
    src/main/antigravity/ src/main/codex/ src/main/grok/ src/main/command-code/

 Test Files  46 passed | 1 skipped (47)
      Tests  749 passed | 13 skipped (762)

The other touched agents (devin, droid, cursor, gemini, openclaude, copilot, kimi, agent-hooks): 40 files passed, 576 passed | 6 skipped.

pnpm tc and pnpm lint pass on this branch.

The Windows-gated runtime test is skipped on the macOS host used here — it is not proof. See Residual risk.

Release-readiness

Scan Result
Functional correctness Every remaining drain is reachable only behind a confirmed Orca invocation. The no-env path is proved to terminate: runHookProcess rejects after 10s rather than resolving, so a hung more.com fails the test — that is the #11549 regression gate.
Cross-platform Windows-only script generation, gated by target === 'local' && process.platform === 'win32'. POSIX scripts cat the payload before any exit, so their semantics are untouched — confirmed by the unchanged, still-passing POSIX suites.
SSH / relay Unaffected. Remote installs go through installRemote() / writeManagedScriptRemote() with target 'posix', which never reaches the win32 branch.
Folder workspace vs worktree No dependence on repo shape — user-wide managed scripts under ~/.orca/agent-hooks. Provider-neutral. All test paths use path.join.
Backcompat On-disk .cmd files are content-compared and atomically rewritten by writeManagedScript(), so an existing leaked-shape script self-refreshes at the next install/reconcile. Downgrading rewrites the old shape back. No schema or settings format changed.
Security / supply chain No new dependencies. The change strictly removes blocking reads from generated scripts; no new exec, network sink, or install hook.

Residual risk

  • This narrows the fix(agent-hooks): drain stdin before hook script early exits so agents never hit EPIPE #8430 EPIPE guarantee on the missing-env path, and that path was in scope for fix(agent-hooks): drain stdin before hook script early exits so agents never hit EPIPE #8430. A non-Orca Windows agent that streams a payload into the hook can now see a broken pipe instead of a silent drain. Deliberate tradeoff: a transient warning beats an immortal cmd.exe/more.com pair and a console window on every hook event. The no-env test accordingly allows only broken-pipe errnos (EPIPE/ECONNRESET/ERR_STREAM_DESTROYED/EOF) — any other errno fails, meaning the script itself broke. copilot-hook.ps1 and kimi-hook.sh capture stdin before any guard and are still held to the old zero-writer-errors bar.
  • No live Windows runtime proof. The behavioural lifecycle test is it.skipIf(process.platform !== 'win32') and skipped on this host; its new with-Orca-env block (a real loopback HTTP reader running all 12 scripts asserting zero stdinErrors, plus a claude-hook.cmd + DEVIN_PROJECT_DIR case that only passes if the surviving epilogue actually consumes the 1MB payload) will execute for the first time on a Windows machine. PR CI will not catch it either — .github/workflows/pr.yml runs Vitest on Ubuntu only; the Windows job builds and packages without running Vitest. Coverage here is structural plus a Windows-only runtime gate that no CI lane executes.
  • Other never-EOF drains remain as hang primitives for stale hooks.json entries: installer-utils.ts ([Console]::In.ReadToEnd() missing-script launcher) and wrapWindowsGitBashHookCommand. This narrows the leak; it does not remove the primitive.
  • docs/reference/agent-hook-stdin-lifecycle.md documented this contract but was deleted in Add native chat skill picker with host-aware discovery #9480 as no longer maintained. The contract now lives in the hook-stdin-contract.ts comment. Restoring a maintained doc is a reasonable follow-up.
  • Already-leaked processes on affected machines still need a manual kill; this only stops new ones. The brief cmd.exe window flash from cmd.exe /C hook.cmd is unchanged.

Made with Orca 🐋

…ign stdin

The generated Windows batch hooks are installed user-wide, so agents launched
outside Orca run them too. Each guard for a missing Orca environment variable
jumped to the shared drain epilogue, which blocks in more.com until stdin hits
EOF. A caller that is not Orca never closes that pipe, so the cmd.exe/more.com
pair and its console window persist forever, and a fresh pair leaks on every
hook event.

Missing Orca env means the caller is not Orca, so Orca owes it no drain: exit
immediately instead. The EPIPE contract from stablyai#8430 only covers hooks Orca itself
invokes, which do get a payload written with stdin then closed, and those still
take the drain.

Claude's statusline script carried the same guard and is the worst offender
because Claude re-invokes it several times a second while streaming; it gets the
same treatment.

Fixes stablyai#11549

Co-authored-by: Orca <help@stably.ai>
@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Windows managed hooks now exit directly when required Orca environment variables are missing. The Windows statusline script now exits directly when ORCA_PANE_KEY is unset. Tests verify the direct exits, the absence of stdin-drain jumps, and stdin capture for valid pane keys.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy issue #11549 by preventing missing-environment Codex hooks from entering the blocking drain while preserving the Orca payload path.
Out of Scope Changes check ✅ Passed The shared guard and statusline changes address the same Windows stdin-drain defect and include focused regression coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly describes the primary fix: Windows hook guards now exit instead of blocking on foreign stdin.
Description check ✅ Passed The description explains the root cause, fix, tests, cross-platform impact, security considerations, and residual risks in detail.

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.

@greptile-apps

greptile-apps Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a process-leak bug on Windows where hook scripts installed for an entire user account would hang indefinitely when invoked by non-Orca callers (e.g. Claude running outside Orca). The root cause was that all three Orca-env guards routed to goto :orca_agent_hook_drain_stdin, which blocked on more.com waiting for stdin EOF — a signal a non-Orca caller never sends.

  • Core fix: buildWindowsHookEnvironmentGuardLines() in hook-stdin-contract.ts now emits exit /b 0 directly instead of routing to the drain epilogue, for all 10 generated batch scripts and the statusline script.
  • Order fix in claude/hook-service.ts: The Devin-skip guard and the ORCA_AGENT_HOOK_ENDPOINT call are reordered so Orca-env guards fire first; the Devin drain path is now only reachable when Orca actually launched the hook, preserving the fix(agent-hooks): drain stdin before hook script early exits so agents never hit EPIPE #8430 EPIPE guarantee for that path.
  • Antigravity wrappers: buildWindowsHookEnvironmentGuardLines() is inserted before the drain in the stale-wrapper path so that a partially uninstalled setup also exits cleanly on non-Orca invocations.

Confidence Score: 5/5

Safe to merge — the change is narrowly scoped to Windows batch script generation, is gated by process.platform === 'win32', and every affected code path is structurally verified by the updated test suite across all 10 batch scripts.

The fix is a one-word substitution (exit /b 0 for goto :drain) applied uniformly through a single shared builder, with the one surviving drain path (Claude's Devin skip) correctly conditioned on Orca env being present first. The reordering in claude/hook-service.ts is logically sound: moving env guards before the Devin skip ensures the drain there is only reached by an Orca-launched hook that will close stdin. The EPIPE residual risk for non-Orca callers is a deliberate, documented trade-off and does not affect correctness of Orca-launched hooks.

Files Needing Attention: No files require special attention. The remaining unreachable drain epilogue in statusline-script.ts is intentionally retained per the PR description.

Important Files Changed

Filename Overview
src/main/agent-hooks/hook-stdin-contract.ts Core change: guard lines now emit exit /b 0 instead of goto :drain; drain epilogue builder preserved and still exported for callers that have a surviving jump.
src/main/claude/hook-service.ts Reorders endpoint-refresh and Devin-skip relative to env guards so the drain epilogue is only reachable when Orca launched the hook; conditional epilogue emission is correctly gated on skipsDevinImport.
src/main/claude/statusline-script.ts Pane-key guard changed from goto :drain to exit /b 0; drain epilogue removed; the epilogue is now unreachable dead code (acknowledged residual in PR description).
src/main/antigravity/hook-service.ts Drain epilogue removed from main hook; wrapper scripts gain env guards before the drain command so stale wrappers exit cleanly on non-Orca invocations.
src/main/command-code/command-code-managed-script.ts Drain epilogue removed; subroutine labels :sourceEndpointByPort / :maybeSourceEndpoint are call-only and unaffected.
src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts Test suite extended with structural assertions for exit-vs-drain, reachability of epilogue, wrapper ordering, and a loopback HTTP server for verifying the Orca-env positive path still drains correctly.
src/main/claude/statusline-script.test.ts Updated to assert exit /b 0 on missing pane key and absence of the drain label; assertions correctly match the new script shape.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Hook script invoked] --> B{ORCA_AGENT_HOOK_ENDPOINT\ndefined & exists?}
    B -- Yes --> C[call endpoint file\nrefresh env vars]
    B -- No --> D
    C --> D{Env guards:\nPORT / TOKEN / PANE_KEY set?}
    D -- Any missing --> E[exit /b 0\nno drain, no hang]
    D -- All present --> F{skipsDevinImport\nand DEVIN_PROJECT_DIR set?}
    F -- Yes --> G[goto :orca_agent_hook_drain_stdin\ndrain stdin then exit]
    F -- No --> H[curl POST to Orca hook endpoint]
    H --> I[exit /b 0]
    G --> I

    subgraph Antigravity wrapper - core missing
        J[Env guards\nPORT / TOKEN / PANE_KEY] -- Any missing --> K[exit /b 0]
        J -- All present --> L[more.com drain\nstdin then exit]
    end

    style E fill:#f96,color:#000
    style K fill:#f96,color:#000
    style G fill:#9cf,color:#000
    style L fill:#9cf,color:#000
Loading

Reviews (2): Last reviewed commit: "fix(agent-hooks): close remaining Window..." | Re-trigger Greptile

…reachability

Order the Orca-env guards ahead of Claude's Devin skip so that skip's drain is
reachable only when Orca invoked the hook, guard the Antigravity event wrappers
before their standalone drain, and stop emitting the epilogue where nothing can
jump to it. Correct the stablyai#8430 rationale: it did cover Orca-less callers, but
assumed every caller closes stdin.

Co-authored-by: Orca <help@stably.ai>
@nwparker

Copy link
Copy Markdown
Contributor Author

Closing as superseded after checking current main.

The immediate-exit Windows hook guards shipped through merged #11568, with broader guard coverage added by #13379 and #19415. Current main exits when the Orca hook environment is absent instead of draining foreign stdin, including the relevant Windows shell variants.

Closing this PR only; its branch is being retained.

@nwparker nwparker closed this Oct 14, 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

Development

Successfully merging this pull request may close these issues.

[Bug]: Codex managed hook leaves persistent cmd.exe windows outside Orca on Windows

1 participant