From 0804246623d232141b1ccf89a74e85334cfbfdce Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Tue, 10 Nov 2026 08:10:26 -0500 Subject: [PATCH] fix(orchestration): close a terminal prompt's card as soon as Orca can't answer it When the dialog leaves without an answer through Orca, the closing line is published at once, so the coordinator's card becomes a receipt; a tool result that arrives later adds a second line naming how it closed, without waking the coordinator. On startup, open terminal prompts left by an earlier run are closed the same way, since their holds lived in memory. A Claude terminal card's reason is the warning Claude prints under the command. --- .../runtime-orchestration-database-access.ts | 3 + .../approvals/terminal-approval-orphans.ts | 60 +++++++++++++++++++ .../terminal-worker-approval-hold.ts | 2 + .../terminal-worker-approval-holds.test.ts | 59 ++++++++++++++++-- .../terminal-worker-approval-holds.ts | 30 +++++++--- .../turn-stops/worker-turn-stop-report.ts | 11 +++- .../terminal/wait/claude-open-dialog-hold.ts | 25 ++++++++ .../approvals/worker-approval-payload.ts | 4 +- 8 files changed, 176 insertions(+), 18 deletions(-) create mode 100644 src/main/runtime/orchestration/workers/approvals/terminal-approval-orphans.ts diff --git a/src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts b/src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts index 4b8d54984d2..5ebdd602d2c 100644 --- a/src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts +++ b/src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts @@ -2,6 +2,7 @@ import { getWorkerTerminalAutoReleaseScheduler } from '../terminal-authority/rel import { OrchestrationDb } from './orchestration-db' import { committedHandBackTypes, type MailHandBack } from './messages/helper-mailbox-hand-back' import { existsSync } from 'node:fs' +import { closeOrphanedTerminalApprovals } from '../workers/approvals/terminal-approval-orphans' import { OrcaRuntimeWithAutomationApiOperations } from '../../workspaces/persisted-surfaces/automation-api-operations' export abstract class RuntimeOrchestrationDatabaseAccess extends OrcaRuntimeWithAutomationApiOperations { @@ -24,6 +25,8 @@ export abstract class RuntimeOrchestrationDatabaseAccess extends OrcaRuntimeWith // Recover deadlines armed before a restart. getWorkerTerminalAutoReleaseScheduler(this).rearm() this.continueRestoredWorkerMail(this._orchestrationDb) + // No terminal prompt's hold survives a restart; its card must not stay answerable. + closeOrphanedTerminalApprovals(this._orchestrationDb) } return this._orchestrationDb } diff --git a/src/main/runtime/orchestration/workers/approvals/terminal-approval-orphans.ts b/src/main/runtime/orchestration/workers/approvals/terminal-approval-orphans.ts new file mode 100644 index 00000000000..c75c668c907 --- /dev/null +++ b/src/main/runtime/orchestration/workers/approvals/terminal-approval-orphans.ts @@ -0,0 +1,60 @@ +/** A terminal worker's prompt is answerable only while Orca holds its hook, and holds live in + * memory: after a restart, a prompt still open in the mailbox can no longer be answered here. */ +import { z } from 'zod' +import { WorkerApprovalPayloadSchema } from '../../../../../shared/orchestration/approvals/worker-approval-payload' +import type { OrchestrationDb } from '../../db/orchestration-db' +import { reportWorkerApprovalClosed } from '../turn-stops/worker-turn-stop-report' + +// Why a bound: older escalations are long past Claude's own 2:00 timeout. +const RECENT_ESCALATIONS = 200 + +const Row = z.object({ payload: z.string() }) +const Carrier = z.object({ + handle: z.string(), + dispatchId: z.string(), + approval: WorkerApprovalPayloadSchema +}) + +/** Closes every open terminal-worker prompt, so its card becomes a receipt; a prompt already + * closed keeps its line, since the closing report's id is fixed per prompt. */ +export function closeOrphanedTerminalApprovals(db: OrchestrationDb): void { + const rows = Row.array().parse( + db.db + .prepare(`SELECT payload FROM messages WHERE type = 'escalation' + AND json_extract(payload, '$.approval.state') = 'open' + AND json_extract(payload, '$.approval.approvalId') LIKE 'apr\\_%' ESCAPE '\\' + ORDER BY sequence DESC LIMIT ${RECENT_ESCALATIONS}`) + .all() + ) + for (const row of rows) { + const carried = Carrier.safeParse(parseJson(row.payload)) + const dispatch = carried.success ? db.getDispatchContextById(carried.data.dispatchId) : null + if (!carried.success || !dispatch) { + continue + } + const { approval, handle } = carried.data + reportWorkerApprovalClosed( + db, + dispatch, + { + from: handle, + approval: { + ...approval, + state: 'expired', + allowedActions: [], + outcome: { by: 'unknown', decision: null, reason: null, reasonDelivered: true } + } + }, + // Nothing to wake: the coordinator reads it with its next mail. + { notify: () => {} } + ) + } +} + +function parseJson(text: string): unknown { + try { + return JSON.parse(text) + } catch { + return null + } +} diff --git a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-hold.ts b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-hold.ts index 57748b7953d..203c96f78d6 100644 --- a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-hold.ts +++ b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-hold.ts @@ -40,6 +40,8 @@ export type TerminalWorkerApprovalHold = { /** Compare-and-set: only the step out of `open` may write a decision to the hook. */ state: 'open' | 'answering' | 'answered' | 'closed' dialogSeen: boolean + /** Its card already closed; the tool's result may still name how, without waking anyone. */ + refinable: boolean /** Its PostToolUse arrived while an answer was in flight: the tool ran. */ ranSeen: boolean expiresAt?: string diff --git a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.test.ts b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.test.ts index 76eac4acbe3..b9381dab121 100644 --- a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.test.ts +++ b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.test.ts @@ -12,6 +12,7 @@ import '../../db/dispatch-row-writer' import '../../db/attempt-outcome-projection' import { createRootDispatch } from '../../db/root-dispatch-test-fixture' import { TerminalWorkerApprovalHolds } from './terminal-worker-approval-holds' +import { closeOrphanedTerminalApprovals } from './terminal-approval-orphans' import type { ClaudeToolResult } from './claude-tool-result-close' const PANE = makePaneKey('tab-worker', '11111111-1111-4111-8111-111111111111') @@ -27,6 +28,19 @@ const DIALOG = [ ' 2. No', ' Esc to cancel · Tab to amend' ] +const WARNED = [ + ' Bash command', + ' ╌╌╌╌╌╌╌╌', + ' │ rm -rf build', + ' ╌╌╌╌╌╌╌╌', + ' │ Dangerous rm operation not ruled out — the shell may read this', + ' │ command differently than it was parsed', + ' ⚠ Claude Code will automatically block this request in 1:42, to avoid holding up an unattended session', + ' Do you want to proceed?', + ' ❯ 1. Yes', + ' 2. No', + ' Esc to cancel · Tab to amend' +] // An earlier prompt's deny stays on screen: only this call's tool_result says how it closed. const AFTER = [ '● Bash(rm -rf old)', @@ -92,7 +106,7 @@ function setup(options: { canAnswer?: boolean } = {}) { .getUnreadRunMailbox(run.id, 100) .filter((message) => message.type === 'status') .map((message) => message.body) - return { dispatch, screen, holds, tick, closing } + return { db, dispatch, screen, holds, tick, closing } } function hook( @@ -255,7 +269,7 @@ 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 () => { + it("closes the card when the dialog leaves, and names it from a result read on the lead's Stop", async () => { const ctx = setup() await opened(ctx, hook('tool-1')) ctx.screen.lines = AFTER @@ -270,9 +284,13 @@ describe('terminal worker approval holds', () => { hookEventName: 'Stop', payload: { state: 'done', prompt: '', agentType: 'claude' } }) - await vi.waitFor(() => expect(ctx.closing()).toHaveLength(1)) + await vi.waitFor(() => expect(ctx.closing()).toHaveLength(2)) - expect(ctx.closing()).toEqual([expect.stringContaining("Denied in the worker's terminal")]) + // The card closed when the dialog left; the late result only names how. + expect(ctx.closing()).toEqual([ + expect.stringContaining('Closed without an answer Orca can name'), + 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 () => { @@ -286,4 +304,37 @@ describe('terminal worker approval holds', () => { expect.stringContaining("a person must answer it in the worker's terminal") ]) }) + it("carries the warning Claude prints under a flagged command as the card's reason", () => { + const ctx = setup() + ctx.screen.lines = WARNED + ctx.holds.admit(hook('tool-1').request) + expect(ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id)?.summary.reason).toBe( + 'Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed' + ) + const plain = setup() + plain.holds.admit(hook('tool-1').request) + expect(plain.holds.takeOpenApproval(PANE, plain.dispatch.id)?.summary.reason).toBeNull() + }) + + it('closes a prompt left open by an earlier run, once, when the database opens', () => { + const ctx = setup() + ctx.holds.admit(hook('tool-1').request) + const approval = ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id)! + ctx.db.insertMessage({ + from: HANDLE, + to: 'term_coordinator', + subject: 'Worker is waiting on approval', + type: 'escalation', + payload: JSON.stringify({ handle: HANDLE, dispatchId: ctx.dispatch.id, approval }), + runId: ctx.dispatch.run_id + }) + + closeOrphanedTerminalApprovals(ctx.db) + closeOrphanedTerminalApprovals(ctx.db) + expect(ctx.closing()).toEqual([ + expect.stringContaining( + `Closed without an answer Orca can name: approval ${approval.approvalId}` + ) + ]) + }) }) diff --git a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.ts b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.ts index fc315111ba1..91e4bb0aa8e 100644 --- a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.ts +++ b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.ts @@ -10,6 +10,7 @@ import type { import type { AgentHookEventPayload } from '../../../../../shared/agent-hook-listener/listener-event' import { claudeDialogExpiresAt, + claudeDialogWarning, showsClaudeDialog } from '../../../terminal/wait/claude-open-dialog-hold' import { claudeToolClose } from './claude-tool-result-close' @@ -90,6 +91,7 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { channel: request.openChannel(), state: 'open', dialogSeen: false, + refinable: false, ranSeen: false, reported: false, timer: null @@ -139,8 +141,8 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { return null } hold.reported = true - // The escalation usually goes out before the first poll, so read the countdown here too. - hold.expiresAt ??= claudeDialogExpiresAt(this.deps.readScreen(paneKey), this.deps.now()) + // The escalation usually goes out before the first poll, so read the dialog here too. + this.readDialog(hold, this.deps.readScreen(paneKey)) return this.payload(hold) } @@ -197,7 +199,7 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { return } hold.dialogSeen ||= shown === true - hold.expiresAt ??= claudeDialogExpiresAt(lines, this.deps.now()) + this.readDialog(hold, lines) this.watchDialog(hold) }, DIALOG_POLL_MS) } @@ -233,17 +235,24 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { } } + /** Closes the card at once; the tool's result, if it comes, only names how in a second line. */ private closeAwaitingEvidence(hold: Hold): void { - hold.state = 'closed' - this.release(hold) - void hold.channel.answer(null) - if (!hold.reported) { + const reported = hold.reported + this.close(hold, null) + if (!reported) { return } + hold.refinable = true this.closingByToolUseId.set(hold.toolUseId, hold) hold.timer = this.deps.setTimer(() => this.close(hold, null), CLOSE_EVIDENCE_MS) } + /** Claude's countdown and its warning, from the first screen that shows them. */ + private readDialog(hold: Hold, lines: readonly string[] | null): void { + hold.expiresAt ??= claudeDialogExpiresAt(lines, this.deps.now()) + hold.summary.reason ??= claudeDialogWarning(lines) + } + /** Ends a record not answered through Orca; a reported one gets its one closing line. */ private close(hold: Hold, how: CloseHow | null): void { if (hold.state === 'answered') { @@ -253,7 +262,9 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { this.release(hold) this.closingByToolUseId.delete(hold.toolUseId) void hold.channel.answer(null) - if (!hold.reported) { + const refines = hold.refinable + hold.refinable = false + if (!(hold.reported || (refines && how))) { return } hold.reported = false @@ -269,7 +280,8 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { reasonDelivered: true }) }, - this.deps + this.deps, + refines ) } diff --git a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stop-report.ts b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stop-report.ts index 0fcdae563d6..4e9f2d03a0a 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stop-report.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stop-report.ts @@ -251,14 +251,19 @@ export function reportWorkerApprovalClosed( db: OrchestrationDb, dispatch: DispatchContextRow, closed: { from: string; approval: WorkerApprovalPayload }, - deps: Pick + deps: Pick, + /** Names how an already-closed prompt closed: its card's receipt changes, the coordinator is not woken. */ + refines = false ): void { const { approval } = closed escalateWorkerFailure( db, dispatch, { - id: stopReportId(dispatch.id, `approval:${approval.approvalId}:closed`), + id: stopReportId( + dispatch.id, + `approval:${approval.approvalId}:${refines ? 'refined' : 'closed'}` + ), from: closed.from, mailbox: () => dispatchReportMailbox(db, dispatch), describe: () => ({ @@ -273,6 +278,6 @@ export function reportWorkerApprovalClosed( }, notice: true }, - deps.notify + refines ? () => {} : deps.notify ) } diff --git a/src/main/runtime/terminal/wait/claude-open-dialog-hold.ts b/src/main/runtime/terminal/wait/claude-open-dialog-hold.ts index ee8d662f339..e7e74220da3 100644 --- a/src/main/runtime/terminal/wait/claude-open-dialog-hold.ts +++ b/src/main/runtime/terminal/wait/claude-open-dialog-hold.ts @@ -60,3 +60,28 @@ export function claudeDialogExpiresAt( } return undefined } + +// Why String.raw: the orcad bundle must stay ASCII (see CURSORED_OPTION_RE). +const DASHED_RULE_RE = new RegExp(String.raw`^\s*╌`) +const BOX_LINE_RE = new RegExp(String.raw`^\s*│ ?`) +const PROCEED_RE = /Do you want to proceed\?/ + +/** The warning Claude prints under a command it flagged, the paragraph after the command's own + * dashed box and before the countdown; null when the dialog has none. */ +export function claudeDialogWarning(lines: readonly string[] | null): string | null { + const region = (lines ?? []).filter((row) => row.trim() !== '').slice(-DIALOG_REGION_LINES * 2) + const proceed = region.findLastIndex((line) => PROCEED_RE.test(line)) + const rules = region + .slice(0, Math.max(proceed, 0)) + .flatMap((line, index) => (DASHED_RULE_RE.test(line) ? [index] : [])) + // The first rule opens the command's box, the second closes it; a warning follows the second. + if (proceed === -1 || rules.length < 2) { + return null + } + const warning = region + .slice((rules.at(-1) ?? 0) + 1, proceed) + .filter((line) => BOX_LINE_RE.test(line)) + .map((line) => line.replace(BOX_LINE_RE, '').trim()) + .join(' ') + return warning || null +} diff --git a/src/shared/orchestration/approvals/worker-approval-payload.ts b/src/shared/orchestration/approvals/worker-approval-payload.ts index c358d19eb63..e2a52152b02 100644 --- a/src/shared/orchestration/approvals/worker-approval-payload.ts +++ b/src/shared/orchestration/approvals/worker-approval-payload.ts @@ -6,8 +6,8 @@ export const WorkerApprovalDecisionSchema = z.enum(['allow', 'deny']) export type WorkerApprovalDecision = z.infer /** Who settled it: a person (in Orca), the coordinator agent, someone in the worker's own chat or - * terminal, the agent's own timeout, or no one Orca can name. `terminal-only`: still open, but only - * a person at the worker's terminal can answer it now. */ + * terminal, the agent's own timeout, or no one Orca can name. `terminal-only`: closed for Orca while + * the prompt is still up; only a person at the worker's terminal can answer it. */ export const WorkerApprovalAnswererSchema = z.enum([ 'person', 'coordinator',