Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config/tsconfig.cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"../src/main/agent-hooks/managed-agent-hook-controls.ts",
"../src/main/agent-hooks/managed-agent-hook-registry.ts",
"../src/main/agent-hooks/managed-hook-script-refresh.ts",
"../src/main/agent-hooks/nested-claude-host-guard.ts",
"../src/main/agent-hooks/posix-hook-command.ts",
"../src/main/agent-hooks/runtime-home-hook-command.ts",
"../src/main/agent-hooks/windows-direct-cmd-hook-command.ts",
Expand Down
39 changes: 39 additions & 0 deletions src/main/agent-hooks/nested-claude-host-guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { WINDOWS_HOOK_STDIN_DRAIN_LABEL } from './hook-stdin-contract'

// 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_TURN_VARS = ['CLAUDECODE', 'CLAUDE_CODE'] as const

// Why: a backgrounded Claude job runs in a daemon worker outside any pane, and
// that worker may abandon stdin. On Windows the drain parks in more.com, so
// this marker must exit instead of routing there (#11549) — the same rule
// `claude/hook-script.ts` and `claude/statusline-script.ts` already follow.
const NESTED_CLAUDE_WORKER_VAR = 'CLAUDE_JOB_DIR'

const NESTED_CLAUDE_HOST_VARS = [...NESTED_CLAUDE_TURN_VARS, NESTED_CLAUDE_WORKER_VAR] as const

/**
* Why (#20109): an agent launched from inside a Claude Code turn inherits the
* lead pane's `ORCA_PANE_KEY`, so its own `Stop`/`SessionEnd` settles the lead's
* pane and fires Agent Task Complete while the lead is still working. Only the
* lead session on a pane may settle it. Claude's own hook already bails the same
* way on `CLAUDE_JOB_DIR` (#9236); this is the cross-agent case.
*
* The guard has to live in the managed template, because `refreshManagedScripts`
* rewrites the installed script from it on every launch.
*/
export function buildPosixNestedClaudeHostGuardLines(): string[] {
const condition = NESTED_CLAUDE_HOST_VARS.map((name) => `[ -n "$${name}" ]`).join(' || ')
return [`if ${condition}; then`, ' exit 0', 'fi']
}

/** The same guard for a cmd hook. A nested turn still owns a live pipe, so it
* routes to the drain; the daemon-worker marker exits without draining. */
export function buildWindowsNestedClaudeHostGuardLines(): string[] {
return [
`if not "%${NESTED_CLAUDE_WORKER_VAR}%"=="" exit /b 0`,
...NESTED_CLAUDE_TURN_VARS.map(
(name) => `if not "%${name}%"=="" goto :${WINDOWS_HOOK_STDIN_DRAIN_LABEL}`
)
]
}
168 changes: 168 additions & 0 deletions src/main/grok/grok-hook-nested-claude-host.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { spawn } from 'node:child_process'
import { createServer, type Server } from 'node:http'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { getGrokManagedScript } from './grok-hook-script'
import { buildWindowsGrokHookScript } from './windows-grok-hook-script'

// Why (#20109): Claude launching Grok as a nested CLI leaves Grok holding the
// lead pane's ORCA_PANE_KEY, so a nested Stop would settle the Claude pane and
// fire Agent Task Complete mid-turn. Run the real generated script rather than
// asserting on its text: the guard only matters if /bin/sh actually takes it.
describe.skipIf(process.platform === 'win32')('Grok POSIX hook under a Claude host', () => {
let dir = ''
let server: Server | null = null

afterEach(async () => {
if (dir) {
rmSync(dir, { recursive: true, force: true })
dir = ''
}
if (server) {
const closing = server
server = null
await new Promise<void>((resolve) => closing.close(() => resolve()))
}
})

/** Runs the managed script against a local endpoint and reports what it posted. */
async function runHook(env: Record<string, string>): Promise<{
exitCode: number | null
posts: string[]
spoolFiles: string[]
}> {
dir = mkdtempSync(join(tmpdir(), 'orca-grok-nested-'))
const scriptPath = join(dir, 'grok-hook.sh')
writeFileSync(scriptPath, getGrokManagedScript('posix'), { mode: 0o755 })

const posts: string[] = []
server = createServer((request, response) => {
let body = ''
request.on('data', (chunk: Buffer) => {
body += chunk.toString()
})
request.on('end', () => {
posts.push(body)
response.writeHead(200).end('ok')
})
})
const port = await new Promise<number>((resolve) => {
server?.listen(0, '127.0.0.1', () => {
const address = server?.address()
resolve(typeof address === 'object' && address ? address.port : 0)
})
})

// Why: a readable endpoint file is what lets spool_hook_event write at all.
// With it unset the spool assertion below would pass even if a nested run
// spooled, because the helper returns before touching the disk.
const endpointPath = join(dir, 'endpoint.env')
writeFileSync(endpointPath, '')

const child = spawn('/bin/sh', [scriptPath], {
stdio: ['pipe', 'ignore', 'ignore'],
env: {
PATH: process.env.PATH ?? '',
HOME: dir,
ORCA_PANE_KEY: 'pane-lead',
ORCA_AGENT_HOOK_PORT: String(port),
ORCA_AGENT_HOOK_TOKEN: 'token-1',
ORCA_AGENT_HOOK_ENDPOINT: endpointPath,
...env
}
})
child.stdin.on('error', () => {})
child.stdin.end(JSON.stringify({ hook_event_name: 'Stop', session_id: 'nested-1' }))

const exitCode = await new Promise<number | null>((resolve, reject) => {
const timer = setTimeout(() => {
child.kill('SIGKILL')
reject(new Error('grok hook did not exit within 10s'))
}, 10_000)
child.on('error', (error) => {
clearTimeout(timer)
reject(error)
})
child.on('close', (code) => {
clearTimeout(timer)
resolve(code)
})
})

// The spool is the other way an event could still reach the lead pane.
// spool_hook_event derives its directory from the endpoint file's own
// parent (`${ORCA_AGENT_HOOK_ENDPOINT%/*}/spool`), not from HOME.
const spoolRoot = join(dir, 'spool')
let spoolFiles: string[] = []
try {
const { readdirSync } = await import('node:fs')
spoolFiles = readdirSync(spoolRoot, { recursive: true, encoding: 'utf8' }).filter((entry) =>
entry.endsWith('.jsonl')
)
} catch {
spoolFiles = []
}

return { exitCode, posts, spoolFiles }
}

it('posts a native run to the pane it belongs to', async () => {
const result = await runHook({})

expect(result.exitCode).toBe(0)
expect(result.posts).toHaveLength(1)
expect(result.posts[0]).toContain('paneKey=pane-lead')
})

// Why: without this the "spools nothing" assertions below would be vacuous —
// they must be able to observe a spool file when one is genuinely written.
it('spools a native run whose post cannot be delivered', async () => {
const result = await runHook({ ORCA_AGENT_HOOK_PORT: '1' })

expect(result.exitCode).toBe(0)
expect(result.posts).toEqual([])
expect(result.spoolFiles.length).toBeGreaterThan(0)
})

it.each(['CLAUDECODE', 'CLAUDE_CODE', 'CLAUDE_JOB_DIR'])(
'posts nothing and spools nothing when %s marks a nested run',
async (variable) => {
const result = await runHook({ [variable]: '1' })

expect(result.exitCode).toBe(0)
expect(result.posts).toEqual([])
expect(result.spoolFiles).toEqual([])
}
)
})

