Skip to content

fix(grok): stop a nested Grok run from settling its Claude host pane - #22306

Open
huiq777 wants to merge 2 commits into
stablyai:mainfrom
huiq777:fix/20109-nested-grok-host-guard
Open

huiq777 wants to merge 2 commits into
stablyai:mainfrom
huiq777:fix/20109-nested-grok-host-guard

Conversation

@huiq777

@huiq777 huiq777 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

If you ask Claude to run grok for you, Grok finishes its little job and announces "done" — but it announces it on Claude's pane, because it inherited Claude's pane identity. Orca then played the Agent Task Complete chime and marked the pane finished while Claude was still working. This teaches the Grok hook to stay quiet when it is running inside another agent's turn.

What Changed

Before: grok-hook.sh posts every lifecycle event to /hook/grok with paneKey=$ORCA_PANE_KEY. A Grok process launched from inside a Claude turn inherits that variable from the lead pane, so its Stop/SessionEnd settled the Claude pane as done and fired Agent Task Complete mid-turn.

After: the managed hook exits early when CLAUDECODE, CLAUDE_CODE or CLAUDE_JOB_DIR is present — the variables Claude Code exports into everything it launches.

Mechanism: this mirrors a bail Claude's own hook already performs for the same class of problem — src/main/claude/hook-script.ts exits on CLAUDE_JOB_DIR because a backgrounded session inherits a pane key it does not run in (#9236). This is the cross-agent version of that.

