fix(orchestration): read a prompt's tool_result without blocking main

The transcript read is async, reads only its tail, and skips any path that
is not a regular file, so a FIFO or device cannot stall the main process.
A closed prompt still awaiting its result gets one last read when the lead's
turn stops, so a result written late still names the close.
This commit is contained in:
Jinwoo-H
2026-11-11 01:02:37 -05:00
parent 45c102de9a
commit e8122d7e9c
5 changed files with 95 additions and 58 deletions
@@ -1,3 +1,4 @@
import { execFileSync } from 'node:child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -24,17 +25,28 @@ const result = (id: string, content: unknown, isError?: boolean) => ({
})
describe("Claude's tool_result for one tool call", () => {
it('reads only that call, in either content shape', () => {
it('reads only that call, in either content shape', async () => {
const path = transcript(
result('toolu_old', 'use a script file', true),
{ type: 'assistant', message: { content: [{ type: 'tool_use', id: 'toolu_new' }] } },
result('toolu_new', [{ type: 'text', text: '59' }])
)
expect(readClaudeToolResult(path, 'toolu_new')).toEqual({ isError: false, text: '59' })
expect(readClaudeToolResult(path, 'toolu_none')).toBeNull()
expect(readClaudeToolResult(join(path, 'missing'), 'toolu_new')).toBeNull()
expect(await readClaudeToolResult(path, 'toolu_new')).toEqual({ isError: false, text: '59' })
expect(await readClaudeToolResult(path, 'toolu_none')).toBeNull()
expect(await readClaudeToolResult(join(path, 'missing'), 'toolu_new')).toBeNull()
})
it.skipIf(process.platform === 'win32')(
'never opens a path that is not a regular file',
async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-claude-transcript-'))
dirs.push(dir)
const fifo = join(dir, 'fifo')
execFileSync('mkfifo', [fifo])
expect(await readClaudeToolResult(fifo, 'toolu_new')).toBeNull()
}
)
it('credits Orca only with its own deny text, and names a No and the 2:00 block', () => {
const deny = { isError: true, text: 'use a script file' }
expect(claudeToolClose(deny, 'use a script file')).toBe('hook-denied')
@@ -2,7 +2,7 @@
* call (probe 2026-11-10, Claude 2.1.322): a hook's deny message verbatim, the user's No, the 2:00
* safety-check block, or the command's own output. Hook events do not say this: a deny or a No
* fires no PostToolUse or PostToolUseFailure. */
import { closeSync, fstatSync, openSync, readSync } from 'node:fs'
import { open, stat, type FileHandle } from 'node:fs/promises'
export type ClaudeToolResult = { isError: boolean; text: string }
export type ClaudeToolClose = 'hook-denied' | 'user-denied' | 'auto-denied' | 'ran' | 'other'
@@ -12,23 +12,29 @@ const TAIL_BYTES = 512 * 1024
const USER_DENIED = "The user doesn't want to proceed with this tool use"
const AUTO_DENIED = 'denied by a built-in Claude Code safety check'
export function readClaudeToolResult(
/** Null unless the path is a regular file: a FIFO or device would never finish a read. */
export async function readClaudeToolResult(
transcriptPath: string,
toolUseId: string
): ClaudeToolResult | null {
let fd: number | null = null
): Promise<ClaudeToolResult | null> {
let file: FileHandle | null = null
try {
fd = openSync(transcriptPath, 'r')
const size = fstatSync(fd).size
const length = Math.min(size, TAIL_BYTES)
const buffer = Buffer.alloc(length)
readSync(fd, buffer, 0, length, size - length)
const lines = buffer
.toString('utf8')
.split('\n')
.filter((line) => line.includes(toolUseId))
// Why stat before open: opening a FIFO waits for a writer.
const stats = await stat(transcriptPath)
if (!stats.isFile()) {
return null
}
file = await open(transcriptPath, 'r')
const length = Math.min(stats.size, TAIL_BYTES)
const { buffer, bytesRead } = await file.read(
Buffer.alloc(length),
0,
length,
stats.size - length
)
const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n')
for (const line of lines.toReversed()) {
const result = toolResultIn(line, toolUseId)
const result = line.includes(toolUseId) ? toolResultIn(line, toolUseId) : null
if (result) {
return result
}
@@ -37,9 +43,7 @@ export function readClaudeToolResult(
} catch {
return null
} finally {
if (fd !== null) {
closeSync(fd)
}
await file?.close().catch(() => {})
}
}
@@ -5,19 +5,19 @@ const RETRY_MS = 100
/** The first non-null `read` within the wait, retried on `setTimer`; null when none came. */
export function firstWithin<T>(
setTimer: (run: () => void, delayMs: number) => unknown,
read: () => T | null
read: () => T | null | Promise<T | null>
): Promise<T | null> {
return new Promise((resolve) => {
let waited = 0
const check = (): void => {
const value = read()
const check = async (): Promise<void> => {
const value = await read()
if (value !== null || waited >= WAIT_MS) {
resolve(value)
return
}
waited += RETRY_MS
setTimer(check, RETRY_MS)
setTimer(() => void check(), RETRY_MS)
}
check()
void check()
})
}
@@ -66,7 +66,7 @@ function setup(options: { canAnswer?: boolean } = {}) {
canAnswerPane: () => options.canAnswer ?? true,
processIncarnation: () => screen.incarnation,
readScreen: () => screen.lines,
readToolResult: ({ transcriptPath, toolUseId }) =>
readToolResult: async ({ transcriptPath, toolUseId }) =>
transcriptPath === '/t/session.jsonl' && toolUseId === 'tool-1' ? screen.result : null,
setTimer: (run) => {
const timer = { run, cancelled: false }
@@ -246,6 +246,26 @@ describe('terminal worker approval holds', () => {
expect(ctx.closing()).toEqual([expect.stringContaining("Denied in the worker's terminal")])
})
it("names a close from a tool_result written only by the lead's Stop", async () => {
const ctx = setup()
await opened(ctx, hook('tool-1'))
ctx.screen.lines = AFTER
// Only until it closes awaiting a result: further ticks would fire its 10-minute fallback.
for (let i = 0; i < 80 && ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id); i++) {
await ctx.tick()
}
ctx.screen.result = USER_NO
ctx.holds.observe({
paneKey: PANE,
connectionId: null,
hookEventName: 'Stop',
payload: { state: 'done', prompt: '', agentType: 'claude' }
})
await vi.waitFor(() => expect(ctx.closing()).toHaveLength(1))
expect(ctx.closing()).toEqual([expect.stringContaining("Denied in the worker's terminal")])
})
it('treats a killed hook with the dialog still up as answerable only in the terminal', async () => {
const ctx = setup()
const asked = hook('tool-1')
@@ -10,7 +10,8 @@ import type {
} from '../../../../agent-hooks/server/claude-permission-hook-hold'
import type { AgentHookEventPayload } from '../../../../../shared/agent-hook-listener/listener-event'
import { showsClaudeDialog } from '../../../terminal/wait/claude-open-dialog-hold'
import { claudeToolClose, type ClaudeToolResult } from './claude-tool-result-close'
import { claudeToolClose } from './claude-tool-result-close'
import type { ClaudeToolClose, ClaudeToolResult } from './claude-tool-result-close'
import { firstWithin } from './first-within'
import type { OrchestrationDb } from '../../db/orchestration-db'
import type { DispatchContextRow } from '../../db/orchestration-records'
@@ -26,6 +27,14 @@ import type {
// Why 500 ms: Esc posts no hook, so only the screen says the dialog left; a click is refused within it.
const DIALOG_POLL_MS = 500
// How each tool_result names a close Orca did not make; null says no more than "closed".
const CLOSE_OF: Record<ClaudeToolClose, CloseHow | null> = {
ran: { by: 'worker-terminal', decision: 'allow' },
'user-denied': { by: 'worker-terminal', decision: 'deny' },
'auto-denied': { by: 'auto', decision: 'deny' },
'hook-denied': null,
other: null
}
// A closed prompt waits this long for its tool's result before its closing line says no more than "closed".
const CLOSE_EVIDENCE_MS = 10 * 60_000
@@ -41,7 +50,10 @@ export type TerminalWorkerApprovalHoldsDeps = Pick<WorkerTurnStopReportDeps, 'no
/** The pane's screen once it has applied every PTY chunk; null while it lags or is unreadable. */
readScreen: (paneKey: string) => readonly string[] | null
/** The tool_result Claude's transcript records for this tool call, once written. */
readToolResult: (call: { transcriptPath: string; toolUseId: string }) => ClaudeToolResult | null
readToolResult: (call: {
transcriptPath: string
toolUseId: string
}) => Promise<ClaudeToolResult | null>
setTimer: (run: () => void, delayMs: number) => { cancel: () => void }
}
@@ -151,7 +163,10 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
) {
for (const hold of this.closingByToolUseId.values()) {
if (hold.paneKey === event.paneKey) {
this.close(hold, null)
// One last read: a result written late still names the close.
void this.deps
.readToolResult(hold)
.then((result) => this.close(hold, result && CLOSE_OF[claudeToolClose(result, null)]))
}
}
}
@@ -238,34 +253,20 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
if (hold.state !== 'open') {
return
}
switch (hold.ranSeen ? 'ran' : result && claudeToolClose(result, null)) {
case 'ran':
this.close(hold, { by: 'worker-terminal', decision: 'allow' })
return
case 'user-denied':
this.close(hold, { by: 'worker-terminal', decision: 'deny' })
return
case 'auto-denied':
this.close(hold, { by: 'auto', decision: 'deny' })
return
case 'hook-denied':
case 'other':
this.close(hold, null)
return
case null: {
const lines = await firstWithin(this.deps.setTimer, () =>
this.deps.readScreen(hold.paneKey)
)
if (hold.state !== 'open') {
return
}
if (!lines || showsClaudeDialog(lines)) {
// The dialog is up but Orca can no longer answer it: a person must, in the terminal.
this.close(hold, { by: 'terminal-only', decision: null })
} else {
this.closeAwaitingEvidence(hold)
}
}
const close = hold.ranSeen ? 'ran' : result && claudeToolClose(result, null)
if (close) {
this.close(hold, CLOSE_OF[close])
return
}
const lines = await firstWithin(this.deps.setTimer, () => this.deps.readScreen(hold.paneKey))
if (hold.state !== 'open') {
return
}
if (!lines || showsClaudeDialog(lines)) {
// The dialog is up but Orca can no longer answer it: a person must, in the terminal.
this.close(hold, { by: 'terminal-only', decision: null })
} else {
this.closeAwaitingEvidence(hold)
}
}