mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 11:54:46 +00:00
feat(orchestration): answer workers' permission prompts from the coordinator (re-land with fixes) (#41259)
* revert: worker permission approvals (#40756) This reverts commit818055fcbb. The feature misbehaves in real use: an Allow on a worker's approval card was recorded as closed without an answer, and closed approval cards render at the bottom of the coordinator chat, below newer messages. Removed: the Claude PermissionRequest hook hold and its 130 s timeout, the approval card in the coordinator chat, `orchestration deny`, the approval payload on stop escalations, and the held-delivery lines on send receipts. Escalation text goes back to its pre-#40756 wording. Kept from later commits: - #40983 (lost-worker alerts): its `lost` reason, cause/leftover/settled fields, turnStartedAt and the rejected-report check stay; only the approval branches around them are removed. - #41158 (owner moves) and the test cleanups (#41151, #41175, #41177) only touched approval code that is now deleted. * feat(orchestration): answer workers' permission prompts from the coordinator (re-land of #40756) * fix(orchestration): credit an approval from Claude's own decision record and place each worker card at its time - An Allow that Claude took is answered by the person even when the command then fails or is still running; a failed command's PostToolUseFailure counts as ran. - Expired means the agent's own timeout only; a close Orca can't name is not an expiry, and reasonDelivered is true only with a reason. - Escalations wait for the dialog to paint and read Claude's warning even when a long command hides the top of its box. - Worker cards and receipts render after the message they followed in time, not after the whole conversation; the toast says what happened. * fix(native-chat): place timed rows without a memo the compiler skips * perf(orchestration): feed chat approvals from their own stream, pin open cards, close cards whose worker ended Native chats no longer subscribe to the crew stream for worker approvals. A narrow orchestration.workerApprovalsSubscribe stream per chat party wakes only on that party's own mail and on Run/Dispatch changes, never on agent status, and reads the crew only when the approval list itself changes. The pane no longer redraws for approvals: the transcript receipts and the pinned stack each hold the feed themselves. Open worker prompts are pinned above the composer (above the chat's own prompt), oldest first, in a bounded scrolling stack; the transcript keeps only receipts, at the time the worker asked. The countdown ticks only for open cards in a visible pane. An approval whose Dispatch is no longer running reads as closed ("No longer open · worker ended"); a hook that hangs up after its worker is gone closes as worker-ended rather than "answer it in the terminal"; and a click that finds the prompt or Dispatch already gone turns the card into its receipt at once. Also carries over: a stop owes a closing line only to an approval whose escalation went out. * fix(native-chat): no toast when a worker approval answer lands; the card's receipt says it * fix(native-chat): a worker approval card answers on click, as the chat's own prompt does The card turns into 'Allowed by you' at once and Claude's confirmation runs behind it; only an answer Claude did not take changes it to the real outcome, and a failure reopens the card. * fix(orchestration): keep main's stop-report index for the open-approval sweep after the re-land * fix(orchestration): final-review fixes for chat worker approvals - A click that gets approval_not_open no longer hides the card: the host's list decides, so a prompt the host still holds stays answerable. Only dispatch_inactive closes it locally. - The approvals stream watches only the orchestration database's own changes (Runs, Dispatches, mail), not terminal identity notices, so agent status and title changes cost it nothing in main. - Receipts are the chat's history: no 30-minute window, bounded by 100 rows with still-open prompts kept first. - The pinned stack is capped against the pane and gives way first, so the chat's own prompt keeps its room; a prompt that closes while shown stays pinned as its receipt for 4 s, and one only the worker's terminal can answer stays pinned. - A close no one named, after the worker's Dispatch ended, reads as worker-ended, and an unanswered close of an ended worker sends the coordinator no second notice. - The transcript's receipts keep one array until a receipt changes. * refactor(native-chat): a worker approval card waits on the host after a click instead of answering ahead of it Both buttons turn off and the clicked one shows a spinner until the answer returns; the host's list then turns the card into its receipt. Drops the client-side close and its reconciliation. * fix(native-chat): let the compiler memoize the worker approval answer handler (cherry picked from commitb8950a4f66)
This commit is contained in:
committed by
Brennan Benson
parent
2024f8f561
commit
433d33ddfb
@@ -16,7 +16,7 @@ import {
|
||||
TerminalWorkerTurnStops
|
||||
} from '../orchestration/workers/turn-stops/terminal-worker-turn-stops'
|
||||
import { TerminalWorkerApprovalHolds } from '../orchestration/workers/approvals/terminal-worker-approval-holds'
|
||||
import { readClaudeToolResult } from '../orchestration/workers/approvals/claude-tool-result-close'
|
||||
import { readClaudeToolRecord } from '../orchestration/workers/approvals/claude-tool-result-close'
|
||||
import type { WorkerTerminalResourceRow } from '../orchestration/terminal-authority/release/worker-terminal-ownership'
|
||||
import { resolveStructuredWorkerIdentity } from '../orchestration/terminal-authority/structured-sessions/structured-worker-authority'
|
||||
import {
|
||||
@@ -84,7 +84,7 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithWin
|
||||
return process.platform !== 'win32' && pty !== null && pty.connectionId === null && !pty.isWsl
|
||||
},
|
||||
processIncarnation: (handle) => this.getTerminalProcessIncarnation(handle),
|
||||
readToolResult: (call) => readClaudeToolResult(call.transcriptPath, call.toolUseId),
|
||||
readToolRecord: (call) => readClaudeToolRecord(call.transcriptPath, call.toolUseId),
|
||||
readScreen: (paneKey) => {
|
||||
const ptyId = this.getPtyRecordForPaneKey(paneKey)?.ptyId
|
||||
return ptyId ? (this.readCaughtUpRuledScreen(ptyId)?.lines ?? null) : null
|
||||
@@ -99,8 +99,8 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithWin
|
||||
readHookRow: (paneKey) => this.agentTransitions.latestRow(paneKey),
|
||||
setTimer: unrefTimer,
|
||||
readScreen: (handle) => this.readTerminal(handle, { screen: true, limit: 15 }),
|
||||
takeOpenApproval: (paneKey, dispatchId) =>
|
||||
this.terminalWorkerApprovals.takeOpenApproval(paneKey, dispatchId)
|
||||
takeOpenApproval: (paneKey, dispatchId, reporting) =>
|
||||
this.terminalWorkerApprovals.takeOpenApproval(paneKey, dispatchId, reporting)
|
||||
})
|
||||
|
||||
private readonly externalConversations = installExternalConversations(this.store, this)
|
||||
|
||||
@@ -206,7 +206,7 @@ export function buildCrewSnapshot(
|
||||
}
|
||||
const snapshot = emptyCrew('ok')
|
||||
const approvals = Map.groupBy(
|
||||
host.sourceInputs.approvals(selfAliases(), now),
|
||||
host.sourceInputs.approvals(selfAliases()),
|
||||
({ approval }) => approval.worker.dispatchId
|
||||
)
|
||||
for (const { assignment, worker, parent } of host.relations.get(self.address) ?? []) {
|
||||
|
||||
@@ -4,7 +4,10 @@ import type { OrchestrationCoordinatorKey } from '../addressing/orchestration-ca
|
||||
import type { OrchestrationDb } from '../db/orchestration-db'
|
||||
import { exposeUtcTimestamp } from '../db/utc-timestamp'
|
||||
import { currentRunCoordinatorOrcaSessionIdSql } from '../db/runs/run-coordinator-orca-session'
|
||||
import type { WorkerApprovalPayload } from '../../../../shared/orchestration/approvals/worker-approval-payload'
|
||||
import {
|
||||
closedApproval,
|
||||
type WorkerApprovalPayload
|
||||
} from '../../../../shared/orchestration/approvals/worker-approval-payload'
|
||||
import { readApprovalReport } from '../workers/approvals/worker-approval-report'
|
||||
|
||||
const nullable = z.string().nullable()
|
||||
@@ -133,18 +136,32 @@ export function readCrewTraffic(
|
||||
)
|
||||
}
|
||||
|
||||
// Why a bound: one coordinator's open and recently closed approvals, newest report each.
|
||||
const WORKER_ENDED = {
|
||||
by: 'worker-ended',
|
||||
decision: null,
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
} as const
|
||||
|
||||
// Why a bound: one coordinator's approvals, the still-open ones first, then the newest receipts.
|
||||
const CREW_APPROVAL_ROWS = 100
|
||||
|
||||
/** Each worker approval's newest report to this party: open ones, and ones closed since `closedSince`.
|
||||
* Only Orca's own stop reports count, never a payload a worker sent itself. Oldest first. */
|
||||
/** Each worker approval's newest report to this party, oldest first: receipts are the chat's
|
||||
* history, so they stay. Only Orca's own stop reports count, never a payload a worker sent itself. */
|
||||
export function readCrewApprovals(
|
||||
db: OrchestrationDb,
|
||||
aliases: string[],
|
||||
closedSince: string
|
||||
): { approval: WorkerApprovalPayload; at: string }[] {
|
||||
aliases: string[]
|
||||
): { approval: WorkerApprovalPayload; at: string; askedAt: string }[] {
|
||||
const rows = z
|
||||
.object({ id: z.string(), payload: z.string(), created_at: z.string() })
|
||||
.object({
|
||||
id: z.string(),
|
||||
payload: z.string(),
|
||||
created_at: z.string(),
|
||||
asked_at: z.string(),
|
||||
asked_sequence: z.number(),
|
||||
ended: z.number(),
|
||||
ended_at: z.string()
|
||||
})
|
||||
.array()
|
||||
.parse(
|
||||
db.db
|
||||
@@ -153,22 +170,43 @@ export function readCrewApprovals(
|
||||
FROM messages WHERE to_handle IN (SELECT value FROM json_each(?))
|
||||
AND id LIKE 'msg\\_stop\\_%' ESCAPE '\\' AND payload LIKE '%"approval":%' AND json_valid(payload)
|
||||
AND json_type(payload, '$.approval') = 'object'
|
||||
), newest AS (SELECT approval_id, MAX(sequence) AS sequence FROM reports GROUP BY approval_id)
|
||||
SELECT reports.id, reports.payload, reports.created_at FROM reports
|
||||
JOIN newest ON newest.sequence = reports.sequence
|
||||
WHERE json_extract(reports.payload, '$.approval.state') = 'open'
|
||||
OR julianday(reports.created_at) >= julianday(?)
|
||||
ORDER BY reports.sequence DESC LIMIT ${CREW_APPROVAL_ROWS}`)
|
||||
.all(JSON.stringify(aliases), closedSince)
|
||||
), newest AS (SELECT approval_id, MAX(sequence) AS sequence, MIN(created_at) AS asked_at,
|
||||
MIN(sequence) AS asked_sequence
|
||||
FROM reports GROUP BY approval_id)
|
||||
SELECT reports.id, reports.payload, reports.created_at, newest.asked_at, newest.asked_sequence,
|
||||
d.status IS NOT NULL AND d.status NOT IN ('pending', 'dispatched') AS ended,
|
||||
COALESCE(d.completed_at, reports.created_at) AS ended_at
|
||||
FROM reports JOIN newest ON newest.sequence = reports.sequence
|
||||
LEFT JOIN dispatch_contexts d ON d.id = json_extract(reports.payload, '$.approval.worker.dispatchId')
|
||||
-- The bound never hides one still waiting on an answer.
|
||||
ORDER BY (json_extract(reports.payload, '$.approval.state') = 'open'
|
||||
AND (d.status IS NULL OR d.status IN ('pending', 'dispatched'))) DESC,
|
||||
reports.sequence DESC
|
||||
LIMIT ${CREW_APPROVAL_ROWS}`)
|
||||
.all(JSON.stringify(aliases))
|
||||
)
|
||||
const shown: { approval: WorkerApprovalPayload; at: string }[] = []
|
||||
.toSorted((a, b) => a.asked_sequence - b.asked_sequence)
|
||||
const shown: { approval: WorkerApprovalPayload; at: string; askedAt: string }[] = []
|
||||
for (const row of rows) {
|
||||
const approval = readApprovalReport(row)
|
||||
if (approval) {
|
||||
shown.push({ approval, at: exposeUtcTimestamp(row.created_at) ?? row.created_at })
|
||||
if (!approval) {
|
||||
continue
|
||||
}
|
||||
// A prompt is answerable only while its Dispatch runs: once that ends it is closed, and a
|
||||
// terminal that is gone, or a close no one named, was the worker ending.
|
||||
const ended =
|
||||
row.ended === 1 &&
|
||||
(approval.state === 'open' ||
|
||||
approval.outcome?.by === 'terminal-only' ||
|
||||
approval.outcome?.by === 'unknown')
|
||||
const at = ended ? row.ended_at : row.created_at
|
||||
shown.push({
|
||||
approval: ended ? closedApproval(approval, WORKER_ENDED) : approval,
|
||||
at: exposeUtcTimestamp(at) ?? at,
|
||||
askedAt: exposeUtcTimestamp(row.asked_at) ?? row.asked_at
|
||||
})
|
||||
}
|
||||
return shown.toReversed()
|
||||
return shown
|
||||
}
|
||||
|
||||
export function readCrewQuestions(db: OrchestrationDb, aliases: string[]) {
|
||||
|
||||
@@ -222,12 +222,9 @@ export function createCrewSourceInputs(db: OrchestrationDb | null, capacity = ()
|
||||
const input = mailbox(aliases)
|
||||
return (input.questions ??= db ? readCrewQuestions(db, aliases) : [])
|
||||
}
|
||||
// Closed approvals stay as receipts for as long as traffic counts as recent.
|
||||
const approvals = (aliases: string[], now: number) => {
|
||||
const approvals = (aliases: string[]) => {
|
||||
const input = mailbox(aliases)
|
||||
return (input.approvals ??= db
|
||||
? readCrewApprovals(db, aliases, new Date(now - AGENT_STATUS_STALE_AFTER_MS).toISOString())
|
||||
: [])
|
||||
return (input.approvals ??= db ? readCrewApprovals(db, aliases) : [])
|
||||
}
|
||||
const invalidateTraffic = (addresses?: ReadonlySet<string>) => {
|
||||
for (const [key, input] of mail) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { fixture } from './crew-read-model.test-fixture'
|
||||
import { buildCrewSnapshot } from './crew-party-snapshot'
|
||||
import { approvalReportId } from '../workers/approvals/worker-approval-report'
|
||||
|
||||
it("puts each approval's newest report on its worker's row, drops stale receipts, and ignores rows Orca did not write", () => {
|
||||
it("puts each approval's newest report on its worker's row, keeps old receipts, and ignores rows Orca did not write", () => {
|
||||
const { db, deps, run, assign } = fixture()
|
||||
const dispatch = assign('term_worker')
|
||||
const send = (approvalId: string, state: 'open' | 'answered', own = true) =>
|
||||
@@ -43,7 +43,9 @@ it("puts each approval's newest report on its worker's row, drops stale receipts
|
||||
send('apr_open', 'answered', false)
|
||||
|
||||
const [row] = buildCrewSnapshot('term_coord', deps).sections.managing
|
||||
// Receipts are the chat's history: one closed hours ago stays.
|
||||
expect(row.approvals?.map(({ approval }) => [approval.approvalId, approval.state])).toEqual([
|
||||
['apr_old', 'answered'],
|
||||
['apr_answered', 'answered'],
|
||||
['apr_open', 'open']
|
||||
])
|
||||
@@ -81,5 +83,72 @@ it('keeps showing an open approval behind more closed ones than the row bound',
|
||||
.run('apr_still_open')
|
||||
|
||||
const [row] = buildCrewSnapshot('term_coord', deps).sections.managing
|
||||
expect(row.approvals?.map(({ approval }) => approval.approvalId)).toEqual(['apr_still_open'])
|
||||
const ids = row.approvals?.map(({ approval }) => approval.approvalId)
|
||||
expect(ids).toHaveLength(100)
|
||||
expect(ids?.[0]).toBe('apr_still_open')
|
||||
expect(ids?.at(-1)).toBe('apr_149')
|
||||
})
|
||||
|
||||
it('closes an open approval once its Dispatch stops running, at the time it ended', () => {
|
||||
const { db, deps, run, assign } = fixture()
|
||||
const dispatch = assign('term_worker')
|
||||
db.insertMessage({
|
||||
id: approvalReportId(dispatch.id, 'apr_open', 'open'),
|
||||
from: 'term_worker',
|
||||
to: `run:${run.id}`,
|
||||
subject: 'apr_open',
|
||||
type: 'escalation',
|
||||
runId: run.id,
|
||||
payload: JSON.stringify({
|
||||
approval: {
|
||||
v: 1,
|
||||
approvalId: 'apr_open',
|
||||
state: 'open',
|
||||
worker: { handle: 'term_worker', dispatchId: dispatch.id, taskId: dispatch.task_id },
|
||||
summary: { title: 'Allow Bash?', detail: null, reason: null },
|
||||
allowedActions: ['allow', 'deny'],
|
||||
expiresAt: '2099-01-01T00:00:00.000Z'
|
||||
}
|
||||
})
|
||||
})
|
||||
db.completeDispatch(dispatch.id)
|
||||
|
||||
const [row] = buildCrewSnapshot('term_coord', deps).sections.managing
|
||||
expect(row.approvals?.map(({ approval }) => approval)).toEqual([
|
||||
expect.objectContaining({
|
||||
approvalId: 'apr_open',
|
||||
state: 'answered',
|
||||
allowedActions: [],
|
||||
outcome: { by: 'worker-ended', decision: null, reason: null, reasonDelivered: false }
|
||||
})
|
||||
])
|
||||
expect(row.approvals?.[0].approval.expiresAt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reads a close no one named, after its Dispatch ended, as the worker ending', () => {
|
||||
const { db, deps, run, assign } = fixture()
|
||||
const dispatch = assign('term_worker')
|
||||
db.insertMessage({
|
||||
id: approvalReportId(dispatch.id, 'apr_unnamed', 'closed'),
|
||||
from: 'term_worker',
|
||||
to: `run:${run.id}`,
|
||||
subject: 'apr_unnamed',
|
||||
type: 'status',
|
||||
runId: run.id,
|
||||
payload: JSON.stringify({
|
||||
approval: {
|
||||
v: 1,
|
||||
approvalId: 'apr_unnamed',
|
||||
state: 'answered',
|
||||
worker: { handle: 'term_worker', dispatchId: dispatch.id, taskId: dispatch.task_id },
|
||||
summary: { title: 'Allow Bash?', detail: null, reason: null },
|
||||
allowedActions: [],
|
||||
outcome: { by: 'unknown', decision: null, reason: null, reasonDelivered: false }
|
||||
}
|
||||
})
|
||||
})
|
||||
db.completeDispatch(dispatch.id)
|
||||
|
||||
const [row] = buildCrewSnapshot('term_coord', deps).sections.managing
|
||||
expect(row.approvals?.map(({ approval }) => approval.outcome?.by)).toEqual(['worker-ended'])
|
||||
})
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { subscribeWorkerApprovals } from './worker-approval-stream'
|
||||
import type { CrewInvalidation } from './crew-changes'
|
||||
import type {
|
||||
OrchestrationCrewRow,
|
||||
OrchestrationWorkerApprovalsFrame
|
||||
} from '../../../../shared/orchestration/orchestration-crew'
|
||||
|
||||
const approval = {
|
||||
v: 1 as const,
|
||||
approvalId: 'apr_1',
|
||||
state: 'open' as const,
|
||||
worker: { handle: 'term_w', dispatchId: 'ctx_1', taskId: 'task_1' },
|
||||
summary: { title: 'Allow Bash?', detail: null, reason: null },
|
||||
allowedActions: ['allow' as const, 'deny' as const]
|
||||
}
|
||||
|
||||
it("delivers a worker's prompt mailed to a Run the chat started coordinating after it subscribed", async () => {
|
||||
const runs = ['run:a']
|
||||
const mail = new Map<string, unknown[]>()
|
||||
const worker: OrchestrationCrewRow = {
|
||||
partyKey: 'w',
|
||||
role: 'worker',
|
||||
label: 'try-claude',
|
||||
agentKind: 'claude',
|
||||
status: 'blocked'
|
||||
}
|
||||
let wake: (facets: CrewInvalidation) => void = () => {}
|
||||
const frames: OrchestrationWorkerApprovalsFrame[] = []
|
||||
subscribeWorkerApprovals(
|
||||
{
|
||||
mailboxes: () => ['orca_session_id:chat', ...runs],
|
||||
approvals: (mailboxes) => mailboxes.flatMap((mailbox) => mail.get(mailbox) ?? []),
|
||||
workers: () => (mail.size ? [{ ...worker, approvals: [{ approval, at: 't1' }] }] : []),
|
||||
watch: (listener) => {
|
||||
wake = listener
|
||||
return () => {}
|
||||
}
|
||||
},
|
||||
(frame) => frames.push(frame)
|
||||
)
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve))
|
||||
|
||||
runs.push('run:b')
|
||||
wake(new Set(['topology']))
|
||||
await settle()
|
||||
mail.set('run:b', [approval])
|
||||
wake(Object.assign(new Set(['traffic'] as const), { trafficAddresses: new Set(['run:b']) }))
|
||||
await settle()
|
||||
|
||||
expect(frames).toEqual([
|
||||
{ type: 'begin' },
|
||||
{ type: 'complete' },
|
||||
{ type: 'begin' },
|
||||
{ type: 'approval', entry: { approval, at: 't1', worker } },
|
||||
{ type: 'complete' }
|
||||
])
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { CrewInvalidation } from './crew-changes'
|
||||
import type {
|
||||
OrchestrationCrewRow,
|
||||
OrchestrationWorkerApprovalEntry,
|
||||
OrchestrationWorkerApprovalsFrame
|
||||
} from '../../../../shared/orchestration/orchestration-crew'
|
||||
|
||||
export type WorkerApprovalStreamSources = {
|
||||
/** The mailboxes the party's workers report to; re-read only when topology changes. */
|
||||
mailboxes: () => string[]
|
||||
/** The approval rows in those mailboxes, compared to tell whether anything changed. */
|
||||
approvals: (mailboxes: string[]) => unknown[]
|
||||
/** The party's workers, each with its approvals; read only once the approval rows changed. */
|
||||
workers: () => readonly OrchestrationCrewRow[]
|
||||
watch: (wake: (facets: CrewInvalidation) => void) => () => void
|
||||
}
|
||||
|
||||
/** A chat's worker approvals: woken by its own mail and Run changes, never by agent status, so an
|
||||
* agent's turn costs a chat nothing; the crew is read only when the approvals themselves change. */
|
||||
export function subscribeWorkerApprovals(
|
||||
sources: WorkerApprovalStreamSources,
|
||||
emit: (frame: OrchestrationWorkerApprovalsFrame) => void
|
||||
): () => void {
|
||||
let alive = true
|
||||
let queued = false
|
||||
let mailboxes: Set<string> | undefined
|
||||
// Mail arrived for the party since the last read; a first read has everything to read.
|
||||
let mailed = true
|
||||
let previous: string | undefined
|
||||
let readMailboxes: string | undefined
|
||||
const publish = () => {
|
||||
if (!alive) {
|
||||
return
|
||||
}
|
||||
let entries: OrchestrationWorkerApprovalEntry[]
|
||||
try {
|
||||
mailboxes ??= new Set(sources.mailboxes())
|
||||
const key = [...mailboxes].join('\n')
|
||||
// A Run or Dispatch change matters only to listed approvals or to the mailboxes it moves;
|
||||
// new approvals arrive as mail.
|
||||
if (!mailed && key === readMailboxes && previous === '[]') {
|
||||
return
|
||||
}
|
||||
mailed = false
|
||||
readMailboxes = key
|
||||
const rows = mailboxes.size ? sources.approvals([...mailboxes]) : []
|
||||
const serialized = JSON.stringify(rows)
|
||||
if (serialized === previous) {
|
||||
return
|
||||
}
|
||||
previous = serialized
|
||||
entries = rows.length ? approvalEntries(sources.workers()) : []
|
||||
} catch {
|
||||
// Read again on the next change rather than show a partial list.
|
||||
mailboxes = undefined
|
||||
mailed = true
|
||||
previous = undefined
|
||||
readMailboxes = undefined
|
||||
return
|
||||
}
|
||||
emit({ type: 'begin' })
|
||||
for (const entry of entries) {
|
||||
emit({ type: 'approval', entry })
|
||||
}
|
||||
emit({ type: 'complete' })
|
||||
}
|
||||
const unwatch = sources.watch((facets) => {
|
||||
const addressed = facets.has('traffic') ? facets.trafficAddresses : undefined
|
||||
if (addressed) {
|
||||
if (mailboxes && ![...addressed].some((address) => mailboxes!.has(address))) {
|
||||
return
|
||||
}
|
||||
mailed = true
|
||||
} else if (facets.has('topology') || facets.has('traffic')) {
|
||||
// Runs, Dispatches or routing moved: Orca's approval reports are only ever inserted, addressed.
|
||||
mailboxes = undefined
|
||||
} else {
|
||||
return
|
||||
}
|
||||
if (queued) {
|
||||
return
|
||||
}
|
||||
queued = true
|
||||
queueMicrotask(() => {
|
||||
queued = false
|
||||
publish()
|
||||
})
|
||||
})
|
||||
publish()
|
||||
return () => {
|
||||
alive = false
|
||||
unwatch()
|
||||
}
|
||||
}
|
||||
|
||||
function approvalEntries(
|
||||
workers: readonly OrchestrationCrewRow[]
|
||||
): OrchestrationWorkerApprovalEntry[] {
|
||||
return workers
|
||||
.flatMap(({ approvals, ...worker }) => (approvals ?? []).map((entry) => ({ ...entry, worker })))
|
||||
.sort((a, b) => (a.askedAt ?? a.at).localeCompare(b.askedAt ?? b.at))
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import { claudeTookHookAnswer, readClaudeToolRecord } from './claude-tool-result-close'
|
||||
|
||||
let dir: string | null = null
|
||||
afterEach(async () => {
|
||||
if (dir) {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
dir = null
|
||||
})
|
||||
|
||||
it("takes an allowed call whose command then failed as Orca's allow, from Claude's own transcript", async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), 'claude-tool-record-'))
|
||||
const transcript = path.join(dir, 'session.jsonl')
|
||||
// The lines Claude 2.1.322 wrote for the owner's live case (2026-11-11), trimmed to what is read.
|
||||
await writeFile(
|
||||
transcript,
|
||||
[
|
||||
'{"type":"attachment","attachment":{"type":"hook_permission_decision","decision":"allow","toolUseID":"toolu_live","hookEvent":"PermissionRequest"}}',
|
||||
'{"type":"attachment","attachment":{"type":"hook_success","hookEvent":"PostToolUseFailure","toolUseID":"toolu_live"}}',
|
||||
'{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_live","is_error":true,"content":"Exit code 1\\n(eval):14: parse error near `\\\\n\'"}]}}'
|
||||
].join('\n')
|
||||
)
|
||||
|
||||
const record = await readClaudeToolRecord(transcript, 'toolu_live')
|
||||
expect(record).toEqual({
|
||||
hookDecision: 'allow',
|
||||
result: { isError: true, text: "Exit code 1\n(eval):14: parse error near `\\n'" }
|
||||
})
|
||||
expect(claudeTookHookAnswer(record!, 'allow', 'use a script file')).toBe(true)
|
||||
expect(claudeTookHookAnswer(record!, 'deny', 'use a script file')).toBe(false)
|
||||
expect(await readClaudeToolRecord(transcript, 'toolu_other')).toBeNull()
|
||||
})
|
||||
@@ -1,10 +1,17 @@
|
||||
/** How Claude closed a permission prompt, from the tool_result its transcript records for that tool
|
||||
* 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. */
|
||||
/** How Claude closed a permission prompt, from what its transcript records for that tool call
|
||||
* (probes 2026-11-10/11, Claude 2.1.322): the hook decision it took, written as soon as it takes
|
||||
* it, and the tool_result: a hook's deny message verbatim, the user's No, the 2:00 safety-check
|
||||
* block, or the command's own output, which is an error when an allowed command fails. Hook events
|
||||
* do not say this: a deny or a No fires no PostToolUse or PostToolUseFailure. */
|
||||
import { open, stat, type FileHandle } from 'node:fs/promises'
|
||||
import type { WorkerApprovalOutcome } from '../../../../../shared/orchestration/approvals/worker-approval-payload'
|
||||
|
||||
export type ClaudeToolResult = { isError: boolean; text: string }
|
||||
/** What the transcript holds for one call so far: the hook decision Claude took, then its result. */
|
||||
export type ClaudeToolRecord = {
|
||||
hookDecision: 'allow' | 'deny' | null
|
||||
result: ClaudeToolResult | null
|
||||
}
|
||||
export type ClaudeToolClose = 'hook-denied' | 'user-denied' | 'auto-denied' | 'ran' | 'other'
|
||||
|
||||
// Why a tail: the newest tool call's result is at the end of a transcript that can be many MB.
|
||||
@@ -12,11 +19,12 @@ 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'
|
||||
|
||||
/** Null unless the path is a regular file: a FIFO or device would never finish a read. */
|
||||
export async function readClaudeToolResult(
|
||||
/** Null until the transcript holds either for this call, or unless the path is a regular file: a FIFO
|
||||
* or device would never finish a read. */
|
||||
export async function readClaudeToolRecord(
|
||||
transcriptPath: string,
|
||||
toolUseId: string
|
||||
): Promise<ClaudeToolResult | null> {
|
||||
): Promise<ClaudeToolRecord | null> {
|
||||
let file: FileHandle | null = null
|
||||
try {
|
||||
// Why stat before open: opening a FIFO waits for a writer.
|
||||
@@ -32,14 +40,13 @@ export async function readClaudeToolResult(
|
||||
length,
|
||||
stats.size - length
|
||||
)
|
||||
const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n')
|
||||
for (const line of lines.toReversed()) {
|
||||
const result = line.includes(toolUseId) ? toolResultIn(line, toolUseId) : null
|
||||
if (result) {
|
||||
return result
|
||||
}
|
||||
const record: ClaudeToolRecord = { hookDecision: null, result: null }
|
||||
for (const line of buffer.subarray(0, bytesRead).toString('utf8').split('\n')) {
|
||||
const entry = line.includes(toolUseId) ? parseLine(line) : null
|
||||
record.hookDecision ??= hookDecisionIn(entry, toolUseId)
|
||||
record.result ??= toolResultIn(entry, toolUseId)
|
||||
}
|
||||
return null
|
||||
return record.hookDecision || record.result ? record : null
|
||||
} catch {
|
||||
return null
|
||||
} finally {
|
||||
@@ -47,13 +54,28 @@ export async function readClaudeToolResult(
|
||||
}
|
||||
}
|
||||
|
||||
function toolResultIn(line: string, toolUseId: string): ClaudeToolResult | null {
|
||||
let entry: unknown
|
||||
function parseLine(line: string): unknown {
|
||||
try {
|
||||
entry = JSON.parse(line)
|
||||
return JSON.parse(line)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** `{type: 'attachment', attachment: {type: 'hook_permission_decision', decision, toolUseID}}`. */
|
||||
function hookDecisionIn(entry: unknown, toolUseId: string): 'allow' | 'deny' | null {
|
||||
const attachment = isRecord(entry) && isRecord(entry.attachment) ? entry.attachment : null
|
||||
if (
|
||||
attachment?.type !== 'hook_permission_decision' ||
|
||||
attachment.toolUseID !== toolUseId ||
|
||||
(attachment.decision !== 'allow' && attachment.decision !== 'deny')
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return attachment.decision
|
||||
}
|
||||
|
||||
function toolResultIn(entry: unknown, toolUseId: string): ClaudeToolResult | null {
|
||||
const content = isRecord(entry) && isRecord(entry.message) ? entry.message.content : null
|
||||
if (!Array.isArray(content)) {
|
||||
return null
|
||||
@@ -94,3 +116,38 @@ export function claudeToolClose(result: ClaudeToolResult, ourDeny: string | null
|
||||
}
|
||||
return result.text.includes(AUTO_DENIED) ? 'auto-denied' : 'other'
|
||||
}
|
||||
|
||||
/** Whether Claude took Orca's hook answer for this call. Its record of the hook decision says so
|
||||
* outright, before the tool even runs; without one (an older Claude), only a result that answer
|
||||
* alone gives: our deny text, or, after an allow, anything but a person's No or the auto-block,
|
||||
* since an allowed command that fails records an error result too. */
|
||||
export function claudeTookHookAnswer(
|
||||
record: ClaudeToolRecord,
|
||||
decision: 'allow' | 'deny',
|
||||
denyMessage: string
|
||||
): boolean {
|
||||
if (record.hookDecision) {
|
||||
return record.hookDecision === decision
|
||||
}
|
||||
if (!record.result) {
|
||||
return false
|
||||
}
|
||||
const close = claudeToolClose(record.result, decision === 'deny' ? denyMessage : null)
|
||||
return decision === 'deny' ? close === 'hook-denied' : close === 'ran' || close === 'other'
|
||||
}
|
||||
|
||||
// How each tool_result names a close Orca did not make; null says no more than "closed".
|
||||
const CLOSE_HOW: Record<ClaudeToolClose, Pick<WorkerApprovalOutcome, 'by' | 'decision'> | 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
|
||||
}
|
||||
|
||||
/** Who closed a prompt Orca did not answer, from this call's result; null when it names no one. */
|
||||
export function claudeToolCloseHow(
|
||||
result: ClaudeToolResult | null
|
||||
): Pick<WorkerApprovalOutcome, 'by' | 'decision'> | null {
|
||||
return result ? CLOSE_HOW[claudeToolClose(result, null)] : null
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { ClaudePermissionHookChannel } from '../../../../agent-hooks/server
|
||||
import type { OrchestrationDb } from '../../db/orchestration-db'
|
||||
import type { DispatchContextRow } from '../../db/orchestration-records'
|
||||
import type { WorkerTurnStopReportDeps } from '../turn-stops/worker-turn-stop-report'
|
||||
import type { ClaudeToolResult } from './claude-tool-result-close'
|
||||
import type { ClaudeToolRecord } from './claude-tool-result-close'
|
||||
import type {
|
||||
WorkerApprovalOutcome,
|
||||
WorkerApprovalPayload
|
||||
@@ -20,11 +20,11 @@ export type TerminalWorkerApprovalHoldsDeps = Pick<WorkerTurnStopReportDeps, 'no
|
||||
processIncarnation: (handle: string) => string | null
|
||||
/** 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: {
|
||||
/** The hook decision and tool_result Claude's transcript records for this tool call, once written. */
|
||||
readToolRecord: (call: {
|
||||
transcriptPath: string
|
||||
toolUseId: string
|
||||
}) => Promise<ClaudeToolResult | null>
|
||||
}) => Promise<ClaudeToolRecord | null>
|
||||
now: () => number
|
||||
setTimer: (run: () => void, delayMs: number) => { cancel: () => void }
|
||||
}
|
||||
@@ -45,7 +45,7 @@ export type TerminalWorkerApprovalHold = {
|
||||
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. */
|
||||
/** Its PostToolUse or PostToolUseFailure arrived while an answer was in flight: the tool ran. */
|
||||
ranSeen: boolean
|
||||
expiresAt?: string
|
||||
/** The coordinator was told about it, so it is owed one closing line. */
|
||||
|
||||
+198
-32
@@ -14,7 +14,7 @@ import { createRootDispatch } from '../../db/root-dispatch-test-fixture'
|
||||
import { TerminalWorkerApprovalHolds } from './terminal-worker-approval-holds'
|
||||
import { closeOrphanedTerminalApprovals } from './terminal-approval-orphans'
|
||||
import { approvalReportId } from './worker-approval-report'
|
||||
import type { ClaudeToolResult } from './claude-tool-result-close'
|
||||
import type { ClaudeToolRecord, ClaudeToolResult } from './claude-tool-result-close'
|
||||
|
||||
const PANE = makePaneKey('tab-worker', '11111111-1111-4111-8111-111111111111')
|
||||
const HANDLE = 'term_worker'
|
||||
@@ -43,6 +43,21 @@ const USER_NO: ClaudeToolResult = {
|
||||
isError: true,
|
||||
text: "The user doesn't want to proceed with this tool use. The tool use was rejected."
|
||||
}
|
||||
const AUTO_BLOCK: ClaudeToolResult = {
|
||||
isError: true,
|
||||
text: 'Permission for this command was denied by a built-in Claude Code safety check, not by the user.'
|
||||
}
|
||||
// An allowed command that then fails (probe 2026-11-11, the owner's live case).
|
||||
const FAILED: ClaudeToolResult = {
|
||||
isError: true,
|
||||
text: "Exit code 1\n(eval):14: parse error near `\\n'"
|
||||
}
|
||||
const RAN: ClaudeToolResult = { isError: false, text: '59' }
|
||||
/** What the transcript holds: the hook decision Claude took, then the tool's result. */
|
||||
const record = (
|
||||
result: ClaudeToolResult | null,
|
||||
hookDecision: ClaudeToolRecord['hookDecision'] = null
|
||||
): ClaudeToolRecord => ({ hookDecision, result })
|
||||
|
||||
function setup(options: { canAnswer?: boolean } = {}) {
|
||||
const db = new OrchestrationDb(':memory:')
|
||||
@@ -56,8 +71,8 @@ function setup(options: { canAnswer?: boolean } = {}) {
|
||||
const screen: {
|
||||
lines: readonly string[] | null
|
||||
incarnation: string
|
||||
result: ClaudeToolResult | null
|
||||
} = { lines: DIALOG, incarnation: 'run-1', result: null }
|
||||
record: ClaudeToolRecord | null
|
||||
} = { lines: DIALOG, incarnation: 'run-1', record: null }
|
||||
const timers: { run: () => void; cancelled: boolean }[] = []
|
||||
const holds = new TerminalWorkerApprovalHolds({
|
||||
notify: vi.fn(),
|
||||
@@ -65,8 +80,8 @@ function setup(options: { canAnswer?: boolean } = {}) {
|
||||
canAnswerPane: () => options.canAnswer ?? true,
|
||||
processIncarnation: () => screen.incarnation,
|
||||
readScreen: () => screen.lines,
|
||||
readToolResult: async ({ transcriptPath, toolUseId }) =>
|
||||
transcriptPath === '/t/session.jsonl' && toolUseId === 'tool-1' ? screen.result : null,
|
||||
readToolRecord: async ({ transcriptPath, toolUseId }) =>
|
||||
transcriptPath === '/t/session.jsonl' && toolUseId === 'tool-1' ? screen.record : null,
|
||||
now: () => Date.UTC(2026, 10, 10, 12, 0, 0),
|
||||
setTimer: (run) => {
|
||||
const timer = { run, cancelled: false }
|
||||
@@ -90,7 +105,12 @@ function setup(options: { canAnswer?: boolean } = {}) {
|
||||
.getUnreadRunMailbox(run.id, 100)
|
||||
.filter((message) => message.subject.startsWith('Worker approval '))
|
||||
const closing = () => closings().map((message) => message.body)
|
||||
return { db, dispatch, screen, holds, tick, closing, closings }
|
||||
const closedWith = () =>
|
||||
closings().map((message) => {
|
||||
const { approval } = JSON.parse(message.payload ?? '{}')
|
||||
return { state: approval.state, ...approval.outcome }
|
||||
})
|
||||
return { db, dispatch, screen, holds, tick, closing, closings, closedWith }
|
||||
}
|
||||
|
||||
function hook(
|
||||
@@ -127,11 +147,14 @@ function hook(
|
||||
}
|
||||
}
|
||||
|
||||
function postToolUse(toolUseId: string): AgentHookEventPayload {
|
||||
function postToolUse(
|
||||
toolUseId: string,
|
||||
hookEventName: 'PostToolUse' | 'PostToolUseFailure' = 'PostToolUse'
|
||||
): AgentHookEventPayload {
|
||||
return {
|
||||
paneKey: PANE,
|
||||
connectionId: null,
|
||||
hookEventName: 'PostToolUse',
|
||||
hookEventName,
|
||||
toolUseId,
|
||||
payload: { state: 'working', prompt: '', agentType: 'claude' }
|
||||
}
|
||||
@@ -140,23 +163,40 @@ function postToolUse(toolUseId: string): AgentHookEventPayload {
|
||||
async function opened(ctx: ReturnType<typeof setup>, asked: ReturnType<typeof hook>) {
|
||||
ctx.holds.admit(asked.request)
|
||||
await ctx.tick()
|
||||
return ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id)!.approvalId
|
||||
return (await ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id))!.approvalId
|
||||
}
|
||||
|
||||
const deny = (ctx: ReturnType<typeof setup>, approvalId: string) =>
|
||||
ctx.holds.answer({
|
||||
dispatchId: ctx.dispatch.id,
|
||||
approvalId,
|
||||
decision: 'deny',
|
||||
message: REASON
|
||||
const answer = (
|
||||
ctx: ReturnType<typeof setup>,
|
||||
approvalId: string,
|
||||
decision: 'allow' | 'deny' = 'deny'
|
||||
) => ctx.holds.answer({ dispatchId: ctx.dispatch.id, approvalId, decision, message: REASON })
|
||||
const deny = (ctx: ReturnType<typeof setup>, approvalId: string) => answer(ctx, approvalId)
|
||||
|
||||
/** The dialog leaves without Orca's answer, then the lead's turn ends with `result` written. */
|
||||
async function closedInTerminal(ctx: ReturnType<typeof setup>, result: ClaudeToolResult) {
|
||||
const approvalId = 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.isHeld(approvalId); i++) {
|
||||
await ctx.tick()
|
||||
}
|
||||
ctx.screen.record = record(result)
|
||||
ctx.holds.observe({
|
||||
paneKey: PANE,
|
||||
connectionId: null,
|
||||
hookEventName: 'Stop',
|
||||
payload: { state: 'done', prompt: '', agentType: 'claude' }
|
||||
})
|
||||
await vi.waitFor(() => expect(ctx.closing()).toHaveLength(2))
|
||||
}
|
||||
|
||||
describe('terminal worker approval holds', () => {
|
||||
it("claims a deny only from this call's tool_result, despite an older deny line on screen", async () => {
|
||||
const ctx = setup()
|
||||
const asked = hook('tool-1', () => {
|
||||
ctx.screen.lines = AFTER
|
||||
ctx.screen.result = OURS
|
||||
ctx.screen.record = record(OURS, 'deny')
|
||||
})
|
||||
const approvalId = await opened(ctx, asked)
|
||||
|
||||
@@ -181,32 +221,158 @@ describe('terminal worker approval holds', () => {
|
||||
|
||||
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
|
||||
// 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(2))
|
||||
await closedInTerminal(ctx, USER_NO)
|
||||
|
||||
// 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")
|
||||
])
|
||||
// Not an expiry: only the agent's own timeout is one.
|
||||
expect(ctx.closedWith()[0]).toMatchObject({ state: 'answered', by: 'unknown' })
|
||||
})
|
||||
|
||||
it('closes a prompt left open by an earlier run, once, when the database opens', () => {
|
||||
it.each([
|
||||
['allowed, and the command succeeds', record(RAN, 'allow')],
|
||||
['allowed, and the command fails', record(FAILED, 'allow')],
|
||||
['allowed, and the command is still running', record(null, 'allow')],
|
||||
['allowed by a Claude that records no hook decision, and the command fails', record(FAILED)]
|
||||
])("takes Orca's allow when %s", async (_, written) => {
|
||||
const ctx = setup()
|
||||
const asked = hook('tool-1', () => {
|
||||
ctx.screen.lines = AFTER
|
||||
ctx.screen.record = written
|
||||
})
|
||||
const approvalId = await opened(ctx, asked)
|
||||
|
||||
expect(await answer(ctx, approvalId, 'allow')).toMatchObject({ ok: true })
|
||||
expect(asked.replies).toEqual([{ behavior: 'allow' }])
|
||||
})
|
||||
|
||||
it("doesn't take Orca's allow when the person's No won the race", async () => {
|
||||
const ctx = setup()
|
||||
const approvalId = await opened(
|
||||
ctx,
|
||||
hook('tool-1', () => {
|
||||
ctx.screen.lines = AFTER
|
||||
ctx.screen.record = record(USER_NO)
|
||||
})
|
||||
)
|
||||
|
||||
expect(await answer(ctx, approvalId, 'allow')).toMatchObject({ code: 'approval_not_open' })
|
||||
expect(ctx.closedWith()).toEqual([
|
||||
{
|
||||
state: 'answered',
|
||||
by: 'worker-terminal',
|
||||
decision: 'deny',
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it("names a Yes in the terminal whose command failed as allowed in the worker's terminal", async () => {
|
||||
const ctx = setup()
|
||||
await opened(ctx, hook('tool-1'))
|
||||
ctx.screen.lines = AFTER
|
||||
ctx.holds.observe(postToolUse('tool-1', 'PostToolUseFailure'))
|
||||
|
||||
expect(ctx.closedWith()).toEqual([
|
||||
{
|
||||
state: 'answered',
|
||||
by: 'worker-terminal',
|
||||
decision: 'allow',
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it("names Claude's 2:00 auto-block as an expiry", async () => {
|
||||
const ctx = setup()
|
||||
await closedInTerminal(ctx, AUTO_BLOCK)
|
||||
|
||||
expect(ctx.closedWith()[1]).toEqual({
|
||||
state: 'expired',
|
||||
by: 'auto',
|
||||
decision: 'deny',
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
})
|
||||
})
|
||||
|
||||
it("tells the coordinator to send the user to the terminal when the hook is gone but the dialog isn't", async () => {
|
||||
const ctx = setup()
|
||||
const asked = hook('tool-1')
|
||||
await opened(ctx, asked)
|
||||
asked.end('hook-gone')
|
||||
await ctx.tick(40)
|
||||
|
||||
expect(ctx.closings()).toEqual([
|
||||
expect.objectContaining({
|
||||
type: 'escalation',
|
||||
body: expect.stringContaining("Tell the user to answer it in the worker's terminal")
|
||||
})
|
||||
])
|
||||
})
|
||||
|
||||
it('closes as worker ended, not "answer it in the terminal", when the worker is stopped at the prompt', async () => {
|
||||
const ctx = setup()
|
||||
const asked = hook('tool-1')
|
||||
await opened(ctx, asked)
|
||||
// A stop kills the process; its last screen still shows the dialog.
|
||||
ctx.screen.incarnation = 'run-2'
|
||||
asked.end('hook-gone')
|
||||
await ctx.tick(40)
|
||||
|
||||
expect(ctx.closedWith()).toEqual([
|
||||
{
|
||||
state: 'answered',
|
||||
by: 'worker-ended',
|
||||
decision: null,
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it("escalates with Claude's reason once the dialog paints, though a long command hides its box's top", async () => {
|
||||
const ctx = setup()
|
||||
// The live case (2026-11-11): the escalation came before the paint, and the command was so long
|
||||
// that only the rule closing its box was on screen.
|
||||
ctx.screen.lines = null
|
||||
ctx.holds.admit(hook('tool-1').request)
|
||||
const escalating = ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id)
|
||||
ctx.screen.lines = [
|
||||
...Array.from({ length: 30 }, (_, line) => ` │ s=s.replace("import ${line}")`),
|
||||
' │ fs.writeFileSync(p,s)\'; rg -n "ComputerBots" BotSettingsGroups.tsx',
|
||||
' ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌',
|
||||
' │ Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed',
|
||||
...DIALOG.slice(2)
|
||||
]
|
||||
await ctx.tick(2)
|
||||
|
||||
expect((await escalating)?.summary.reason).toBe(
|
||||
'Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed'
|
||||
)
|
||||
})
|
||||
|
||||
it('owes no closing line to a prompt whose escalation never went out', async () => {
|
||||
const ctx = setup()
|
||||
const asked = hook('tool-1')
|
||||
ctx.holds.admit(asked.request)
|
||||
// The worker resumed while the escalation waited for the dialog, so no report was sent.
|
||||
expect(await ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id, () => false)).toBeNull()
|
||||
asked.end('hook-gone')
|
||||
await ctx.tick(40)
|
||||
|
||||
expect(ctx.closings()).toEqual([])
|
||||
})
|
||||
|
||||
it('closes a prompt left open by an earlier run, once, when the database opens', async () => {
|
||||
const ctx = setup()
|
||||
ctx.holds.admit(hook('tool-1').request)
|
||||
const approval = ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id)!
|
||||
const approval = (await ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id))!
|
||||
const escalate = (id: string | undefined, carried: typeof approval) =>
|
||||
ctx.db.insertMessage({
|
||||
...(id ? { id } : {}),
|
||||
|
||||
+52
-36
@@ -13,8 +13,11 @@ import {
|
||||
claudeDialogWarning,
|
||||
showsClaudeDialog
|
||||
} from '../../../terminal/wait/claude-open-dialog-hold'
|
||||
import { claudeToolClose } from './claude-tool-result-close'
|
||||
import type { ClaudeToolClose, ClaudeToolResult } from './claude-tool-result-close'
|
||||
import {
|
||||
claudeTookHookAnswer,
|
||||
claudeToolCloseHow,
|
||||
type ClaudeToolRecord
|
||||
} from './claude-tool-result-close'
|
||||
import { firstWithin } from './first-within'
|
||||
import type {
|
||||
TerminalWorkerApprovalAnswer,
|
||||
@@ -23,29 +26,23 @@ import type {
|
||||
TerminalWorkerApprovalHoldsDeps
|
||||
} from './terminal-worker-approval-hold'
|
||||
import { reportWorkerApprovalClosed } from '../turn-stops/worker-turn-stop-report'
|
||||
import { closedApproval } from './worker-approval'
|
||||
import type {
|
||||
WorkerApprovalDecision,
|
||||
WorkerApprovalOutcome,
|
||||
WorkerApprovalPayload
|
||||
import {
|
||||
closedApproval,
|
||||
type WorkerApprovalDecision,
|
||||
type WorkerApprovalOutcome,
|
||||
type WorkerApprovalPayload
|
||||
} from '../../../../../shared/orchestration/approvals/worker-approval-payload'
|
||||
import { TERMINAL_APPROVAL_ID_PREFIX } from './worker-approval-report'
|
||||
|
||||
// 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
|
||||
|
||||
type Hold = TerminalWorkerApprovalHold
|
||||
type CloseHow = TerminalWorkerApprovalCloseHow
|
||||
// Its tool ran, failed or not: it was allowed in the terminal.
|
||||
const RAN: CloseHow = { by: 'worker-terminal', decision: 'allow' }
|
||||
|
||||
export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
private readonly byApprovalId = new Map<string, Hold>()
|
||||
@@ -107,7 +104,10 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
|
||||
/** Every accepted Claude event: a tool's result says how a dialog closed. */
|
||||
observe(event: AgentHookEventPayload): void {
|
||||
if (event.hookEventName === 'PostToolUse' && event.toolUseId) {
|
||||
// A failed command ran too: it was allowed.
|
||||
const ran =
|
||||
event.hookEventName === 'PostToolUse' || event.hookEventName === 'PostToolUseFailure'
|
||||
if (ran && event.toolUseId) {
|
||||
const open = this.openByPane.get(event.paneKey)
|
||||
const hold =
|
||||
open?.toolUseId === event.toolUseId ? open : this.closingByToolUseId.get(event.toolUseId)
|
||||
@@ -116,7 +116,7 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
}
|
||||
hold.ranSeen = true
|
||||
if (hold.state !== 'answering') {
|
||||
this.close(hold, { by: 'worker-terminal', decision: 'allow' })
|
||||
this.close(hold, RAN)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -129,8 +129,8 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
if (hold.paneKey === event.paneKey) {
|
||||
// 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)]))
|
||||
.readToolRecord(hold)
|
||||
.then((record) => this.close(hold, claudeToolCloseHow(record?.result ?? null)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,14 +142,27 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
return this.byApprovalId.has(approvalId)
|
||||
}
|
||||
|
||||
takeOpenApproval(paneKey: string, dispatchId: string): WorkerApprovalPayload | null {
|
||||
/** `reporting`: whether the caller still sends its report, read last, so a close owes a closing
|
||||
* line only to an approval whose escalation went out. */
|
||||
async takeOpenApproval(
|
||||
paneKey: string,
|
||||
dispatchId: string,
|
||||
reporting: () => boolean = () => true
|
||||
): Promise<WorkerApprovalPayload | null> {
|
||||
const hold = this.openByPane.get(paneKey)
|
||||
if (hold?.state !== 'open' || hold.dispatch.id !== dispatchId) {
|
||||
return null
|
||||
}
|
||||
// The escalation can go out before the dialog paints: wait for it, for its countdown and reason.
|
||||
const lines = await firstWithin(this.deps.setTimer, () => {
|
||||
const screen = this.deps.readScreen(paneKey)
|
||||
return screen && showsClaudeDialog(screen) ? screen : null
|
||||
})
|
||||
if (hold.state !== 'open' || this.openByPane.get(paneKey) !== hold || !reporting()) {
|
||||
return null
|
||||
}
|
||||
hold.reported = true
|
||||
// The escalation usually goes out before the first poll, so read the dialog here too.
|
||||
this.readDialog(hold, this.deps.readScreen(paneKey))
|
||||
this.readDialog(hold, lines)
|
||||
return this.payload(hold)
|
||||
}
|
||||
|
||||
@@ -182,13 +195,13 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
? { behavior: 'allow' }
|
||||
: { behavior: 'deny', message: input.message }
|
||||
)
|
||||
const result = written ? await this.toolResult(hold) : null
|
||||
const ours = input.decision === 'deny' ? 'hook-denied' : 'ran'
|
||||
if (!result || claudeToolClose(result, input.message) !== ours || hold.state !== 'answering') {
|
||||
const record = written ? await this.toolRecord(hold) : null
|
||||
const taken = record ? claudeTookHookAnswer(record, input.decision, input.message) : false
|
||||
if (!taken || hold.state !== 'answering') {
|
||||
// A quit or budget end that closed it meanwhile stays closed: the state only moves forward.
|
||||
if (hold.state === 'answering') {
|
||||
hold.state = 'open'
|
||||
await this.settle(hold, result)
|
||||
await this.settle(hold, record)
|
||||
}
|
||||
return notOpen
|
||||
}
|
||||
@@ -205,7 +218,7 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
const lines = this.deps.readScreen(hold.paneKey)
|
||||
const shown = lines ? showsClaudeDialog(lines) : null
|
||||
if (shown === false && hold.dialogSeen) {
|
||||
void this.toolResult(hold).then((result) => this.settle(hold, result))
|
||||
void this.toolRecord(hold).then((record) => this.settle(hold, record))
|
||||
return
|
||||
}
|
||||
hold.dialogSeen ||= shown === true
|
||||
@@ -220,24 +233,27 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
this.close(hold, null)
|
||||
return
|
||||
}
|
||||
await this.settle(hold, await this.toolResult(hold))
|
||||
await this.settle(hold, await this.toolRecord(hold))
|
||||
}
|
||||
|
||||
/** Names a close from this call's tool_result; with none yet, from whether the dialog is still up. */
|
||||
private async settle(hold: Hold, result: ClaudeToolResult | null): Promise<void> {
|
||||
private async settle(hold: Hold, record: ClaudeToolRecord | null): Promise<void> {
|
||||
if (hold.state !== 'open') {
|
||||
return
|
||||
}
|
||||
const close = hold.ranSeen ? 'ran' : result && claudeToolClose(result, null)
|
||||
if (close) {
|
||||
this.close(hold, CLOSE_OF[close])
|
||||
const how = hold.ranSeen ? RAN : claudeToolCloseHow(record?.result ?? null)
|
||||
if (how) {
|
||||
this.close(hold, how)
|
||||
return
|
||||
}
|
||||
const lines = await firstWithin(this.deps.setTimer, () => this.deps.readScreen(hold.paneKey))
|
||||
if (hold.state !== 'open') {
|
||||
return
|
||||
}
|
||||
if (!lines || showsClaudeDialog(lines)) {
|
||||
if (!this.stillBound(hold)) {
|
||||
// Stopped, exited or handed on: no terminal is left to answer it in.
|
||||
this.close(hold, { by: 'worker-ended', decision: null })
|
||||
} else 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 {
|
||||
@@ -287,7 +303,7 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
by: how?.by ?? 'unknown',
|
||||
decision: how?.decision ?? null,
|
||||
reason: null,
|
||||
reasonDelivered: true
|
||||
reasonDelivered: false
|
||||
})
|
||||
},
|
||||
this.deps,
|
||||
@@ -314,8 +330,8 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds {
|
||||
)
|
||||
}
|
||||
|
||||
private toolResult(hold: Hold): Promise<ClaudeToolResult | null> {
|
||||
return firstWithin(this.deps.setTimer, () => this.deps.readToolResult(hold))
|
||||
private toolRecord(hold: Hold): Promise<ClaudeToolRecord | null> {
|
||||
return firstWithin(this.deps.setTimer, () => this.deps.readToolRecord(hold))
|
||||
}
|
||||
|
||||
private payload(hold: Hold, outcome?: WorkerApprovalOutcome): WorkerApprovalPayload {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
WorkerApprovalPayloadSchema,
|
||||
closedApproval,
|
||||
type WorkerApprovalOutcome,
|
||||
type WorkerApprovalPayload
|
||||
} from '../../../../../shared/orchestration/approvals/worker-approval-payload'
|
||||
@@ -13,7 +14,6 @@ import {
|
||||
stopReportId,
|
||||
type WorkerTurnStopReportDeps
|
||||
} from '../turn-stops/worker-turn-stop-report'
|
||||
import { closedApproval } from './worker-approval'
|
||||
|
||||
/** A Claude terminal worker's approval id; a chat worker's is its journal item id. */
|
||||
export const TERMINAL_APPROVAL_ID_PREFIX = 'apr_'
|
||||
|
||||
@@ -5,11 +5,12 @@ import type {
|
||||
AgentJournalPromptOption
|
||||
} from '../../../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
|
||||
import type {
|
||||
WorkerApprovalAnswerer,
|
||||
WorkerApprovalDecision,
|
||||
WorkerApprovalOutcome,
|
||||
WorkerApprovalPayload
|
||||
import {
|
||||
closedApproval,
|
||||
type WorkerApprovalAnswerer,
|
||||
type WorkerApprovalDecision,
|
||||
type WorkerApprovalOutcome,
|
||||
type WorkerApprovalPayload
|
||||
} from '../../../../../shared/orchestration/approvals/worker-approval-payload'
|
||||
|
||||
/** The outcome of a chat prompt Orca answered: its reason is told only when it went to the worker as mail. */
|
||||
@@ -90,19 +91,3 @@ export function workerApprovalPayload(input: {
|
||||
}
|
||||
return outcome ? closedApproval(open, outcome) : open
|
||||
}
|
||||
|
||||
/** The same approval once closed: nothing left to answer, and how it closed. */
|
||||
export function closedApproval(
|
||||
open: WorkerApprovalPayload,
|
||||
outcome: WorkerApprovalOutcome
|
||||
): WorkerApprovalPayload {
|
||||
const closed: WorkerApprovalPayload = {
|
||||
...open,
|
||||
state: outcome.decision === null ? 'expired' : 'answered',
|
||||
allowedActions: [],
|
||||
outcome
|
||||
}
|
||||
// A countdown means nothing once the prompt is closed.
|
||||
delete closed.expiresAt
|
||||
return closed
|
||||
}
|
||||
|
||||
@@ -25,7 +25,12 @@ export type TerminalWorkerTurnStopsDeps = WorkerTurnStopReportDeps & {
|
||||
getProcessIncarnation: (handle: string) => string | null
|
||||
readScreen: (handle: string) => Promise<RuntimeTerminalRead>
|
||||
/** The pane's open approval Orca can answer; taking it marks it reported. */
|
||||
takeOpenApproval: (paneKey: string, dispatchId: string) => WorkerApprovalPayload | null
|
||||
/** `reporting` is read after the wait; the approval is marked reported only when it holds. */
|
||||
takeOpenApproval: (
|
||||
paneKey: string,
|
||||
dispatchId: string,
|
||||
reporting: () => boolean
|
||||
) => Promise<WorkerApprovalPayload | null>
|
||||
}
|
||||
|
||||
/** Report a terminal worker whose turn ended (or stopped at a prompt) while its Dispatch is open. */
|
||||
@@ -71,16 +76,22 @@ export class TerminalWorkerTurnStops {
|
||||
.readScreen(stopped.handle)
|
||||
.then((view) => redactWorkerTerminalView(view).tail.join('\n'))
|
||||
.catch(() => undefined))
|
||||
// The read awaited: the worker may have resumed, reported, or been handed a new Dispatch since.
|
||||
const before = this.stillStopped(stop)
|
||||
// One report per approval; the screen shows Claude's own reason for asking.
|
||||
const approval =
|
||||
reason === 'needs-input' && before?.target.kind === 'local'
|
||||
? await this.deps.takeOpenApproval(
|
||||
stop.paneKey,
|
||||
before.target.dispatch.id,
|
||||
// Read at the end of the dialog wait; a resume after it is caught by the re-read below.
|
||||
() => this.stillStopped(stop) !== null
|
||||
)
|
||||
: null
|
||||
// Both reads awaited: the worker may have resumed, reported, or been handed a new Dispatch since.
|
||||
const resolved = this.stillStopped(stop)
|
||||
if (!resolved) {
|
||||
return
|
||||
}
|
||||
// One report per approval; the screen shows Claude's own reason for asking.
|
||||
const approval =
|
||||
reason === 'needs-input' && resolved.target.kind === 'local'
|
||||
? this.deps.takeOpenApproval(stop.paneKey, resolved.target.dispatch.id)
|
||||
: null
|
||||
reportWorkerTurnStop(
|
||||
resolved.db,
|
||||
resolved.target,
|
||||
|
||||
@@ -282,6 +282,7 @@ const CLOSED_BY: Record<NonNullable<WorkerApprovalPayload['outcome']>['by'], str
|
||||
'worker-terminal': "in the worker's terminal",
|
||||
auto: "by the worker's agent on its own (its 2:00 timeout)",
|
||||
'terminal-only': "for Orca; a person must answer it in the worker's terminal",
|
||||
'worker-ended': 'because its worker ended',
|
||||
unknown: 'without an answer Orca can name'
|
||||
}
|
||||
|
||||
@@ -317,6 +318,12 @@ export function reportWorkerApprovalClosed(
|
||||
refines = false
|
||||
): void {
|
||||
const { approval } = closed
|
||||
const status = db.getDispatchContextById(dispatch.id)?.status
|
||||
// Unanswered, and its worker already ended: the card reads that on its own, and the coordinator
|
||||
// was told the worker ended; a second notice adds nothing.
|
||||
if (!approval.outcome?.decision && status !== 'pending' && status !== 'dispatched') {
|
||||
return
|
||||
}
|
||||
escalateWorkerFailure(
|
||||
db,
|
||||
dispatch,
|
||||
@@ -331,12 +338,7 @@ export function reportWorkerApprovalClosed(
|
||||
subject: approval.outcome?.decision ? 'Worker approval answered' : 'Worker approval closed',
|
||||
body: describeApprovalClosed(approval)
|
||||
}),
|
||||
payload: {
|
||||
taskId: dispatch.task_id,
|
||||
dispatchId: dispatch.id,
|
||||
handle: closed.from,
|
||||
approval
|
||||
},
|
||||
payload: { taskId: dispatch.task_id, dispatchId: dispatch.id, handle: closed.from, approval },
|
||||
// Only a person at the worker's terminal can answer it now: that needs the coordinator to act.
|
||||
...(approval.outcome?.by === 'terminal-only' ? {} : { notice: true as const })
|
||||
},
|
||||
|
||||
@@ -76,7 +76,7 @@ function terminal(ctx: ReturnType<typeof setup>, current: { row: AgentStatusIpcP
|
||||
},
|
||||
getHandle: () => HANDLE,
|
||||
getProcessIncarnation: () => null,
|
||||
takeOpenApproval: () => null,
|
||||
takeOpenApproval: async () => null,
|
||||
readScreen: async () => ({
|
||||
handle: HANDLE,
|
||||
status: 'running',
|
||||
|
||||
@@ -1,45 +1,77 @@
|
||||
import { CrewSubscribeParams } from '../../../../../shared/orchestration/orchestration-crew'
|
||||
import {
|
||||
CrewSubscribeParams,
|
||||
WorkerApprovalsSubscribeParams
|
||||
} from '../../../../../shared/orchestration/orchestration-crew'
|
||||
import { subscribeCrew } from '../../../orchestration/crew/crew-stream'
|
||||
import type { RpcContext } from '../../core'
|
||||
import { defineOrchestrationStreamingMethod } from './access/orchestration-method-access'
|
||||
|
||||
let sequence = 0
|
||||
/** Run a stream until its client leaves; `start` returns the stream's stop. */
|
||||
async function streamUntilClosed(
|
||||
kind: string,
|
||||
{ runtime, signal, connectionId }: RpcContext,
|
||||
emitEnd: () => void,
|
||||
start: () => () => void
|
||||
): Promise<void> {
|
||||
if (signal?.aborted) {
|
||||
return
|
||||
}
|
||||
await runtime.openAgentSessionRecordStore()
|
||||
if (signal?.aborted) {
|
||||
return
|
||||
}
|
||||
await new Promise<void>((resolve) => {
|
||||
const key = `${kind}:${connectionId ?? 'local'}:${++sequence}`
|
||||
const release = () => runtime.cleanupSubscription(key)
|
||||
const stop = start()
|
||||
runtime.registerSubscriptionCleanup(
|
||||
key,
|
||||
() => {
|
||||
stop()
|
||||
signal?.removeEventListener('abort', release)
|
||||
emitEnd()
|
||||
resolve()
|
||||
},
|
||||
connectionId
|
||||
)
|
||||
signal?.addEventListener('abort', release, { once: true })
|
||||
if (signal?.aborted) {
|
||||
release()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const ORCHESTRATION_CREW_METHODS = [
|
||||
defineOrchestrationStreamingMethod({
|
||||
name: 'orchestration.crewSubscribe',
|
||||
access: { kind: 'localOnly', targets: { party: 'party' } },
|
||||
permission: 'workspace',
|
||||
params: CrewSubscribeParams,
|
||||
handler: async ({ party }, { runtime, signal, connectionId }, emit) => {
|
||||
if (signal?.aborted) {
|
||||
return
|
||||
}
|
||||
await runtime.openAgentSessionRecordStore()
|
||||
if (signal?.aborted) {
|
||||
return
|
||||
}
|
||||
await new Promise<void>((resolve) => {
|
||||
const key = `crew:${connectionId ?? 'local'}:${++sequence}`
|
||||
const release = () => runtime.cleanupSubscription(key)
|
||||
const stop = subscribeCrew(
|
||||
() => runtime.getOrchestrationCrewSnapshot(party),
|
||||
runtime.watchOrchestrationCrew,
|
||||
emit
|
||||
)
|
||||
runtime.registerSubscriptionCleanup(
|
||||
key,
|
||||
() => {
|
||||
stop()
|
||||
signal?.removeEventListener('abort', release)
|
||||
emit({ type: 'end' })
|
||||
resolve()
|
||||
},
|
||||
connectionId
|
||||
)
|
||||
signal?.addEventListener('abort', release, { once: true })
|
||||
if (signal?.aborted) {
|
||||
release()
|
||||
}
|
||||
})
|
||||
}
|
||||
handler: ({ party }, context, emit) =>
|
||||
streamUntilClosed(
|
||||
'crew',
|
||||
context,
|
||||
() => emit({ type: 'end' }),
|
||||
() =>
|
||||
subscribeCrew(
|
||||
() => context.runtime.getOrchestrationCrewSnapshot(party),
|
||||
context.runtime.watchOrchestrationCrew,
|
||||
emit
|
||||
)
|
||||
)
|
||||
}),
|
||||
defineOrchestrationStreamingMethod({
|
||||
name: 'orchestration.workerApprovalsSubscribe',
|
||||
access: { kind: 'localOnly', targets: { party: 'party' } },
|
||||
permission: 'workspace',
|
||||
params: WorkerApprovalsSubscribeParams,
|
||||
handler: ({ party }, context, emit) =>
|
||||
streamUntilClosed(
|
||||
'worker-approvals',
|
||||
context,
|
||||
() => emit({ type: 'end' }),
|
||||
() => context.runtime.subscribeOrchestrationWorkerApprovals(party, emit)
|
||||
)
|
||||
})
|
||||
]
|
||||
|
||||
@@ -9,9 +9,9 @@ import {
|
||||
} from '../../../../orchestration/workers/approvals/chat-worker-approval-prompt'
|
||||
import {
|
||||
chatAnswerOutcome,
|
||||
closedApproval,
|
||||
workerApprovalPayload
|
||||
} from '../../../../orchestration/workers/approvals/worker-approval'
|
||||
import { closedApproval } from '../../../../../../shared/orchestration/approvals/worker-approval-payload'
|
||||
import { closeReportedApproval } from '../../../../orchestration/workers/approvals/worker-approval-report'
|
||||
import {
|
||||
reportWorkerApprovalClosed,
|
||||
|
||||
@@ -74,8 +74,9 @@ export function claudeDialogWarning(lines: readonly string[] | null): string | n
|
||||
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) {
|
||||
// A warning follows the rule that closes the command's box: the last one. A long command
|
||||
// scrolls the rule that opens the box off the screen, so only the closing one may show.
|
||||
if (proceed === -1 || rules.length === 0) {
|
||||
return null
|
||||
}
|
||||
const warning = region
|
||||
|
||||
@@ -7,16 +7,31 @@ import { CrewReadModel } from '../../orchestration/crew/crew-read-model'
|
||||
import { getPublishedHostDescriptor } from '../../hosts/platform-probe/host-descriptor'
|
||||
import { existsSync } from 'node:fs'
|
||||
import type { OrchestrationDb } from '../../orchestration/db/orchestration-db'
|
||||
import { CrewChanges } from '../../orchestration/crew/crew-changes'
|
||||
import { OrcaRuntimeWithOrchestrationDatabaseBinding } from './orchestration-database-binding'
|
||||
import { subscribeWorkerApprovals } from '../../orchestration/crew/worker-approval-stream'
|
||||
import { readCrewApprovals } from '../../orchestration/crew/crew-query'
|
||||
import { parseOrcaSessionAddress } from '../../../../shared/orca-session-address'
|
||||
import type { OrchestrationWorkerApprovalsFrame } from '../../../../shared/orchestration/orchestration-crew'
|
||||
|
||||
export abstract class OrcaRuntimeWithCrewOperations extends OrcaRuntimeWithOrchestrationDatabaseBinding {
|
||||
abstract readonly agentTransitions: Pick<AgentTransitionDetector, 'subscribe'>
|
||||
|
||||
private unwatchCrewDb: (() => void) | undefined
|
||||
// Not a field initializer: a base constructor can bind the database before this class's fields run.
|
||||
declare private orchestrationDbChangesSlot: CrewChanges | undefined
|
||||
/** The orchestration database's own changes (Runs, Dispatches, mail), without terminal identity's. */
|
||||
private get orchestrationDbChanges(): CrewChanges {
|
||||
return (this.orchestrationDbChangesSlot ??= new CrewChanges())
|
||||
}
|
||||
|
||||
protected bindCrewChanges(db: OrchestrationDb): void {
|
||||
this.unwatchCrewDb?.()
|
||||
this.unwatchCrewDb = db.crewChanges.subscribe(this.crewChanges.notify)
|
||||
this.unwatchCrewDb = db.crewChanges.subscribe((facets) => {
|
||||
this.orchestrationDbChanges.notify(facets)
|
||||
this.crewChanges.notify(facets)
|
||||
})
|
||||
this.orchestrationDbChanges.notify()
|
||||
this.crewChanges.notify()
|
||||
}
|
||||
|
||||
@@ -46,4 +61,35 @@ export abstract class OrcaRuntimeWithCrewOperations extends OrcaRuntimeWithOrche
|
||||
}
|
||||
|
||||
watchOrchestrationCrew = (wake: () => void) => this.crewReadModel.subscribe(wake)
|
||||
|
||||
/** A chat coordinator's worker approvals: its own mailbox and its Runs', read only on their changes. */
|
||||
subscribeOrchestrationWorkerApprovals(
|
||||
party: string,
|
||||
emit: (frame: OrchestrationWorkerApprovalsFrame) => void
|
||||
): () => void {
|
||||
const orcaSessionId = parseOrcaSessionAddress(party)
|
||||
return subscribeWorkerApprovals(
|
||||
{
|
||||
mailboxes: () => {
|
||||
const db = this._orchestrationDb
|
||||
return db && orcaSessionId
|
||||
? [
|
||||
party,
|
||||
...db
|
||||
.runsBoundToCoordinator({ orcaSessionId, paneKey: null, terminalHandle: null })
|
||||
.map((run) => `run:${run.id}`)
|
||||
]
|
||||
: []
|
||||
},
|
||||
approvals: (mailboxes) => {
|
||||
const db = this._orchestrationDb
|
||||
return db ? readCrewApprovals(db, mailboxes) : []
|
||||
},
|
||||
workers: () => this.crewReadModel.read(party).sections.managing,
|
||||
// Terminal identity notices (every agent status or title change) say nothing about approvals.
|
||||
watch: this.orchestrationDbChanges.subscribe
|
||||
},
|
||||
emit
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db/orchestration-db'
|
||||
import { isOrcaSessionId } from '../../../../shared/orca-session-address'
|
||||
|
||||
const CHAT = 'claude_11111111_1111_4111_8111_111111111111'
|
||||
|
||||
it("reads a chat's approvals on its own Run's changes, never on terminal identity notices", async () => {
|
||||
if (!isOrcaSessionId(CHAT)) {
|
||||
throw new Error('fixture id')
|
||||
}
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const db = new OrchestrationDb(':memory:')
|
||||
runtime.setOrchestrationDb(db)
|
||||
const runs = vi.spyOn(db, 'runsBoundToCoordinator')
|
||||
const stop = runtime.subscribeOrchestrationWorkerApprovals(`orca_session_id:${CHAT}`, () => {})
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve))
|
||||
const reads = runs.mock.calls.length
|
||||
|
||||
// What every agent status or tab title change sends: terminal identity's default topology notice.
|
||||
for (let i = 0; i < 50; i++) {
|
||||
runtime.crewChanges.notify()
|
||||
await settle()
|
||||
}
|
||||
expect(runs.mock.calls.length - reads).toBe(0)
|
||||
|
||||
db.createRun({
|
||||
objective: 'Coordinate',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: CHAT
|
||||
})
|
||||
await settle()
|
||||
expect(runs.mock.calls.length - reads).toBe(1)
|
||||
stop()
|
||||
})
|
||||
@@ -38,6 +38,7 @@ import type { StructuredAgentSessionHostWork } from './session/structured/use-st
|
||||
import type { NativeChatDeliveryNotice } from './messages/rows/NativeChatMessageRow'
|
||||
import { splitNativeChatSlotsWaitingBehindLiveTurn } from './conversation/slots/native-chat-transcript-slot-selection'
|
||||
import { useNativeChatTranscriptSlots } from './conversation/slots/use-native-chat-transcript-slots'
|
||||
import type { NativeChatTimedRow } from './conversation/slots/native-chat-timed-rows'
|
||||
import { useNativeChatTranscriptWindow } from './viewport/virtualization/use-native-chat-transcript-window'
|
||||
import { useNativeChatHistoryRetention } from './viewport/history/use-native-chat-history-retention'
|
||||
import { useNativeChatSubagentSections } from './subagents/use-native-chat-subagent-sections'
|
||||
@@ -89,7 +90,7 @@ export function NativeChatMessageList({
|
||||
workingStartedAt,
|
||||
settledTurns,
|
||||
deliveryNotices,
|
||||
trailing,
|
||||
timedRows,
|
||||
awaitingInput = null,
|
||||
turnActivity,
|
||||
stopping = false,
|
||||
@@ -118,8 +119,8 @@ export function NativeChatMessageList({
|
||||
/** Host durations by prompt id; otherwise fall back to a duration observed locally. */
|
||||
settledTurns?: NativeChatSettledTurns
|
||||
deliveryNotices?: ReadonlyMap<string, NativeChatDeliveryNotice>
|
||||
/** Rows after the conversation that are not part of it, such as workers' open approvals. */
|
||||
trailing?: React.ReactNode
|
||||
/** Rows that are not part of the conversation but happened during it, such as workers' approvals. */
|
||||
timedRows?: readonly NativeChatTimedRow[]
|
||||
/** Set while the turn waits on the reader; the live activity line yields to it. */
|
||||
awaitingInput?: NativeChatAwaitingInput | null
|
||||
turnActivity?: NativeChatTurnActivity | null
|
||||
@@ -390,6 +391,7 @@ export function NativeChatMessageList({
|
||||
>
|
||||
<NativeChatTranscriptItems
|
||||
slots={slots}
|
||||
timedRows={timedRows}
|
||||
loadedMessageIds={loadedMessageIds}
|
||||
context={rowContext}
|
||||
window={transcriptWindow}
|
||||
@@ -402,7 +404,6 @@ export function NativeChatMessageList({
|
||||
<NativeChatAwaitingInputRow subject={null} pending />
|
||||
) : null}
|
||||
<NativeChatWaitingTranscriptItems slots={waitingSlots} context={rowContext} />
|
||||
{trailing}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -75,7 +75,11 @@ import { useNativeChatHostSendGate } from '@/components/native-chat/host-access/
|
||||
import { useStructuredAgentSessionStartFailureFacts } from '@/components/native-chat/messages/notices/use-structured-agent-session-start-failure-facts'
|
||||
import { pendingPromptsAllUnanswerableHere } from '../../../../shared/agent-session/agent-session-approval-subject'
|
||||
import { NativeChatHostSetupContext } from '@/components/native-chat/host-access/native-chat-host-setup'
|
||||
import { useNativeChatWorkerApprovalSlots } from '@/components/native-chat/worker-approvals/NativeChatWorkerApprovals'
|
||||
import {
|
||||
NativeChatPartyWorkerApprovalStack,
|
||||
NativeChatWorkerApprovalTimeline,
|
||||
nativeChatWorkerApprovalParty
|
||||
} from '@/components/native-chat/worker-approvals/NativeChatWorkerApprovals'
|
||||
|
||||
export function NativeChatStructuredSession(props: Omit<NativeChatStructuredViewProps, 'mode'>) {
|
||||
const ownerWorktreeId = useNativeChatTabOwnerWorktreeId(props.tabId)
|
||||
@@ -112,7 +116,6 @@ export function NativeChatStructuredSession(props: Omit<NativeChatStructuredView
|
||||
const [optionPickerRequest, setOptionPickerRequest] =
|
||||
useState<NativeChatOptionPickerRequest | null>(null)
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const workerApprovals = useNativeChatWorkerApprovalSlots(props, rootRef)
|
||||
const historyPhase = structuredChatHistoryPhase(provisionalLaunch, controller.status)
|
||||
const hostOutage = useNativeChatHostOutage(props.target)
|
||||
const hostNotice = useNativeChatHostOutageNotice(hostOutage)
|
||||
@@ -127,6 +130,7 @@ export function NativeChatStructuredSession(props: Omit<NativeChatStructuredView
|
||||
const hostSendGate = useNativeChatHostSendGate(props.target, props.agent, hostOutage)
|
||||
const hostHeld = hostSendGate.sendBlockedReason !== null
|
||||
const submits = useStructuredNativeChatSubmitReveal(controller, provisionalLaunch.retry, hostHeld)
|
||||
const workerApprovalParty = nativeChatWorkerApprovalParty(props)
|
||||
const promptResponse = useStructuredPromptResponseHold(submits.respond)
|
||||
const needsFailureFacts =
|
||||
submits.queuedMessages.cards.some((card) => card.state === 'returned') ||
|
||||
@@ -297,30 +301,34 @@ export function NativeChatStructuredSession(props: Omit<NativeChatStructuredView
|
||||
view={continuation.view}
|
||||
>
|
||||
<NativeChatHostSetupContext.Provider value={setup}>
|
||||
<NativeChatMessageList
|
||||
// A rewind or a /clear replaces the conversation; nothing the old one held carries over.
|
||||
key={`${controller.epoch}:${controller.contextClear.clears}`}
|
||||
ref={submits.messageListRef}
|
||||
session={session}
|
||||
journalItems={controller.journalItems}
|
||||
journalSubmissions={controller.submissions}
|
||||
journalLatestTurn={controller.latestTurn}
|
||||
journalHostWork={controller.hostWork}
|
||||
subagentRoster={controller.subagentRoster}
|
||||
railOutline={controller.railOutline}
|
||||
isVisible={props.isVisible}
|
||||
isWorking={controller.isWorking}
|
||||
expandSignal={false}
|
||||
workingStartedAt={controller.workingStartedAt}
|
||||
settledTurns={controller.settledTurns}
|
||||
awaitingInput={prompt === null ? null : 'shown'}
|
||||
turnActivity={controller.turnActivity}
|
||||
stopping={stopControls.stopping}
|
||||
structuredAttachments
|
||||
runtimeContext={imageRuntimeContext}
|
||||
deliveryNotices={deliveryNotices}
|
||||
trailing={workerApprovals.rows}
|
||||
/>
|
||||
<NativeChatWorkerApprovalTimeline party={workerApprovalParty}>
|
||||
{(timedRows) => (
|
||||
<NativeChatMessageList
|
||||
// A rewind or a /clear replaces the conversation; nothing the old one held carries over.
|
||||
key={`${controller.epoch}:${controller.contextClear.clears}`}
|
||||
ref={submits.messageListRef}
|
||||
session={session}
|
||||
journalItems={controller.journalItems}
|
||||
journalSubmissions={controller.submissions}
|
||||
journalLatestTurn={controller.latestTurn}
|
||||
journalHostWork={controller.hostWork}
|
||||
subagentRoster={controller.subagentRoster}
|
||||
railOutline={controller.railOutline}
|
||||
isVisible={props.isVisible}
|
||||
isWorking={controller.isWorking}
|
||||
expandSignal={false}
|
||||
workingStartedAt={controller.workingStartedAt}
|
||||
settledTurns={controller.settledTurns}
|
||||
awaitingInput={prompt === null ? null : 'shown'}
|
||||
turnActivity={controller.turnActivity}
|
||||
stopping={stopControls.stopping}
|
||||
structuredAttachments
|
||||
runtimeContext={imageRuntimeContext}
|
||||
deliveryNotices={deliveryNotices}
|
||||
timedRows={timedRows}
|
||||
/>
|
||||
)}
|
||||
</NativeChatWorkerApprovalTimeline>
|
||||
</NativeChatHostSetupContext.Provider>
|
||||
</NativeChatUsageLimitActionsProvider>
|
||||
</NativeChatRowActionsProvider>
|
||||
@@ -346,8 +354,12 @@ export function NativeChatStructuredSession(props: Omit<NativeChatStructuredView
|
||||
tasks={controller}
|
||||
messageListRef={submits.messageListRef}
|
||||
/>
|
||||
{/* Workers' approvals stay findable even while this chat has its own prompt. */}
|
||||
{workerApprovals.strip}
|
||||
{/* Workers' open prompts stay pinned here, above this chat's own prompt. */}
|
||||
<NativeChatPartyWorkerApprovalStack
|
||||
party={workerApprovalParty}
|
||||
target={props.target}
|
||||
isVisible={props.isVisible}
|
||||
/>
|
||||
{prompt ? null : (
|
||||
<NativeChatStructuredComposerTabStrips
|
||||
tabId={props.tabId}
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
|
||||
import { cleanup, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { render } from '../../messages/actions/native-chat-tooltip-test-harness'
|
||||
import { NativeChatMessageList } from '../../NativeChatMessageList'
|
||||
import {
|
||||
layout,
|
||||
marker,
|
||||
session,
|
||||
stubLayout,
|
||||
stubResizeObserver
|
||||
} from '../../viewport/virtualization/native-chat-windowing-test-harness'
|
||||
|
||||
// Pacing is not this test's subject.
|
||||
vi.mock('../../markdown/use-native-chat-paced-text', async (importOriginal) =>
|
||||
(await import('../../markdown/native-chat-unpaced-text-fixture')).unpacedTextModule(
|
||||
importOriginal
|
||||
)
|
||||
)
|
||||
|
||||
let restore: (() => void)[] = []
|
||||
beforeEach(() => {
|
||||
restore = [stubLayout({ scrollGeometry: true, offsetChain: true }), stubResizeObserver()]
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
for (const undo of restore.toReversed()) {
|
||||
undo()
|
||||
}
|
||||
layout.measuredRowHeights = []
|
||||
})
|
||||
|
||||
it('draws a worker approval at its own time, with newer replies after it', () => {
|
||||
// marker(i) is message `marker-i`, at time i + 1.
|
||||
const messages = [0, 1, 2, 3].map(marker)
|
||||
render(
|
||||
<NativeChatMessageList
|
||||
session={session(messages)}
|
||||
isWorking={false}
|
||||
expandSignal={false}
|
||||
timedRows={[
|
||||
{ key: 'open', at: 3.5, node: <p>Allow Bash? (open)</p> },
|
||||
{ key: 'receipt', at: 1.5, node: <p>Allowed by you 3:11 PM</p> }
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
const order = [
|
||||
'marker-0',
|
||||
'Allowed by you 3:11 PM',
|
||||
'marker-1',
|
||||
'marker-2',
|
||||
'Allow Bash? (open)',
|
||||
'marker-3'
|
||||
].map((text) => screen.getByText(text))
|
||||
for (const [index, element] of order.slice(1).entries()) {
|
||||
expect(order[index].compareDocumentPosition(element)).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
/** Rows that are not part of the conversation but happened during it, such as a worker's approval:
|
||||
* each draws after the newest message that came before it, so it stays at its own time. */
|
||||
import { useMemo } from 'react'
|
||||
import type { NativeChatTranscriptSlot } from './native-chat-transcript-slots'
|
||||
|
||||
export type NativeChatTimedRow = { key: string; at: number; node: React.ReactNode }
|
||||
|
||||
export type NativeChatTimedRowPlacement = {
|
||||
/** Keyed by message id: the rows drawn after that message, oldest first. */
|
||||
afterMessage: ReadonlyMap<string, readonly NativeChatTimedRow[]>
|
||||
/** Rows no loaded message precedes, drawn at the end of the conversation. */
|
||||
unplaced: readonly NativeChatTimedRow[]
|
||||
}
|
||||
|
||||
// Separators no key or message id contains.
|
||||
const FIELD = '\u0000'
|
||||
const ROW = '\u0001'
|
||||
|
||||
/** The message each row follows: the last top-level message at or before its time; null for none. */
|
||||
function anchorNativeChatTimedRows(
|
||||
slots: readonly NativeChatTranscriptSlot[],
|
||||
rows: readonly NativeChatTimedRow[]
|
||||
): [key: string, messageId: string | null][] {
|
||||
const dated = slots.flatMap((slot) =>
|
||||
slot.kind === 'message' && slot.depth === 0 && slot.message.timestamp !== null
|
||||
? [{ id: slot.message.id, at: slot.message.timestamp }]
|
||||
: []
|
||||
)
|
||||
return rows
|
||||
.toSorted((a, b) => a.at - b.at)
|
||||
.map((row) => [row.key, dated.findLast((message) => message.at <= row.at)?.id ?? null])
|
||||
}
|
||||
|
||||
/** Stable while no row changes the message it follows, so streaming text does not redraw every row. */
|
||||
export function useNativeChatTimedRows(
|
||||
slots: readonly NativeChatTranscriptSlot[],
|
||||
rows: readonly NativeChatTimedRow[] | undefined
|
||||
): NativeChatTimedRowPlacement | null {
|
||||
// A string, so the memo below sees a change only when some row's anchor does.
|
||||
const anchors = rows?.length
|
||||
? anchorNativeChatTimedRows(slots, rows)
|
||||
.map(([key, messageId]) => `${key}${FIELD}${messageId ?? ''}`)
|
||||
.join(ROW)
|
||||
: ''
|
||||
return useMemo(() => {
|
||||
if (!rows?.length) {
|
||||
return null
|
||||
}
|
||||
const byKey = new Map(rows.map((row) => [row.key, row]))
|
||||
const afterMessage = new Map<string, NativeChatTimedRow[]>()
|
||||
const unplaced: NativeChatTimedRow[] = []
|
||||
for (const [key, messageId] of anchors.split(ROW).map((entry) => entry.split(FIELD))) {
|
||||
const row = byKey.get(key)
|
||||
if (!row) {
|
||||
continue
|
||||
}
|
||||
if (messageId) {
|
||||
afterMessage.set(messageId, [...(afterMessage.get(messageId) ?? []), row])
|
||||
} else {
|
||||
unplaced.push(row)
|
||||
}
|
||||
}
|
||||
return { afterMessage, unplaced }
|
||||
}, [anchors, rows])
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@ import type { StructuredAgentSessionHostWork } from '../../session/structured/us
|
||||
|
||||
type NativeChatTranscriptRowContextInput = Omit<
|
||||
NativeChatTranscriptRowContext,
|
||||
'agentName' | 'actionablePromptIds'
|
||||
'agentName' | 'actionablePromptIds' | 'timedRows'
|
||||
> & {
|
||||
agent: NativeChatLiveSession['agent']
|
||||
hostWork: StructuredAgentSessionHostWork | undefined
|
||||
|
||||
@@ -11,6 +11,7 @@ import { NativeChatSubagentEntries } from '../../subagents/NativeChatSubagentRun
|
||||
import type { NativeChatSubagentDisclosure } from '../../subagents/native-chat-subagent-sections'
|
||||
import type { NativeChatTaskListPredecessors } from '../../../../../../shared/native-chat/input/native-chat-task-list-history'
|
||||
import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-chat-transcript-slots'
|
||||
import type { NativeChatTimedRow } from '../../conversation/slots/native-chat-timed-rows'
|
||||
import type {
|
||||
NativeChatDiffReveal,
|
||||
NativeChatDiffTarget
|
||||
@@ -36,6 +37,8 @@ export type NativeChatTranscriptRowContext = {
|
||||
latestTurnKey?: string
|
||||
/** Keyed by message id: the user messages that did not go through, each with its own words. */
|
||||
deliveryNotices?: ReadonlyMap<string, NativeChatDeliveryNotice>
|
||||
/** Keyed by message id: rows from outside the conversation that came right after that message. */
|
||||
timedRows?: ReadonlyMap<string, readonly NativeChatTimedRow[]>
|
||||
structuredAttachments?: boolean
|
||||
runtimeContext?: RuntimeFileOperationArgs | null
|
||||
onToggleExpandedTurn: (turnKey: string) => void
|
||||
@@ -175,6 +178,9 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({
|
||||
{openedPullRequests ? (
|
||||
<NativeChatOpenedPullRequestCard pullRequests={openedPullRequests} />
|
||||
) : null}
|
||||
{context.timedRows?.get(message.id)?.map(({ key, node }) => (
|
||||
<div key={key}>{node}</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { SecuritySurface } from '@/components/ui/security-surface'
|
||||
import { useRef, useState } from 'react'
|
||||
import { ChevronDown, ShieldQuestion, X } from 'lucide-react'
|
||||
import { ChevronDown, Loader2, ShieldQuestion, X } from 'lucide-react'
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
|
||||
import { approvalDetailPreview } from '../../../../../shared/agent-session/agent-session-approval-detail-preview'
|
||||
import { cn } from '@/lib/class-names'
|
||||
@@ -26,6 +26,8 @@ export type NativeChatApprovalCardProps = {
|
||||
onCollapse?: () => void
|
||||
/** A choice is being delivered: the options wait for its answer. */
|
||||
isSubmitting?: boolean
|
||||
/** The option being sent, while `isSubmitting`: its button shows that it is working. */
|
||||
submittingOption?: string
|
||||
shouldFocus?: boolean
|
||||
/** Shown when the card has no options: only the terminal can answer it. */
|
||||
onOpenTerminal?: () => void
|
||||
@@ -33,8 +35,8 @@ export type NativeChatApprovalCardProps = {
|
||||
worker?: { name: string; onOpen: () => void }
|
||||
/** Live time left before the agent decides on its own, shown only when its screen shows it. */
|
||||
countdown?: string
|
||||
/** `transcript`: a row in the message list, not the composer slot (no slot height, no focus). */
|
||||
placement?: 'composer' | 'transcript'
|
||||
/** `stacked`: one of several cards above the composer, not the chat's own slot (no slot height, no focus). */
|
||||
placement?: 'composer' | 'stacked'
|
||||
}
|
||||
|
||||
/** PTY options are literal replies; structured options are journal ids. The first option is primary unless the options are neutral. */
|
||||
@@ -44,6 +46,7 @@ export function NativeChatApprovalCard({
|
||||
onCancel,
|
||||
onCollapse,
|
||||
isSubmitting = false,
|
||||
submittingOption,
|
||||
shouldFocus = false,
|
||||
onOpenTerminal,
|
||||
worker,
|
||||
@@ -56,7 +59,7 @@ export function NativeChatApprovalCard({
|
||||
const neededPath = approvalBlockedPathToShow(approval)
|
||||
// A newer Orca's subject: its detail is shown, and only the card's cancel answers.
|
||||
const newerSubject = isNewerApprovalSubject(approval.subject)
|
||||
const inTranscript = placement === 'transcript'
|
||||
const stacked = placement === 'stacked'
|
||||
const hasContext = Boolean(
|
||||
countdown ||
|
||||
approval.description ||
|
||||
@@ -65,18 +68,16 @@ export function NativeChatApprovalCard({
|
||||
approval.subject ||
|
||||
approval.detail
|
||||
)
|
||||
useNativeChatPromptCardFocus(cardRef, shouldFocus && !inTranscript)
|
||||
useNativeChatPromptCardFocus(cardRef, shouldFocus && !stacked)
|
||||
const escape = onCancel ?? (isSubmitting ? undefined : onCollapse)
|
||||
|
||||
return (
|
||||
<SecuritySurface>
|
||||
<div
|
||||
className={inTranscript ? 'bg-chat-pane' : 'min-h-0 shrink overflow-hidden bg-chat-pane'}
|
||||
>
|
||||
<div className={stacked ? 'bg-chat-pane' : 'min-h-0 shrink overflow-hidden bg-chat-pane'}>
|
||||
<div
|
||||
className={cn(
|
||||
'mx-auto flex w-full max-w-(--chat-content-max-width) px-3 pt-2 pb-1 sm:px-4',
|
||||
!inTranscript && 'h-full min-h-0 max-h-full'
|
||||
!stacked && 'h-full min-h-0 max-h-full'
|
||||
)}
|
||||
>
|
||||
<div
|
||||
@@ -211,7 +212,14 @@ export function NativeChatApprovalCard({
|
||||
: 'border border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground'
|
||||
)}
|
||||
>
|
||||
{opt.label}
|
||||
{isSubmitting && opt.send === submittingOption ? (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<Loader2 className="size-3.5 animate-spin" aria-hidden />
|
||||
{opt.label}
|
||||
</span>
|
||||
) : (
|
||||
opt.label
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
{approval.options.length === 0 && onOpenTerminal ? (
|
||||
|
||||
+16
-1
@@ -5,6 +5,10 @@ import {
|
||||
} from '../../messages/rows/NativeChatTranscriptRow'
|
||||
import { nativeChatSlotKey } from '../../conversation/slots/native-chat-transcript-slot-selection'
|
||||
import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-chat-transcript-slots'
|
||||
import {
|
||||
useNativeChatTimedRows,
|
||||
type NativeChatTimedRow
|
||||
} from '../../conversation/slots/native-chat-timed-rows'
|
||||
import type { NativeChatTranscriptWindow } from './use-native-chat-transcript-window'
|
||||
import type { ReaderGesture } from '../scroll/native-chat-autoscroll'
|
||||
import { NativeChatForwardedGestureContext } from '../scroll/native-chat-reader-scroll-input'
|
||||
@@ -17,6 +21,7 @@ import {
|
||||
/** Mounted rows own their height; only unloaded gaps use cached measurements. */
|
||||
export function NativeChatTranscriptItems({
|
||||
slots,
|
||||
timedRows,
|
||||
loadedMessageIds,
|
||||
context,
|
||||
window,
|
||||
@@ -24,6 +29,8 @@ export function NativeChatTranscriptItems({
|
||||
forwardGesture
|
||||
}: {
|
||||
slots: readonly NativeChatTranscriptSlot[]
|
||||
/** Rows from outside the conversation, each drawn after the message it followed in time. */
|
||||
timedRows?: readonly NativeChatTimedRow[]
|
||||
loadedMessageIds: ReadonlySet<string>
|
||||
context: NativeChatTranscriptRowContext
|
||||
window: NativeChatTranscriptWindow
|
||||
@@ -33,6 +40,11 @@ export function NativeChatTranscriptItems({
|
||||
}): React.JSX.Element {
|
||||
const rowKeys = useMemo(() => slots.map(nativeChatSlotKey), [slots])
|
||||
const replyReveals = useNativeChatReplyReveals(rowKeys, loadedMessageIds)
|
||||
const placed = useNativeChatTimedRows(slots, timedRows)
|
||||
const rowContext = useMemo(
|
||||
() => (placed ? { ...context, timedRows: placed.afterMessage } : context),
|
||||
[context, placed]
|
||||
)
|
||||
return (
|
||||
<NativeChatReplyRevealsContext.Provider value={replyReveals}>
|
||||
<NativeChatForwardedGestureContext.Provider value={forwardGesture}>
|
||||
@@ -49,7 +61,7 @@ export function NativeChatTranscriptItems({
|
||||
<div data-index={item.index} ref={window.measureRow} className="flow-root w-full">
|
||||
<NativeChatTranscriptRow
|
||||
slot={slot}
|
||||
context={context}
|
||||
context={rowContext}
|
||||
newRowsMarker={
|
||||
rowKeys[item.index] === newRowsMarker?.key ? newRowsMarker : undefined
|
||||
}
|
||||
@@ -73,6 +85,9 @@ export function NativeChatTranscriptItems({
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{placed?.unplaced.map(({ key, node }) => (
|
||||
<div key={key}>{node}</div>
|
||||
))}
|
||||
</NativeChatForwardedGestureContext.Provider>
|
||||
</NativeChatReplyRevealsContext.Provider>
|
||||
)
|
||||
|
||||
+154
-90
@@ -1,10 +1,13 @@
|
||||
import { defineFixture } from '../../../component-fixtures/component-fixture'
|
||||
import { NativeChatMessageList } from '../NativeChatMessageList'
|
||||
import type { NativeChatLiveSession } from '../session/terminal/read/native-chat-live-session-contract'
|
||||
import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types'
|
||||
import { NativeChatApprovalCard } from '../prompts/NativeChatApprovalCard'
|
||||
import {
|
||||
NativeChatWorkerApprovalRows,
|
||||
NativeChatWorkerApprovalStrip,
|
||||
type NativeChatWorkerApproval
|
||||
NativeChatWorkerApprovalReceipt,
|
||||
NativeChatWorkerApprovalStack
|
||||
} from './NativeChatWorkerApprovals'
|
||||
import type { NativeChatWorkerApproval } from './native-chat-worker-approval-feed'
|
||||
import type { OrchestrationCrewRow } from '../../../../../shared/orchestration/orchestration-crew'
|
||||
import type {
|
||||
WorkerApprovalOutcome,
|
||||
@@ -68,7 +71,6 @@ const openDocs: NativeChatWorkerApproval = {
|
||||
worker: docs
|
||||
}
|
||||
const target = { kind: 'local' } as const
|
||||
const root = { current: null }
|
||||
|
||||
const composer = (
|
||||
<div className="px-3 pt-2 sm:px-4">
|
||||
@@ -78,47 +80,6 @@ const composer = (
|
||||
</div>
|
||||
)
|
||||
|
||||
export const open = defineFixture({
|
||||
width: 760,
|
||||
render: () => (
|
||||
<div className="native-chat-appearance bg-chat-pane py-4">
|
||||
<NativeChatWorkerApprovalRows approvals={[openBash]} target={target} />
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export const several = defineFixture({
|
||||
width: 760,
|
||||
render: () => (
|
||||
<div className="native-chat-appearance bg-chat-pane pt-4 pb-3">
|
||||
<NativeChatWorkerApprovalRows approvals={[openBash, openDocs]} target={target} />
|
||||
<NativeChatWorkerApprovalStrip approvals={[openBash, openDocs]} rootRef={root} />
|
||||
{composer}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export const coordinatorBusy = defineFixture({
|
||||
width: 760,
|
||||
render: () => (
|
||||
<div className="native-chat-appearance bg-chat-pane pt-3 pb-3">
|
||||
<NativeChatWorkerApprovalStrip approvals={[openBash, openDocs]} rootRef={root} />
|
||||
<NativeChatApprovalCard
|
||||
approval={{
|
||||
title: 'Allow Read?',
|
||||
detail: '~/orca-lanes/worker-prompt-stall/plan.html',
|
||||
options: [
|
||||
{ label: 'Allow', send: 'allow' },
|
||||
{ label: 'Deny', send: 'deny' }
|
||||
]
|
||||
}}
|
||||
onChoose={() => {}}
|
||||
onCancel={() => {}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
function closed(
|
||||
id: string,
|
||||
outcome: WorkerApprovalOutcome,
|
||||
@@ -126,7 +87,7 @@ function closed(
|
||||
): NativeChatWorkerApproval {
|
||||
return {
|
||||
approval: approval(id, bash, {
|
||||
state: outcome.decision ? 'answered' : 'expired',
|
||||
state: outcome.by === 'auto' ? 'expired' : 'answered',
|
||||
allowedActions: [],
|
||||
outcome
|
||||
}),
|
||||
@@ -139,50 +100,153 @@ export const answered = defineFixture({
|
||||
width: 760,
|
||||
render: () => (
|
||||
<div className="native-chat-appearance bg-chat-pane py-3">
|
||||
<NativeChatWorkerApprovalRows
|
||||
target={target}
|
||||
approvals={[
|
||||
closed('a', { by: 'person', decision: 'allow', reason: null, reasonDelivered: true }),
|
||||
closed('b', {
|
||||
by: 'person',
|
||||
decision: 'deny',
|
||||
reason: 'Denied by the owner.',
|
||||
reasonDelivered: true
|
||||
}),
|
||||
closed('c', {
|
||||
by: 'coordinator',
|
||||
decision: 'deny',
|
||||
reason:
|
||||
'Write the script to scripts/dialog_title.py and run it with python3 instead of a heredoc.',
|
||||
reasonDelivered: true
|
||||
}),
|
||||
closed('d', {
|
||||
by: 'worker-terminal',
|
||||
decision: 'allow',
|
||||
reason: null,
|
||||
reasonDelivered: true
|
||||
}),
|
||||
closed('e', {
|
||||
by: 'worker-terminal',
|
||||
decision: 'deny',
|
||||
reason: null,
|
||||
reasonDelivered: true
|
||||
}),
|
||||
closed(
|
||||
'f',
|
||||
{ by: 'worker-chat', decision: 'allow', reason: null, reasonDelivered: false },
|
||||
docs
|
||||
),
|
||||
closed('g', { by: 'auto', decision: 'deny', reason: null, reasonDelivered: true }),
|
||||
closed('h', {
|
||||
by: 'terminal-only',
|
||||
decision: null,
|
||||
reason: null,
|
||||
reasonDelivered: true
|
||||
}),
|
||||
closed('i', { by: 'unknown', decision: null, reason: null, reasonDelivered: false })
|
||||
]}
|
||||
/>
|
||||
{[
|
||||
closed('a', { by: 'person', decision: 'allow', reason: null, reasonDelivered: false }),
|
||||
closed('b', {
|
||||
by: 'person',
|
||||
decision: 'deny',
|
||||
reason: 'Denied by the owner.',
|
||||
reasonDelivered: true
|
||||
}),
|
||||
closed('c', {
|
||||
by: 'coordinator',
|
||||
decision: 'deny',
|
||||
reason:
|
||||
'Write the script to scripts/dialog_title.py and run it with python3 instead of a heredoc.',
|
||||
reasonDelivered: true
|
||||
}),
|
||||
closed('d', {
|
||||
by: 'worker-terminal',
|
||||
decision: 'allow',
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
}),
|
||||
closed('e', {
|
||||
by: 'worker-terminal',
|
||||
decision: 'deny',
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
}),
|
||||
closed(
|
||||
'f',
|
||||
{ by: 'worker-chat', decision: 'allow', reason: null, reasonDelivered: false },
|
||||
docs
|
||||
),
|
||||
closed('g', { by: 'auto', decision: 'deny', reason: null, reasonDelivered: false }),
|
||||
closed('h', {
|
||||
by: 'terminal-only',
|
||||
decision: null,
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
}),
|
||||
closed('i', { by: 'unknown', decision: null, reason: null, reasonDelivered: false })
|
||||
].map((entry) => (
|
||||
<NativeChatWorkerApprovalReceipt key={entry.approval.approvalId} entry={entry} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// A coordinator chat that kept replying after a worker asked twice: each card sits at its own time.
|
||||
const CHAT_START = Date.parse('2026-11-11T20:09:00.000Z')
|
||||
function reply(id: string, role: NativeChatMessage['role'], minute: number, text: string) {
|
||||
const message: NativeChatMessage = {
|
||||
id,
|
||||
role,
|
||||
source: 'transcript',
|
||||
timestamp: CHAT_START + minute * 60_000,
|
||||
blocks: [{ type: 'text', text }]
|
||||
}
|
||||
return message
|
||||
}
|
||||
const transcript: NativeChatLiveSession = {
|
||||
messages: [
|
||||
reply('ask', 'user', 0, 'Have a worker build the bot settings page.'),
|
||||
reply('started', 'assistant', 1, 'A worker is on it in dungeness.'),
|
||||
reply('status', 'user', 4, 'How is it going?'),
|
||||
reply('answer', 'assistant', 5, 'It finished the settings rows and is wiring the avatar now.'),
|
||||
reply('next', 'user', 7, 'Also check the tree spacing.'),
|
||||
reply('ack', 'assistant', 8, 'Added it to the worker task.')
|
||||
],
|
||||
agent: 'claude',
|
||||
sessionId: 'fixture',
|
||||
status: 'ready',
|
||||
readPhase: 'ready',
|
||||
hasMore: false,
|
||||
loadingEarlier: false,
|
||||
olderHistoryGeneration: 0,
|
||||
loadEarlier: async () => 'applied'
|
||||
}
|
||||
const allowedAt = new Date(CHAT_START + 2.5 * 60_000).toISOString()
|
||||
|
||||
const allowed = {
|
||||
...closed('allowed', { by: 'person', decision: 'allow', reason: null, reasonDelivered: false }),
|
||||
at: allowedAt
|
||||
}
|
||||
|
||||
/** The coordinator chat as the pane lays it out: transcript with receipts, then the pinned stack,
|
||||
* the chat's own prompt, and the composer. */
|
||||
function pane(
|
||||
stack: readonly NativeChatWorkerApproval[],
|
||||
ownPrompt = false,
|
||||
height = 'h-[760px]'
|
||||
): React.JSX.Element {
|
||||
return (
|
||||
<div className={`native-chat-appearance flex ${height} flex-col bg-chat-pane pb-3`}>
|
||||
<NativeChatMessageList
|
||||
session={transcript}
|
||||
isWorking={false}
|
||||
expandSignal={false}
|
||||
timedRows={[
|
||||
{
|
||||
key: allowed.approval.approvalId,
|
||||
at: Date.parse(allowed.at),
|
||||
node: <NativeChatWorkerApprovalReceipt entry={allowed} />
|
||||
}
|
||||
]}
|
||||
/>
|
||||
<NativeChatWorkerApprovalStack approvals={stack} target={target} />
|
||||
{ownPrompt ? (
|
||||
<NativeChatApprovalCard
|
||||
approval={{
|
||||
title: 'Allow Read?',
|
||||
detail: '~/orca-lanes/worker-prompt-stall/plan.html',
|
||||
options: [
|
||||
{ label: 'Allow', send: 'allow' },
|
||||
{ label: 'Deny', send: 'deny' }
|
||||
]
|
||||
}}
|
||||
onChoose={() => {}}
|
||||
onCancel={() => {}}
|
||||
/>
|
||||
) : null}
|
||||
{composer}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const oneOpen = defineFixture({ width: 760, render: () => pane([openBash]) })
|
||||
|
||||
export const twoOpen = defineFixture({ width: 760, render: () => pane([openBash, openDocs]) })
|
||||
|
||||
export const openWithOwnPrompt = defineFixture({
|
||||
width: 760,
|
||||
render: () => pane([openBash], true)
|
||||
})
|
||||
|
||||
// A short split pane: the stack gives way first, so the chat's own prompt keeps its buttons.
|
||||
export const twoOpenWithOwnPromptShort = defineFixture({
|
||||
width: 760,
|
||||
render: () => pane([openBash, openDocs], true, 'h-[520px]')
|
||||
})
|
||||
|
||||
// The click's outcome where the card was, for the moment before it moves into the transcript.
|
||||
export const settling = defineFixture({
|
||||
width: 760,
|
||||
render: () =>
|
||||
pane([
|
||||
closed('settled', { by: 'person', decision: 'allow', reason: null, reasonDelivered: false })
|
||||
])
|
||||
})
|
||||
|
||||
export const receiptInPlace = defineFixture({ width: 760, render: () => pane([]) })
|
||||
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import type { OrchestrationCrewRow } from '../../../../../shared/orchestration/orchestration-crew'
|
||||
|
||||
const rpc = vi.hoisted(() => ({ call: vi.fn() }))
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), info: vi.fn(), error: vi.fn() }))
|
||||
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: rpc.call }))
|
||||
vi.mock('sonner', () => ({ toast }))
|
||||
|
||||
const { RuntimeRpcCallError } = await import('@/runtime/rpc/calls/runtime-rpc-result')
|
||||
const { NativeChatWorkerApprovalStack } = await import('./NativeChatWorkerApprovals')
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const worker: OrchestrationCrewRow = {
|
||||
partyKey: 'w',
|
||||
role: 'worker',
|
||||
label: 'try-claude',
|
||||
agentKind: 'claude',
|
||||
status: 'blocked'
|
||||
}
|
||||
const entry = {
|
||||
approval: {
|
||||
v: 1 as const,
|
||||
approvalId: 'apr_1',
|
||||
state: 'open' as const,
|
||||
worker: { handle: 'term_w', dispatchId: 'ctx_1', taskId: 'task_1' },
|
||||
summary: { title: 'Allow Bash?', detail: 'rg -n x', reason: null },
|
||||
allowedActions: ['allow' as const, 'deny' as const]
|
||||
},
|
||||
at: '2026-11-11T20:11:30.000Z',
|
||||
askedAt: '2026-11-11T20:11:24.000Z',
|
||||
worker
|
||||
}
|
||||
|
||||
const reject = (code: string) =>
|
||||
rpc.call.mockRejectedValueOnce(
|
||||
new RuntimeRpcCallError({
|
||||
id: '1',
|
||||
ok: false,
|
||||
error: { code, message: code },
|
||||
_meta: { runtimeId: 'r' }
|
||||
})
|
||||
)
|
||||
|
||||
function renderStack() {
|
||||
render(<NativeChatWorkerApprovalStack approvals={[entry]} target={{ kind: 'local' }} />)
|
||||
}
|
||||
|
||||
it('waits on the host after a click: both buttons off, the clicked one working, no toast when it lands', async () => {
|
||||
renderStack()
|
||||
let land: (value: unknown) => void = () => {}
|
||||
rpc.call.mockReturnValueOnce(new Promise((resolve) => (land = resolve)))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Allow' }))
|
||||
expect(screen.getByRole('button', { name: 'Allow' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Deny' })).toBeDisabled()
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Allow' }).querySelector('.animate-spin')
|
||||
).not.toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'Deny' }).querySelector('.animate-spin')).toBeNull()
|
||||
land({})
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Allow' })).toBeEnabled())
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
expect(toast.info).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves the card to the host list when the answer was not applied', async () => {
|
||||
renderStack()
|
||||
reject('approval_not_open')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Allow' }))
|
||||
await waitFor(() => expect(toast.info).toHaveBeenCalledTimes(1))
|
||||
// Still open as far as this card knows: answerable again until the host's list says otherwise.
|
||||
expect(screen.getByRole('button', { name: 'Allow' })).toBeEnabled()
|
||||
|
||||
reject('internal_error')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Deny' }))
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1))
|
||||
expect(screen.getByRole('button', { name: 'Deny' })).toBeEnabled()
|
||||
})
|
||||
+138
-121
@@ -1,132 +1,145 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call'
|
||||
import { RuntimeRpcCallError } from '@/runtime/rpc/calls/runtime-rpc-result'
|
||||
import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval'
|
||||
import { openOrchestrationCrewAgent } from '@/lib/agent-session/open/open-agent-message-sender'
|
||||
import { useOrchestrationCrew } from '@/components/orchestration-crew/use-orchestration-crew'
|
||||
import { NativeChatApprovalCard } from '../prompts/NativeChatApprovalCard'
|
||||
import { NativeChatResolutionReceipt } from '../prompts/NativeChatResolutionReceipt'
|
||||
import { NativeChatWorkerLifetimeStrip } from '../worker-lifetime/NativeChatWorkerLifetimeStrip'
|
||||
import {
|
||||
isWorkerApprovalDecision,
|
||||
workerApprovalCard,
|
||||
workerApprovalReceiptBody,
|
||||
workerApprovalReceiptReason,
|
||||
workerApprovalReceiptText,
|
||||
workerApprovalLapsesAt,
|
||||
workerApprovalTimeLeft
|
||||
} from './worker-approval-card-model'
|
||||
import {
|
||||
useNativeChatPinnedWorkerApprovals,
|
||||
useNativeChatWorkerApprovalReceipts,
|
||||
type NativeChatWorkerApproval
|
||||
} from './native-chat-worker-approval-feed'
|
||||
import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target'
|
||||
import type { NativeChatTimedRow } from '../conversation/slots/native-chat-timed-rows'
|
||||
import {
|
||||
formatOrcaSessionAddress,
|
||||
isOrcaSessionId
|
||||
} from '../../../../../shared/orca-session-address'
|
||||
import type { OrchestrationCrewRow } from '../../../../../shared/orchestration/orchestration-crew'
|
||||
import type {
|
||||
WorkerApprovalDecision,
|
||||
WorkerApprovalPayload
|
||||
} from '../../../../../shared/orchestration/approvals/worker-approval-payload'
|
||||
|
||||
export type NativeChatWorkerApproval = {
|
||||
approval: WorkerApprovalPayload
|
||||
at: string
|
||||
worker: OrchestrationCrewRow
|
||||
}
|
||||
import type { WorkerApprovalDecision } from '../../../../../shared/orchestration/approvals/worker-approval-payload'
|
||||
|
||||
// The person's own Deny: the worker gets this, word for word where its agent takes a message.
|
||||
const OWNER_DENY_REASON = 'Denied by the owner.'
|
||||
|
||||
/** This chat's workers' approvals, from its crew's mailbox rows as soon as they are stored; local only in v1. */
|
||||
export function useNativeChatWorkerApprovals(
|
||||
target: RuntimeClientTarget | null,
|
||||
party: string | null
|
||||
): NativeChatWorkerApproval[] {
|
||||
const crew = useOrchestrationCrew(target?.kind === 'local' ? target : null, party)
|
||||
const all = useMemo(
|
||||
() =>
|
||||
crew.sections.managing
|
||||
.flatMap((worker) => (worker.approvals ?? []).map((entry) => ({ ...entry, worker })))
|
||||
.sort((a, b) => a.at.localeCompare(b.at)),
|
||||
[crew]
|
||||
)
|
||||
const [now, setNow] = useState(Date.now)
|
||||
const nextLapse = Math.min(
|
||||
...all.map(({ approval }) => workerApprovalLapsesAt(approval)).filter((at) => at > now)
|
||||
)
|
||||
useEffect(() => {
|
||||
if (!Number.isFinite(nextLapse)) {
|
||||
return
|
||||
}
|
||||
const timer = setTimeout(() => setNow(Date.now()), nextLapse - Date.now())
|
||||
return () => clearTimeout(timer)
|
||||
}, [nextLapse])
|
||||
return useMemo(
|
||||
() => all.filter(({ approval }) => workerApprovalLapsesAt(approval) > now),
|
||||
[all, now]
|
||||
/** A worker's answered or lapsed prompt, in the transcript where the worker first asked. */
|
||||
export function NativeChatWorkerApprovalReceipt({
|
||||
entry
|
||||
}: {
|
||||
entry: NativeChatWorkerApproval
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const { approval } = entry
|
||||
return (
|
||||
<div
|
||||
className="px-3 pb-2 sm:px-4"
|
||||
data-native-chat-worker-approval-receipt={approval.approvalId}
|
||||
>
|
||||
<NativeChatResolutionReceipt
|
||||
body={workerApprovalReceiptBody(approval, entry.at, t)}
|
||||
outcome={{
|
||||
worker: entry.worker.label,
|
||||
text: workerApprovalReceiptText(approval, t),
|
||||
...workerApprovalReceiptReason(approval, t)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const cardSelector = (approvalId: string) =>
|
||||
`[data-native-chat-worker-approval="${CSS.escape(approvalId)}"]`
|
||||
|
||||
/** Open cards and receipts at the end of the conversation; a card here never takes focus or cancels the chat's turn. */
|
||||
export function NativeChatWorkerApprovalRows({
|
||||
/** Workers' prompts pinned above the composer, oldest first: open ones as cards, and ones just
|
||||
* closed as their receipt. A card here never takes focus or cancels the chat's turn. */
|
||||
export function NativeChatWorkerApprovalStack({
|
||||
approvals,
|
||||
target
|
||||
target,
|
||||
isVisible = true
|
||||
}: {
|
||||
approvals: readonly NativeChatWorkerApproval[]
|
||||
target: RuntimeClientTarget
|
||||
/** A hidden pane's countdown stands still; it shows the time again once visible. */
|
||||
isVisible?: boolean
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const [submitting, setSubmitting] = useState<ReadonlySet<string>>(new Set())
|
||||
const now = useSecondClock(approvals.some(({ approval }) => approval.expiresAt))
|
||||
const answer = useCallback(
|
||||
(entry: NativeChatWorkerApproval, decision: WorkerApprovalDecision) => {
|
||||
const { approvalId, worker } = entry.approval
|
||||
setSubmitting((current) => new Set(current).add(approvalId))
|
||||
callRuntimeRpc(target, 'orchestration.approvalAnswer', {
|
||||
dispatch: worker.dispatchId,
|
||||
prompt: approvalId,
|
||||
decision,
|
||||
...(decision === 'deny' ? { reason: OWNER_DENY_REASON } : {})
|
||||
})
|
||||
.catch((error: unknown) =>
|
||||
toast.error(
|
||||
t('components.native-chat.approval.answerFailed', '{{name}}: {{detail}}', {
|
||||
name: entry.worker.label,
|
||||
detail: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
const open = approvals.filter(({ approval }) => approval.state === 'open')
|
||||
// Each prompt being answered here, and with which decision: the card waits on the host's outcome.
|
||||
const [submitting, setSubmitting] = useState<ReadonlyMap<string, WorkerApprovalDecision>>(
|
||||
new Map()
|
||||
)
|
||||
const now = useSecondClock(isVisible && open.some(({ approval }) => approval.expiresAt))
|
||||
const answer = (entry: NativeChatWorkerApproval, decision: WorkerApprovalDecision): void => {
|
||||
const { approvalId, worker } = entry.approval
|
||||
setSubmitting((current) => new Map(current).set(approvalId, decision))
|
||||
const name = entry.worker.label
|
||||
callRuntimeRpc(target, 'orchestration.approvalAnswer', {
|
||||
dispatch: worker.dispatchId,
|
||||
prompt: approvalId,
|
||||
decision,
|
||||
...(decision === 'deny' ? { reason: OWNER_DENY_REASON } : {})
|
||||
})
|
||||
// A landed answer needs no toast: the host's list turns the card into its receipt.
|
||||
.catch((error: unknown) => {
|
||||
// Not applied: the host's list decides. A prompt that closed meanwhile (its worker ended,
|
||||
// or it was answered elsewhere) turns into its receipt from that; one still open stays answerable.
|
||||
const code = error instanceof RuntimeRpcCallError ? error.code : null
|
||||
if (code === 'dispatch_inactive' || code === 'approval_not_open') {
|
||||
toast.info(
|
||||
code === 'dispatch_inactive'
|
||||
? t(
|
||||
'components.native-chat.approval.answerWorkerEnded',
|
||||
'{{name}} has ended, so this prompt is closed',
|
||||
{ name }
|
||||
)
|
||||
: t(
|
||||
'components.native-chat.approval.answerNotApplied',
|
||||
'{{name}}: the answer did not reach this prompt',
|
||||
{ name }
|
||||
)
|
||||
)
|
||||
)
|
||||
.finally(() =>
|
||||
setSubmitting((current) => {
|
||||
const next = new Set(current)
|
||||
next.delete(approvalId)
|
||||
return next
|
||||
return
|
||||
}
|
||||
toast.error(
|
||||
t('components.native-chat.approval.answerFailed', '{{name}}: {{detail}}', {
|
||||
name,
|
||||
detail: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
)
|
||||
},
|
||||
[t, target]
|
||||
)
|
||||
})
|
||||
.finally(() =>
|
||||
setSubmitting((current) => {
|
||||
const next = new Map(current)
|
||||
next.delete(approvalId)
|
||||
return next
|
||||
})
|
||||
)
|
||||
}
|
||||
if (approvals.length === 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div className="space-y-4 pb-2" data-native-chat-worker-approvals="">
|
||||
// Bounded by the pane, and the first to give way, so the chat's own prompt card keeps its room.
|
||||
<div
|
||||
className="scrollbar-sleek max-h-[40%] min-h-0 shrink-[4] overflow-y-auto"
|
||||
data-native-chat-worker-approvals=""
|
||||
>
|
||||
{approvals.map((entry) => {
|
||||
const { approval } = entry
|
||||
if (approval.state !== 'open') {
|
||||
// Settling, or only the worker's terminal can answer it: the outcome stays where the card was.
|
||||
return (
|
||||
<div key={approval.approvalId} className="px-3 sm:px-4">
|
||||
<NativeChatResolutionReceipt
|
||||
body={workerApprovalReceiptBody(approval, entry.at, t)}
|
||||
outcome={{
|
||||
worker: entry.worker.label,
|
||||
text: workerApprovalReceiptText(approval, t),
|
||||
...workerApprovalReceiptReason(approval, t)
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
key={approval.approvalId}
|
||||
className="mx-auto w-full max-w-(--chat-content-max-width) pt-2"
|
||||
>
|
||||
<NativeChatWorkerApprovalReceipt entry={entry} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -141,6 +154,7 @@ export function NativeChatWorkerApprovalRows({
|
||||
}
|
||||
}}
|
||||
isSubmitting={submitting.has(approval.approvalId)}
|
||||
submittingOption={submitting.get(approval.approvalId)}
|
||||
worker={{
|
||||
name: entry.worker.label,
|
||||
onOpen: () => void openOrchestrationCrewAgent(entry.worker, target)
|
||||
@@ -154,7 +168,7 @@ export function NativeChatWorkerApprovalRows({
|
||||
)
|
||||
}
|
||||
: {})}
|
||||
placement="transcript"
|
||||
placement="stacked"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
@@ -163,31 +177,17 @@ export function NativeChatWorkerApprovalRows({
|
||||
)
|
||||
}
|
||||
|
||||
/** "N approvals · Show": counts open approvals, and stays up even while the chat has its own prompt. */
|
||||
export function NativeChatWorkerApprovalStrip({
|
||||
approvals,
|
||||
rootRef
|
||||
}: {
|
||||
approvals: readonly NativeChatWorkerApproval[]
|
||||
rootRef: React.RefObject<HTMLElement | null>
|
||||
/** The pinned stack for a chat's own party; it holds the approvals itself, so the pane does not redraw for them. */
|
||||
export function NativeChatPartyWorkerApprovalStack({
|
||||
party,
|
||||
...stack
|
||||
}: Omit<Parameters<typeof NativeChatWorkerApprovalStack>[0], 'approvals'> & {
|
||||
party: string | null
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const open = approvals.filter(({ approval }) => approval.state === 'open')
|
||||
if (open.length === 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<NativeChatWorkerLifetimeStrip
|
||||
text={t('components.native-chat.approval.strip', '{{count}} approvals', {
|
||||
count: open.length,
|
||||
defaultValue_one: '{{count}} approval'
|
||||
})}
|
||||
keepOpenLabel={t('components.native-chat.approval.show', 'Show')}
|
||||
onKeepOpen={() =>
|
||||
rootRef.current
|
||||
?.querySelector(cardSelector(open[0].approval.approvalId))
|
||||
?.scrollIntoView({ block: 'center' })
|
||||
}
|
||||
<NativeChatWorkerApprovalStack
|
||||
approvals={useNativeChatPinnedWorkerApprovals(party)}
|
||||
{...stack}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -206,17 +206,34 @@ function useSecondClock(active: boolean): number {
|
||||
return now
|
||||
}
|
||||
|
||||
/** A coordinator chat's worker approvals: card rows for its transcript, and the strip above its composer. */
|
||||
export function useNativeChatWorkerApprovalSlots(
|
||||
pane: { target: RuntimeClientTarget; sessionId: string },
|
||||
rootRef: React.RefObject<HTMLElement | null>
|
||||
): { rows: React.ReactNode; strip: React.ReactNode } {
|
||||
const approvals = useNativeChatWorkerApprovals(
|
||||
pane.target,
|
||||
isOrcaSessionId(pane.sessionId) ? formatOrcaSessionAddress(pane.sessionId) : null
|
||||
/** The chat's address its workers report to, when it can coordinate: a local Orca session (v1). */
|
||||
export function nativeChatWorkerApprovalParty(pane: {
|
||||
target: RuntimeClientTarget
|
||||
sessionId: string
|
||||
}): string | null {
|
||||
return pane.target.kind === 'local' && isOrcaSessionId(pane.sessionId)
|
||||
? formatOrcaSessionAddress(pane.sessionId)
|
||||
: null
|
||||
}
|
||||
|
||||
/** A coordinator chat's closed worker prompts, each in its transcript at the time the worker
|
||||
* asked. Holds them itself, so only the transcript redraws, and only when a receipt changes. */
|
||||
export function NativeChatWorkerApprovalTimeline({
|
||||
party,
|
||||
children
|
||||
}: {
|
||||
party: string | null
|
||||
children: (timedRows: readonly NativeChatTimedRow[]) => React.ReactNode
|
||||
}): React.ReactNode {
|
||||
const receipts = useNativeChatWorkerApprovalReceipts(party)
|
||||
const timedRows = useMemo(
|
||||
() =>
|
||||
receipts.map((entry) => ({
|
||||
key: `worker-approval:${entry.approval.approvalId}`,
|
||||
at: Date.parse(entry.askedAt ?? entry.at),
|
||||
node: <NativeChatWorkerApprovalReceipt entry={entry} />
|
||||
})),
|
||||
[receipts]
|
||||
)
|
||||
return {
|
||||
rows: <NativeChatWorkerApprovalRows approvals={approvals} target={pane.target} />,
|
||||
strip: <NativeChatWorkerApprovalStrip approvals={approvals} rootRef={rootRef} />
|
||||
}
|
||||
return children(timedRows)
|
||||
}
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import type { OrchestrationWorkerApprovalEntry } from '../../../../../shared/orchestration/orchestration-crew'
|
||||
|
||||
const stream = vi.hoisted(() => ({ emit: (_frame: unknown): void => {} }))
|
||||
vi.mock('@/runtime/rpc/subscriptions/runtime-rpc-subscribe', () => ({
|
||||
subscribeRuntimeRpc: (
|
||||
_target: unknown,
|
||||
_method: string,
|
||||
_params: unknown,
|
||||
handlers: { onEvent: (frame: unknown) => void }
|
||||
) => {
|
||||
stream.emit = handlers.onEvent
|
||||
return Promise.resolve({ unsubscribe: () => {} })
|
||||
}
|
||||
}))
|
||||
|
||||
const feed = await import('./native-chat-worker-approval-feed')
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
const PARTY = 'orca_session_id:chat'
|
||||
function approval(
|
||||
approvalId: string,
|
||||
state: 'open' | 'answered',
|
||||
by?: 'person' | 'terminal-only'
|
||||
): OrchestrationWorkerApprovalEntry {
|
||||
return {
|
||||
approval: {
|
||||
v: 1,
|
||||
approvalId,
|
||||
state,
|
||||
worker: { handle: 'term_w', dispatchId: 'ctx_1', taskId: 'task_1' },
|
||||
summary: { title: 'Allow Bash?', detail: null, reason: null },
|
||||
allowedActions: state === 'open' ? ['allow', 'deny'] : [],
|
||||
...(by
|
||||
? {
|
||||
outcome: {
|
||||
by,
|
||||
decision: by === 'person' ? 'allow' : null,
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
}
|
||||
}
|
||||
: {})
|
||||
},
|
||||
at: '2026-11-11T20:00:00.000Z',
|
||||
worker: { partyKey: 'w', role: 'worker', label: 'w', agentKind: 'claude', status: 'blocked' }
|
||||
}
|
||||
}
|
||||
function send(...entries: OrchestrationWorkerApprovalEntry[]): void {
|
||||
act(() => {
|
||||
stream.emit({ type: 'begin' })
|
||||
for (const entry of entries) {
|
||||
stream.emit({ type: 'approval', entry })
|
||||
}
|
||||
stream.emit({ type: 'complete' })
|
||||
})
|
||||
}
|
||||
|
||||
it('keeps a prompt that closed while shown pinned as its receipt for a moment, then moves it to the transcript', async () => {
|
||||
vi.useFakeTimers()
|
||||
const pinned = renderHook(() => feed.useNativeChatPinnedWorkerApprovals(PARTY))
|
||||
const receipts = renderHook(() => feed.useNativeChatWorkerApprovalReceipts(PARTY))
|
||||
await act(async () => {})
|
||||
send(approval('apr_old', 'answered', 'person'), approval('apr_1', 'open'))
|
||||
expect(pinned.result.current.map((e) => e.approval.approvalId)).toEqual(['apr_1'])
|
||||
const history = receipts.result.current
|
||||
|
||||
// The host closes it: its receipt stays where the card was for a moment.
|
||||
send(approval('apr_old', 'answered', 'person'), approval('apr_1', 'answered', 'person'))
|
||||
expect(pinned.result.current.map((e) => [e.approval.approvalId, e.approval.state])).toEqual([
|
||||
['apr_1', 'answered']
|
||||
])
|
||||
// Only a pinned prompt changed: the transcript's receipts are the same array.
|
||||
expect(receipts.result.current).toBe(history)
|
||||
act(() => vi.advanceTimersByTime(4_000))
|
||||
expect(pinned.result.current).toEqual([])
|
||||
expect(receipts.result.current.map((e) => e.approval.approvalId)).toEqual(['apr_old', 'apr_1'])
|
||||
})
|
||||
|
||||
it('keeps a prompt only the worker terminal can answer pinned', async () => {
|
||||
vi.useFakeTimers()
|
||||
const pinned = renderHook(() => feed.useNativeChatPinnedWorkerApprovals('orca_session_id:other'))
|
||||
await act(async () => {})
|
||||
send(approval('apr_t', 'answered', 'terminal-only'))
|
||||
act(() => vi.advanceTimersByTime(60_000))
|
||||
expect(pinned.result.current.map((e) => e.approval.approvalId)).toEqual(['apr_t'])
|
||||
})
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react'
|
||||
import { subscribeRuntimeRpc } from '@/runtime/rpc/subscriptions/runtime-rpc-subscribe'
|
||||
import {
|
||||
WorkerApprovalsFrame,
|
||||
type OrchestrationWorkerApprovalEntry
|
||||
} from '../../../../../shared/orchestration/orchestration-crew'
|
||||
import { workerApprovalLapsesAt } from './worker-approval-card-model'
|
||||
|
||||
export type NativeChatWorkerApproval = OrchestrationWorkerApprovalEntry
|
||||
|
||||
type Feed = {
|
||||
/** The host's list, as last received. */
|
||||
received: readonly NativeChatWorkerApproval[]
|
||||
/** Prompts that closed while shown, kept pinned until then (epoch ms) so the outcome lands in view. */
|
||||
settling: Map<string, number>
|
||||
settleTimer?: ReturnType<typeof setTimeout>
|
||||
/** Above the composer: open prompts, ones only the worker's terminal can answer, and settling ones. */
|
||||
pinned: readonly NativeChatWorkerApproval[]
|
||||
/** In the transcript, at the time each was asked. */
|
||||
receipts: readonly NativeChatWorkerApproval[]
|
||||
listeners: Set<() => void>
|
||||
dispose: () => void
|
||||
}
|
||||
|
||||
const EMPTY: readonly NativeChatWorkerApproval[] = []
|
||||
// Why 5 s: a dropped local stream is rare; retry without hammering a host that refuses it.
|
||||
const RETRY_MS = 5_000
|
||||
// Why 4 s: long enough to read the outcome where the card was, short enough not to crowd the composer.
|
||||
const SETTLE_MS = 4_000
|
||||
const feeds = new Map<string, Feed>()
|
||||
|
||||
const signature = (entries: readonly NativeChatWorkerApproval[]): string =>
|
||||
entries
|
||||
.map(({ approval, at }) =>
|
||||
[
|
||||
approval.approvalId,
|
||||
approval.state,
|
||||
approval.outcome?.by,
|
||||
approval.outcome?.decision,
|
||||
at
|
||||
].join('\u0000')
|
||||
)
|
||||
.join('\u0001')
|
||||
const keep = (
|
||||
previous: readonly NativeChatWorkerApproval[],
|
||||
next: NativeChatWorkerApproval[]
|
||||
): readonly NativeChatWorkerApproval[] =>
|
||||
signature(previous) === signature(next) ? previous : next.length ? next : EMPTY
|
||||
|
||||
function publish(feed: Feed): void {
|
||||
const wasOpen = new Set(
|
||||
feed.pinned.flatMap(({ approval }) => (approval.state === 'open' ? [approval.approvalId] : []))
|
||||
)
|
||||
const entries = feed.received
|
||||
const now = Date.now()
|
||||
for (const { approval } of entries) {
|
||||
if (approval.state !== 'open' && wasOpen.has(approval.approvalId)) {
|
||||
feed.settling.set(approval.approvalId, now + SETTLE_MS)
|
||||
}
|
||||
}
|
||||
for (const [approvalId, until] of feed.settling) {
|
||||
if (until <= now || !entries.some(({ approval }) => approval.approvalId === approvalId)) {
|
||||
feed.settling.delete(approvalId)
|
||||
}
|
||||
}
|
||||
const pinned = (entry: NativeChatWorkerApproval): boolean =>
|
||||
entry.approval.state === 'open' ||
|
||||
entry.approval.outcome?.by === 'terminal-only' ||
|
||||
feed.settling.has(entry.approval.approvalId)
|
||||
feed.pinned = keep(feed.pinned, entries.filter(pinned))
|
||||
feed.receipts = keep(
|
||||
feed.receipts,
|
||||
entries.filter((entry) => !pinned(entry))
|
||||
)
|
||||
clearTimeout(feed.settleTimer)
|
||||
if (feed.settling.size) {
|
||||
feed.settleTimer = setTimeout(() => publish(feed), Math.min(...feed.settling.values()) - now)
|
||||
}
|
||||
feed.listeners.forEach((notify) => notify())
|
||||
}
|
||||
|
||||
/** One stream per chat party, shared by its transcript rows and its strip; local hosts only (v1).
|
||||
* Not parked while hidden: a hidden coordinator tab still needs its workers' prompts. */
|
||||
function observeWorkerApprovals(party: string, listener: () => void): () => void {
|
||||
let feed = feeds.get(party)
|
||||
if (!feed) {
|
||||
const held: Feed = {
|
||||
received: EMPTY,
|
||||
settling: new Map(),
|
||||
pinned: EMPTY,
|
||||
receipts: EMPTY,
|
||||
listeners: new Set(),
|
||||
dispose: () => {}
|
||||
}
|
||||
feed = held
|
||||
feeds.set(party, held)
|
||||
let close: (() => void) | undefined
|
||||
let retry: ReturnType<typeof setTimeout> | undefined
|
||||
let generation = 0
|
||||
const open = (): void => {
|
||||
const attempt = ++generation
|
||||
const live = () => feeds.get(party) === held && generation === attempt
|
||||
let pending: NativeChatWorkerApproval[] | undefined
|
||||
// Keeps the cards it has: the next stream sends the current list as soon as it opens.
|
||||
const lose = (error?: unknown): void => {
|
||||
if (!live()) {
|
||||
return
|
||||
}
|
||||
generation += 1
|
||||
close?.()
|
||||
close = undefined
|
||||
const code =
|
||||
typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined
|
||||
if (code !== 'method_not_found' && code !== 'forbidden') {
|
||||
retry = setTimeout(open, RETRY_MS)
|
||||
}
|
||||
}
|
||||
void subscribeRuntimeRpc(
|
||||
{ kind: 'local' },
|
||||
'orchestration.workerApprovalsSubscribe',
|
||||
{ party },
|
||||
{
|
||||
onEvent: (value) => {
|
||||
const parsed = WorkerApprovalsFrame.safeParse(value)
|
||||
if (!live() || !parsed.success) {
|
||||
return
|
||||
}
|
||||
const frame = parsed.data
|
||||
if (frame.type === 'begin') {
|
||||
pending = []
|
||||
} else if (frame.type === 'approval') {
|
||||
pending?.push(frame.entry)
|
||||
} else if (frame.type === 'complete' && pending) {
|
||||
held.received = pending.length ? pending : EMPTY
|
||||
pending = undefined
|
||||
publish(held)
|
||||
} else if (frame.type === 'end') {
|
||||
lose()
|
||||
}
|
||||
},
|
||||
onError: lose,
|
||||
onClose: lose
|
||||
}
|
||||
).then((handle) => {
|
||||
if (live()) {
|
||||
close = handle.unsubscribe
|
||||
} else {
|
||||
handle.unsubscribe()
|
||||
}
|
||||
}, lose)
|
||||
}
|
||||
held.dispose = () => {
|
||||
generation += 1
|
||||
clearTimeout(held.settleTimer)
|
||||
clearTimeout(retry)
|
||||
close?.()
|
||||
}
|
||||
open()
|
||||
}
|
||||
const held = feed
|
||||
held.listeners.add(listener)
|
||||
return () => {
|
||||
held.listeners.delete(listener)
|
||||
// A remount in the same task keeps the stream.
|
||||
queueMicrotask(() => {
|
||||
if (held.listeners.size === 0 && feeds.get(party) === held) {
|
||||
feeds.delete(party)
|
||||
held.dispose()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** A chat coordinator's workers' approvals for the pinned area, oldest first; an open one leaves
|
||||
* once its countdown lapses with no closing report. None for no party. */
|
||||
export function useNativeChatPinnedWorkerApprovals(
|
||||
party: string | null
|
||||
): readonly NativeChatWorkerApproval[] {
|
||||
const pinned = useFeedPart(party, 'pinned')
|
||||
const [now, setNow] = useState(Date.now)
|
||||
const nextLapse = Math.min(
|
||||
...pinned.map(({ approval }) => workerApprovalLapsesAt(approval)).filter((at) => at > now)
|
||||
)
|
||||
useEffect(() => {
|
||||
if (!Number.isFinite(nextLapse)) {
|
||||
return
|
||||
}
|
||||
const timer = setTimeout(() => setNow(Date.now()), nextLapse - Date.now())
|
||||
return () => clearTimeout(timer)
|
||||
}, [nextLapse])
|
||||
return useMemo(
|
||||
() => pinned.filter(({ approval }) => workerApprovalLapsesAt(approval) > now),
|
||||
[pinned, now]
|
||||
)
|
||||
}
|
||||
|
||||
/** A chat coordinator's closed worker approvals for its transcript; the same array until one changes. */
|
||||
export function useNativeChatWorkerApprovalReceipts(
|
||||
party: string | null
|
||||
): readonly NativeChatWorkerApproval[] {
|
||||
return useFeedPart(party, 'receipts')
|
||||
}
|
||||
|
||||
function useFeedPart(
|
||||
party: string | null,
|
||||
part: 'pinned' | 'receipts'
|
||||
): readonly NativeChatWorkerApproval[] {
|
||||
const subscribe = useCallback(
|
||||
(listener: () => void) => (party ? observeWorkerApprovals(party, listener) : () => {}),
|
||||
[party]
|
||||
)
|
||||
return useSyncExternalStore(subscribe, () =>
|
||||
party ? (feeds.get(party)?.[part] ?? EMPTY) : EMPTY
|
||||
)
|
||||
}
|
||||
+5
-3
@@ -51,12 +51,12 @@ export function workerApprovalReceiptBody(
|
||||
}
|
||||
}
|
||||
|
||||
/** Who answered, from the closing message's evidence; anything it does not name is "No longer open". */
|
||||
/** Who answered, from the closing message's evidence; a close it does not name says only that. */
|
||||
export function workerApprovalReceiptText(approval: WorkerApprovalPayload, t: Translate): string {
|
||||
const outcome = approval.outcome
|
||||
const decision = outcome?.decision ?? null
|
||||
const by = outcome?.by
|
||||
switch (decision === null && by !== 'terminal-only' ? 'unknown' : by) {
|
||||
switch (decision === null && by !== 'terminal-only' && by !== 'worker-ended' ? 'unknown' : by) {
|
||||
case 'person':
|
||||
return decision === 'allow'
|
||||
? t('components.native-chat.approval.allowedByYou', 'Allowed by you')
|
||||
@@ -76,9 +76,11 @@ export function workerApprovalReceiptText(approval: WorkerApprovalPayload, t: Tr
|
||||
'components.native-chat.approval.answerInTerminal',
|
||||
"Answer it in the worker's terminal"
|
||||
)
|
||||
case 'worker-ended':
|
||||
return t('components.native-chat.approval.workerEnded', 'No longer open · worker ended')
|
||||
case 'unknown':
|
||||
case undefined:
|
||||
return t('components.native-chat.approval.noLongerOpen', 'No longer open')
|
||||
return t('components.native-chat.approval.closedUnnamed', 'Closed without a recorded answer')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-2
@@ -1608,8 +1608,6 @@
|
||||
"startupMenu": {
|
||||
"title": "{{value0}} is waiting for a choice in the terminal"
|
||||
},
|
||||
"strip_one": "{{count}} approval",
|
||||
"strip_other": "{{count}} approvals",
|
||||
"title": "Allow {{value0}}?"
|
||||
},
|
||||
"ask": {
|
||||
|
||||
@@ -20961,18 +20961,18 @@
|
||||
"worker": "Worker · {{name}}",
|
||||
"openWorker": "Open worker",
|
||||
"answerFailed": "{{name}}: {{detail}}",
|
||||
"answerNotApplied": "{{name}}: the answer did not reach this prompt",
|
||||
"answerWorkerEnded": "{{name}} has ended, so this prompt is closed",
|
||||
"countdown": "Claude denies it on its own in {{time}} if nobody answers.",
|
||||
"strip_one": "{{count}} approval",
|
||||
"strip_other": "{{count}} approvals",
|
||||
"show": "Show",
|
||||
"allowedByYou": "Allowed by you",
|
||||
"deniedByYou": "Denied by you",
|
||||
"deniedByCoordinator": "Denied by coordinator",
|
||||
"allowedInTerminal": "Allowed in the worker's terminal",
|
||||
"deniedInTerminal": "Denied in the worker's terminal",
|
||||
"answeredInChat": "Answered in the worker's chat",
|
||||
"noLongerOpen": "No longer open",
|
||||
"closedUnnamed": "Closed without a recorded answer",
|
||||
"autoDenied": "Auto-denied by Claude after 2:00",
|
||||
"workerEnded": "No longer open · worker ended",
|
||||
"answerInTerminal": "Answer it in the worker's terminal"
|
||||
},
|
||||
"launchPromptNotDelivered": "Not delivered — check the terminal",
|
||||
|
||||
@@ -7,7 +7,8 @@ export type WorkerApprovalDecision = z.infer<typeof WorkerApprovalDecisionSchema
|
||||
|
||||
/** 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`: closed for Orca while
|
||||
* the prompt is still up; only a person at the worker's terminal can answer it. */
|
||||
* the prompt is still up; only a person at the worker's terminal can answer it. `worker-ended`: its
|
||||
* Dispatch stopped running, so nothing is left to answer. */
|
||||
export const WorkerApprovalAnswererSchema = z.enum([
|
||||
'person',
|
||||
'coordinator',
|
||||
@@ -15,6 +16,7 @@ export const WorkerApprovalAnswererSchema = z.enum([
|
||||
'worker-terminal',
|
||||
'auto',
|
||||
'terminal-only',
|
||||
'worker-ended',
|
||||
'unknown'
|
||||
])
|
||||
export type WorkerApprovalAnswerer = z.infer<typeof WorkerApprovalAnswererSchema>
|
||||
@@ -48,3 +50,21 @@ export const WorkerApprovalPayloadSchema = z.object({
|
||||
})
|
||||
export type WorkerApprovalPayload = z.infer<typeof WorkerApprovalPayloadSchema>
|
||||
export type WorkerApprovalState = WorkerApprovalPayload['state']
|
||||
|
||||
/** The same approval once closed: nothing left to answer, and how it closed. */
|
||||
export function closedApproval(
|
||||
open: WorkerApprovalPayload,
|
||||
outcome: WorkerApprovalOutcome
|
||||
): WorkerApprovalPayload {
|
||||
const closed: WorkerApprovalPayload = {
|
||||
...open,
|
||||
// Expired is the agent's own timeout alone; every other close, named or not, is not one.
|
||||
state: outcome.by === 'auto' ? 'expired' : 'answered',
|
||||
allowedActions: [],
|
||||
// Only a reason can be delivered.
|
||||
outcome: { ...outcome, reasonDelivered: outcome.reason !== null && outcome.reasonDelivered }
|
||||
}
|
||||
// A countdown means nothing once the prompt is closed.
|
||||
delete closed.expiresAt
|
||||
return closed
|
||||
}
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { z } from 'zod'
|
||||
import { isPublicOrchestrationAddress } from './mailbox/orchestration-agent-reference'
|
||||
import { WorkerApprovalPayloadSchema } from './approvals/worker-approval-payload'
|
||||
import { parseOrcaSessionAddress } from '../orca-session-address'
|
||||
|
||||
export const CrewParty = z.string().refine(isPublicOrchestrationAddress)
|
||||
export const CrewSubscribeParams = z.object({ party: CrewParty })
|
||||
const CrewRowApproval = z.object({
|
||||
approval: WorkerApprovalPayloadSchema,
|
||||
at: z.string(),
|
||||
/** When the worker asked: where its card sits in the chat, open or answered. */
|
||||
askedAt: z.string().optional()
|
||||
})
|
||||
export const CrewRow = z.object({
|
||||
partyKey: z.string(),
|
||||
role: z.enum(['manager', 'worker', 'peer']),
|
||||
@@ -23,9 +30,7 @@ export const CrewRow = z.object({
|
||||
.optional(),
|
||||
pendingQuestion: z.object({ preview: z.string(), at: z.string() }).optional(),
|
||||
/** This worker's permission prompts addressed to the viewing party, each as its newest message: open ones, and recent receipts. */
|
||||
approvals: z
|
||||
.array(z.object({ approval: WorkerApprovalPayloadSchema, at: z.string() }))
|
||||
.optional(),
|
||||
approvals: z.array(CrewRowApproval).optional(),
|
||||
sendAddress: CrewParty.optional(),
|
||||
openTarget: z
|
||||
.discriminatedUnion('kind', [
|
||||
@@ -56,6 +61,23 @@ export const CrewFrame = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('end') })
|
||||
])
|
||||
export type OrchestrationCrewFrame = z.infer<typeof CrewFrame>
|
||||
|
||||
/** A chat coordinator's worker approvals alone, so a chat need not follow its whole crew. */
|
||||
export const WorkerApprovalsSubscribeParams = z.object({
|
||||
party: CrewParty.refine((party) => parseOrcaSessionAddress(party) !== null)
|
||||
})
|
||||
export const WorkerApprovalEntry = CrewRowApproval.extend({
|
||||
worker: CrewRow.omit({ approvals: true })
|
||||
})
|
||||
export type OrchestrationWorkerApprovalEntry = z.infer<typeof WorkerApprovalEntry>
|
||||
export const WorkerApprovalsFrame = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('begin') }),
|
||||
// One approval per frame: a frame stays small whatever the count.
|
||||
z.object({ type: z.literal('approval'), entry: WorkerApprovalEntry }),
|
||||
z.object({ type: z.literal('complete') }),
|
||||
z.object({ type: z.literal('end') })
|
||||
])
|
||||
export type OrchestrationWorkerApprovalsFrame = z.infer<typeof WorkerApprovalsFrame>
|
||||
export function emptyCrew(status: 'ok' | 'unknown'): OrchestrationCrewSnapshot {
|
||||
return { status, sections: { managedBy: [], managing: [], talkingWith: [] } }
|
||||
}
|
||||
|
||||
+5
-1
@@ -40,7 +40,10 @@ import {
|
||||
OrcadPeerDesktopsParamsSchema
|
||||
} from '../orcad-peer-desktops-contract'
|
||||
import { OrcadTerminalCensusParamsSchema } from '../orcad-terminal-census'
|
||||
import { CrewSubscribeParams } from '../orchestration/orchestration-crew'
|
||||
import {
|
||||
CrewSubscribeParams,
|
||||
WorkerApprovalsSubscribeParams
|
||||
} from '../orchestration/orchestration-crew'
|
||||
import { PeerRunCancelParams } from '../orchestration/remote-owned-wire'
|
||||
import { RegisterDeviceKeyParamsSchema } from '../remote-runtime/pairing/device-key-registration-contract'
|
||||
import { PairingCreateOfferParamsSchema } from '../remote-runtime/pairing/pairing-create-offer-contract'
|
||||
@@ -1393,6 +1396,7 @@ export const RPC_PARAMS_BY_METHOD = {
|
||||
'orchestration.taskCreate': TaskCreateParams,
|
||||
'orchestration.taskList': TaskListParams,
|
||||
'orchestration.workerAbandon': WorkerDispatchParams,
|
||||
'orchestration.workerApprovalsSubscribe': WorkerApprovalsSubscribeParams,
|
||||
'orchestration.workerAutoClose': OrchestrationWorkerSubjectParams,
|
||||
'orchestration.workerChatTouch': OrchestrationWorkerSubjectParams,
|
||||
'orchestration.workerKeepOpen': OrchestrationWorkerKeepOpenParams,
|
||||
|
||||
Reference in New Issue
Block a user