describe('Windows grok hook under a Claude host', () => {
// Why: cmd cannot run here, so pin the ordering the drain contract needs.
it('routes a nested turn to the stdin drain instead of posting', () => {
const lines = buildWindowsGrokHookScript().split('\r\n')
const postIndex = lines.findIndex((line) => line.includes('/hook/grok'))
expect(postIndex).toBeGreaterThan(-1)

for (const variable of ['CLAUDECODE', 'CLAUDE_CODE']) {
const guardIndex = lines.findIndex(
(line) =>
line.includes(`%${variable}%`) && line.includes('goto :orca_agent_hook_drain_stdin')
)
expect(guardIndex, `${variable} guard missing`).toBeGreaterThan(-1)
expect(guardIndex).toBeLessThan(postIndex)
}
})

// Why: a backgrounded Claude job is the abandoned-stdin case #11549 guards
// against, so it must exit rather than park in more.com. claude-hook.cmd is
// pinned to the same shape in claude/hook-service.test.ts.
it('exits on the daemon-worker marker without routing to the drain', () => {
const lines = buildWindowsGrokHookScript().split('\r\n')
const guard = lines.find((line) => line.includes('%CLAUDE_JOB_DIR%'))

expect(guard).toBe('if not "%CLAUDE_JOB_DIR%"=="" exit /b 0')
expect(guard).not.toContain('orca_agent_hook_drain_stdin')
})
})
4 changes: 4 additions & 0 deletions src/main/grok/grok-hook-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
buildPosixHookSpoolLines,
POSIX_HOOK_JSON_STDIN
} from '../agent-hooks/hook-stdin-contract'
import { buildPosixNestedClaudeHostGuardLines } from '../agent-hooks/nested-claude-host-guard'
import {
buildWindowsGrokHookScript,
GROK_HOME_ENVELOPE_MAX_LENGTH
Expand Down Expand Up @@ -38,6 +39,9 @@ export function getGrokManagedScript(target: 'local' | 'posix' = 'local'): strin
'#!/bin/sh',
...buildPosixHookPayloadCapture('exit', POSIX_HOOK_JSON_STDIN),
...buildPosixHookSpoolLines('grok'),
// Placed after the payload capture so a nested run still drains stdin, and
// it exits without spooling: the event must not reach the lead's pane later.
...buildPosixNestedClaudeHostGuardLines(),
'if [ -n "$ORCA_AGENT_HOOK_ENDPOINT" ] && [ -r "$ORCA_AGENT_HOOK_ENDPOINT" ]; then',
' . "$ORCA_AGENT_HOOK_ENDPOINT" 2>/dev/null || :',
'fi',
Expand Down
2 changes: 2 additions & 0 deletions src/main/grok/windows-grok-hook-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
buildWindowsHookEnvironmentGuardLines,
buildWindowsHookStdinDrainEpilogue
} from '../agent-hooks/hook-stdin-contract'
import { buildWindowsNestedClaudeHostGuardLines } from '../agent-hooks/nested-claude-host-guard'

/** Matches the envelope length cap used by the POSIX grok-hook branch. */
export const GROK_HOME_ENVELOPE_MAX_LENGTH = 4096
Expand Down Expand Up @@ -33,6 +34,7 @@ export function buildWindowsGrokHookScript(): string {
'setlocal DisableDelayedExpansion',
'if defined ORCA_AGENT_HOOK_ENDPOINT if exist "%ORCA_AGENT_HOOK_ENDPOINT%" call "%ORCA_AGENT_HOOK_ENDPOINT%" 2>nul',
...buildWindowsHookEnvironmentGuardLines(),
...buildWindowsNestedClaudeHostGuardLines(),
'set "ORCA_GROK_HOME="',
'if not defined GROK_HOME goto :orca_grok_home_ready',
`if not "%GROK_HOME:~${GROK_HOME_ENVELOPE_MAX_LENGTH},1%"=="" goto :orca_grok_home_ready`,
Expand Down