Two details that are not incidental:

  • The guard must live in the template. The issue explicitly rules out editing the installed ~/.orca/agent-hooks/grok-hook.sh, because refreshManagedScripts/install() rewrite it from the stock template on launch.
  • POSIX exits without spooling; cmd jumps to the drain. Skipping must not mean "deliver later", so the POSIX path returns before spool_hook_event — otherwise the nested event would simply reach the lead pane on the next flush. On Windows the guard gotos the stdin drain rather than exiting, because abandoning the pipe strands a console window per event ([Bug]: Codex managed hook leaves persistent cmd.exe windows outside Orca on Windows #11549). That asymmetry is the existing contract, and buildWindowsGrokReplayGuardLines already uses the same jump.

The env-var list lives in one small module so the POSIX and cmd builders cannot drift apart.

Why

Issue #20109. Alternatives considered:

  • Ignore nested Stop on the listener side (normalizeGrokEvent) — rejected: by then the post already carries the lead's paneKey and nothing in the payload distinguishes a nested Grok from a native one. The reporter confirms the nested process is a full session with SessionStart…Stop and no subagentType, so the descendant-roster work in fix(agents): keep a pane working while its agent's descendants are live #19722 does not catch it either.
  • Match on GROK_HOOK_EVENT like the existing replay guard — rejected: that guard solves the inverse case (Grok importing Claude's vendor hooks) and is set in both native and nested Grok runs, so it cannot separate them.
  • Have the lead keep a working marker for the whole turn — that is a real improvement but it is the other half of this issue (see Scope), and it would paper over a nested agent writing to a pane it does not own rather than stop it.

Linked Issue

Related #20109

Deliberately Related rather than Fixes: #20109 reports three defects and this PR addresses one.

Scope

Fixed here — the cross-model half:

  • A nested Grok under a Claude lead no longer settles the lead's pane.

Correction: an earlier revision of this section claimed Claude/Codex parity. That was wrong — the guard matches Claude markers only, and Codex exports CODEX_THREAD_ID rather than any of them, so a Grok launched from a Codex turn still posts onto the Codex pane. Thanks to the reviewer for catching the overclaim. Codex coverage is a one-line addition to the marker list once someone can confirm the variable a Codex-launched child actually sees; I have not been able to verify that, so I have not guessed at it.

Explicitly not in this PR — the native-pane half, which is independent and better reviewed on its own:

  • normalizeGrokEvent inferring idle from TUI footer message text rather than notificationType == idle_prompt.
  • Spinner-less … - grok titles classifying as idle while hooks still report working.

Those change how a native Grok pane is classified and carry a different regression risk (#15225/#15230 are adjacent). Happy to follow up, or to fold them in if a maintainer would rather have one PR.

Visual Proof

N/A — no UI change. The user-visible effect is the absence of a chime and of a premature done, which is not something a screenshot shows. It is pinned behaviorally instead; see Testing.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New file src/main/grok/grok-hook-nested-claude-host.test.ts. Rather than assert on the generated text, it executes the real generated script with /bin/sh against a local HTTP server and observes what it posts — the repo already runs the hook this way in grok-hook-stdin-no-eof.test.ts, and a guard is only worth anything if sh actually takes it.

  • Control: a native run (no Claude variables) still posts exactly once, with paneKey=pane-lead.
  • The fix: CLAUDECODE, CLAUDE_CODE and CLAUDE_JOB_DIR each produce zero posts, exit 0, and leave no spool file — the spool being the other route the event could take to the lead pane.
  • Windows: asserts each guard appears before the post command and jumps to orca_agent_hook_drain_stdin, since cmd cannot run on the test host.

I verified the tests fail without the source change. Reverting only the two script builders:

× posts nothing and spools nothing when CLAUDECODE marks a nested run
× posts nothing and spools nothing when CLAUDE_CODE marks a nested run
× posts nothing and spools nothing when CLAUDE_JOB_DIR marks a nested run
× skips to the stdin drain instead of posting
  Tests  4 failed | 1 passed (5)

The native-run control passes in both states, which is the check that matters — it shows the guard suppresses the nested case without simply breaking posting.

Commands run on macOS (arm64):

vitest run src/main/grok/ src/main/agent-hooks/      # 99 files, 1008 passed, 27 skipped
vitest run src/main/grok/ src/main/agent-hooks/ src/main/claude/
                                                     # 178 files, 1862 passed, 38 skipped
pnpm tc                                              # exit 0
pnpm exec oxlint src/main/grok/ src/main/agent-hooks/  # exit 0
pnpm exec oxfmt --check <changed files>              # correctly formatted
ORCA_CODE_QUALITY_BASE=upstream/main pnpm run check:code-quality:changed
                                                     # passed, 0 findings across 4 files

Platforms: POSIX behavior executed on macOS. The Windows branch is asserted structurally, not run — I have no Windows host, and I have flagged that rather than imply otherwise.

AI Disclosure

Written with Claude Code (Claude Opus 5). I reviewed the change and ran every command above myself.

Review

  • Cross-platform: both branches updated together from one shared env-var list. POSIX exits; cmd jumps to the drain to honor the Windows stdin rule ([Bug]: Codex managed hook leaves persistent cmd.exe windows outside Orca on Windows #11549). No paths are constructed.
  • SSH / remote / local: the template is what grok-hook-remote-install.ts ships, so a remote host installs the same guard. No execution-host assumption is added.
  • Agents / integrations: scoped to the Grok managed hook. Claude, Codex, Gemini and the rest are untouched, and the existing Grok replay guard is unaffected.
  • Performance: three string comparisons before any curl. On the nested path it strictly removes work — one fewer HTTP POST per event.
  • Security: no new input, endpoint or credential. It only declines to send.
  • Backwards compatibility: the sole behavior change is that a Grok hook running with a Claude variable present no longer posts. Orca never sets CLAUDECODE/CLAUDE_CODE itself (I grepped src/ to confirm), so a native Grok pane launched by Orca is unaffected — which the control test demonstrates.

⚠️ Known limitation — needs a maintainer decision before merge

A reviewer raised, and I have confirmed, that CLAUDECODE can reach a native Grok pane: a pane's env is built from Orca's own process.env (host-env/assembly.ts:47, host-env/pi-agent.ts:132), and host-env/spawn-env-keys.ts:13 scrubs only CLAUDE_CODE_CHILD_SESSION / _SESSION_ID / _BRIDGE_SESSION_ID — not CLAUDECODE. So if Orca is itself launched from inside a Claude Code session, every Grok pane inherits the marker and this guard silently suppresses all Grok hook status, not just nested runs.

That is worse than the bug being fixed, so I am not asking for this to be merged as-is. Two ways out, and the choice is a policy call about shared pane env that I do not think a contributor should make alone:

  1. Scrub the marker at pane spawn — add CLAUDECODE (and CLAUDE_CODE, if it is real) to the list that already exists for exactly this reason, whose comment reads "Orca never sets these, so an inherited value means a pty host launched from inside a Claude session". The guard then means "genuinely nested". This changes env for every agent's panes, not just Grok.
  2. Key the guard on a marker Orca already scrubs — e.g. CLAUDE_CODE_SESSION_ID, which a native pane cannot carry precisely because it is stripped, while a Claude running inside a pane would set it for its children. Narrower, but I cannot verify a nested Grok actually receives it without a Claude CLI on this machine, and I would rather say so than assert it.

Happy to implement either. Option 1 is what the reviewer suggested.

Agent skill upstream boundary

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

Notes

config/tsconfig.cli.json gains the new module. That project uses an explicit file list, and windows-grok-hook-script.ts is in it, so omitting the import target fails tsc tsconfig.tc.cli.json with TS6307. grok-replay-guard.ts is listed there for the same reason.

Credit: the diagnosis, the CLAUDECODE finding and the hook-decision counts (9 posts native vs 9 skipped nested) are the reporter's work in #20109.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred) — typecheck, the affected suites, oxlint, oxfmt and the changed-code quality gate run locally; full suite and build left to CI

🤖 Generated with Claude Code

A Grok CLI launched from inside a Claude turn inherits the lead pane's
ORCA_PANE_KEY, so its own Stop/SessionEnd posted to /hook/grok settled the
Claude pane as done and fired Agent Task Complete while Claude was still
waiting on the child.

Skip the managed Grok hook when CLAUDECODE, CLAUDE_CODE or CLAUDE_JOB_DIR
marks a nested run, matching the bail Claude's own hook already does on
CLAUDE_JOB_DIR. The guard lives in the template because refreshManagedScripts
rewrites the installed script on every launch. POSIX exits without spooling
so the event cannot reach the lead later; cmd jumps to the drain so the
caller's stdin is still consumed.

Related stablyai#20109

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: da8fd4b5-b090-44b9-8220-793002663b93

📥 Commits

Reviewing files that changed from the base of the PR and between c2abbbd and 98aa19e.

📒 Files selected for processing (2)
  • src/main/agent-hooks/nested-claude-host-guard.ts
  • src/main/grok/grok-hook-nested-claude-host.test.ts

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


📝 Walkthrough

Walkthrough

The change adds shared POSIX and Windows builders for nested Claude host guards. Generated Grok hooks use these guards to avoid posting nested events to the lead pane while continuing stdin handling. The CLI TypeScript configuration compiles the new module. POSIX integration tests verify native posting, spool fallback, and nested suppression. Windows tests verify guard placement and separate stdin-drain routing.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 98aa1

The supplied change is mergeable after normal checks.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR satisfies the nested-host objective in [#20109]. The managed POSIX template captures stdin, then exits when CLAUDECODE, CLAUDE_CODE, or CLAUDE_JOB_DIR is set. It does not post or spool th…
Out of Scope Changes check ✅ Passed The changes remain within [#20109]. The shared guard module, CLI configuration entry, managed Grok template integrations, and generated-hook tests all support nested Grok event suppression. The PR doe…
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files.
Title check ✅ Passed The title clearly identifies the main change: preventing nested Grok runs from settling the Claude host pane.
Description check ✅ Passed The description is detailed and covers the required explanation, change, rationale, linked issue, visual proof, testing, AI disclosure, review considerations, scope, and checklist. It uses Related #20…

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: aef7b3fb-50c0-4a91-b07c-33131eddd519

📥 Commits

Reviewing files that changed from the base of the PR and between a8786c0 and c2abbbd.

📒 Files selected for processing (5)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/nested-claude-host-guard.ts
  • src/main/grok/grok-hook-nested-claude-host.test.ts
  • src/main/grok/grok-hook-script.ts
  • src/main/grok/windows-grok-hook-script.ts

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

@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 blocking issues — one scope question and three rough edges noted inline.

Reviewed changes

  • Nested-host guard template — new nested-claude-host-guard.ts centralizes CLAUDECODE/CLAUDE_CODE/CLAUDE_JOB_DIR and emits a POSIX exit 0 form plus a cmd goto-drain form; both Grok script builders consume it.
  • POSIX Grok script — the guard sits after payload capture and the spool helper definition, before the endpoint refresh and curl, so a nested run drains stdin but neither spools nor posts.
  • Windows Grok script — the guard is inserted after the Orca env guard and before the GROK_HOME handling, jumping to the shared stdin-drain epilogue.
  • New behavioural test — runs the real generated POSIX script under /bin/sh against a local HTTP server for the native control and each Claude marker, plus a structural ordering assertion for the cmd branch.
  • config/tsconfig.cli.json — adds the new module to the explicit CLI project file list.

ℹ️ A Codex lead is not covered, though the PR body says it is

Under "Scope", the PR states "A nested Grok under a Claude/Codex lead no longer settles the lead's pane." The guard only matches Claude markers, so a Grok launched by a Codex turn still posts onto the Codex pane and settles it. Claude leads are fixed; the claim is broader than the mechanism.

Technical details
# Codex-lead coverage gap

## Affected sites
- `src/main/agent-hooks/nested-claude-host-guard.ts:5` — `NESTED_CLAUDE_HOST_VARS` contains only Claude markers.
- PR body, "Scope" — asserts Claude/Codex parity for the nested-pane fix.

## Evidence
- Upstream `openai/codex` (`codex-rs/protocol/src/shell_environment.rs`) inserts `CODEX_THREAD_ID` only; `codex-rs/core/src/spawn.rs` sets `CODEX_SANDBOX` / `CODEX_SANDBOX_NETWORK_DISABLED`. Sourcegraph searches over `repo:^github.com/openai/codex$` for `CLAUDECODE`, `CLAUDE_CODE`, `CLAUDE_JOB_DIR` return zero env-var hits (only agent-name string literals). Codex inherits the parent env (`ShellEnvironmentPolicyInherit::All`) but never authors a Claude marker.
- So `buildPosixNestedClaudeHostGuardLines()` evaluates false for a Codex-launched Grok, and the hook posts normally.

## Required outcome
- Either narrow the claim to Claude leads, or add the marker a Codex turn exports (`CODEX_THREAD_ID`, `CODEX_SANDBOX*`) after confirming it is present for every Codex-launched child.

## Open questions for the human
- Is the Codex half intended in this PR or tracked separately? The issue's own suggested fix lists only the Claude markers, so the body's Claude/Codex wording may be inherited from the issue title.

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


// The variables Claude Code exports into every process it launches. A nested
// agent inherits them along with the lead pane's ORCA_PANE_KEY.
const NESTED_CLAUDE_HOST_VARS = ['CLAUDECODE', 'CLAUDE_CODE', 'CLAUDE_JOB_DIR'] as const

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.

CLAUDECODE can be inherited by a native Grok pane when Orca itself was launched from inside a Claude Code session: Orca builds each pane's env from its own process env and spawn-env-keys.ts:13 strips only the CLAUDE_CODE_* session markers, not CLAUDECODE. In that setup every Grok pane silently loses all hook status, not just a nested run.

Technical details
# Native-pane false positive via inherited CLAUDECODE

## Affected sites
- `src/main/agent-hooks/nested-claude-host-guard.ts:5` — matches `CLAUDECODE` for every Grok hook.
- `src/main/ipc/pty/host-env/spawn-env-keys.ts:13` — scrubs `CLAUDE_CODE_CHILD_SESSION` / `_SESSION_ID` / `_BRIDGE_SESSION_ID` but not `CLAUDECODE`.

## Required outcome
- Ensure `CLAUDECODE` (and `CLAUDE_CODE`, if it is real) cannot reach a native pane's spawn env, or the guard suppresses native Grok status whenever Orca runs under Claude Code.

## Suggested approach
- Add the marker to the pty host-env scrub list that already handles Claude-inherited values, keeping the guard's meaning to "a genuinely nested run".

…real

Review found the Windows guard routed CLAUDE_JOB_DIR to the stdin drain.
That marker is a daemon worker outside any pane, which is the abandoned-stdin
case stablyai#11549 guards against, and claude-hook.cmd is pinned to exit on it
instead. Split it out to exit /b 0 and keep only the live-turn markers on the
drain.

The nested-run test also could not observe a spool: it left the endpoint unset,
so spool_hook_event returned before writing, and it matched .json while the
hook writes .jsonl. Point it at a real endpoint, match the right suffix, and
correct the directory — the spool lives beside the endpoint file, not under
HOME. A native run whose post fails now pins that a spool is observable, so
the nested assertions cannot pass vacuously.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@huiq777

huiq777 commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — I verified all four findings against the tree rather than taking them on trust, and three of them were right. Two are fixed in 98aa19e; the fourth is blocking and I would rather not guess at it.

1. Windows CLAUDE_JOB_DIR routed to the drain — correct, fixed. claude/hook-service.test.ts pins the exact shape you cited:

expect(guard).toBe('if not "%CLAUDE_JOB_DIR%"=="" exit /b 0')
// Why: the drain parks in more.com, and a daemon worker is exactly the
// abandoned-stdin case #11549 guards against — it must never route there.
expect(guard).not.toContain(WINDOWS_HOOK_STDIN_DRAIN_LABEL)

That test covers claude-hook.cmd, so my version would not have failed it — the invariant would just have been quietly broken in grok-hook.cmd. The guard now splits: CLAUDE_JOB_DIR exits, and only the live-turn markers (CLAUDECODE, CLAUDE_CODE) route to the drain, since those do still own a live pipe. Both legs are pinned by their own test now.

2. The spool assertion was vacuous — correct, and worse than reported. Three separate things defeated it: the endpoint was unset so spool_hook_event returned at [ -n "${ORCA_AGENT_HOOK_ENDPOINT:-}" ] || return 0; the filter matched .json while the hook writes .jsonl; and my spool directory was wrong anyway — it derives from the endpoint file's own parent (${ORCA_AGENT_HOOK_ENDPOINT%/*}/spool), not HOME.

I did not just apply the suggested diff, because a corrected assertion that still cannot observe anything is no better. There is now a control that makes a native run fail its post and asserts a spool file appears. That test failed until I fixed the directory, which is what proves the nested "spools nothing" assertions can actually see a regression.

3. Codex is not covered — correct, my PR body was wrong. The guard matches Claude markers only; Codex exports CODEX_THREAD_ID. I have corrected the Scope section rather than quietly widening the marker list, because I cannot confirm from here which variable a Codex-launched child actually sees, and guessing would reintroduce exactly the kind of unverified claim you caught.

4. CLAUDECODE reaching a native pane — correct, and I am treating it as blocking. I confirmed the chain: pane env is built from Orca's process.env (assembly.ts:47, pi-agent.ts:132) and spawn-env-keys.ts:13 scrubs only the three CLAUDE_CODE_* session stamps. So launching Orca from inside a Claude Code session suppresses all Grok status, which is a worse failure than the one this PR fixes.

I have written this up in the PR body as a known limitation rather than shipping it. The fix you suggest — adding the marker to the pty host-env scrub list — is I think the right one, and that list's own comment ("Orca never sets these, so an inherited value means a pty host launched from inside a Claude session") describes this situation exactly. But it changes pane env for every agent, not just Grok, so I would like a maintainer to confirm that direction before I touch shared spawn env. I will implement it immediately on a thumbs-up, or take the narrower alternative in the PR body if that is preferred.

Verification after the fixes, on macOS (arm64): reverting the two script builders to upstream now fails 5 of 7 cases, with both native controls passing in either state; restored, 7/7. src/main/grok/, src/main/agent-hooks/ and src/main/claude/ together are 1864 passed / 38 skipped. pnpm tc exit 0, oxlint exit 0, oxfmt clean, and the changed-code quality gate reports 0 findings across the 4 files.

@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 in this delta — the Windows worker-marker and vacuous spool-test concerns from the prior review are addressed. The native-pane CLAUDECODE question is unchanged and still needs the maintainer decision the PR body describes, so this is not an approval.

Reviewed changes

  • Split the Claude host markers into turn vars (CLAUDECODE, CLAUDE_CODE) and a worker var (CLAUDE_JOB_DIR) in nested-claude-host-guard.ts.
  • Windows cmd guard now exit /b 0s on the worker marker and reserves the stdin drain for the turn markers, matching the CLAUDE_JOB_DIR invariant in claude/hook-script.ts and claude/statusline-script.ts.
  • Test harness points ORCA_AGENT_HOOK_ENDPOINT at a real readable file and derives the spool root from it, so the "spools nothing" assertions can actually observe a spool.
  • Added a positive control that spools when the native post cannot be delivered, and split the Windows assertions into drain-routing (turn markers) and exit (worker marker).

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

@nwparker

Copy link
Copy Markdown
Contributor

Thanks for the careful work here, @huiq777, including the follow-up fixes after review. A nested Grok run inheriting its Claude host's pane key is now handled on the server side by the pane-owner guard, and Grok completions are announced only when work is truly done (#20507, #20523), so this hook-side bail is redundant and the branch conflicts with current main. We are closing it as superseded; if you still see a nested Grok settle its host pane on the latest build, please open an issue with the repro.

This branch has not been deployed

No deployments
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