From ac45d424686ea4869ef6f9934c50d65fa3da0c89 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:35:24 -0800 Subject: [PATCH] fix(orchestration): advise coordinators when a running worker goes quiet Track producer activity separately from renewed status leases and send advisory status mail after sustained silence, with longer grace for tools and agents whose progress is not visible. Keep notices deduplicated across restarts and explain the advisory behavior in the coordinator guide. Co-authored-by: Taras Kornichuk --- skill-guides/orchestration.md | 3 + src/cli/skills/bundled-skill-guides.ts | 3 + .../agent-hooks/server/producer-progress.ts | 107 +++++++++++ .../server/server-authority-aliases.ts | 1 + src/main/agent-hooks/server/server-cleanup.ts | 1 + .../server/server-ingest-normalization.ts | 10 +- .../server/server-ingest-terminal.ts | 6 +- .../agent-hooks/server/server-lifecycle.ts | 1 + src/main/agent-hooks/server/server-state.ts | 3 + .../host/electron-runtime-desktop-surface.ts | 6 + ...ctured-agent-session-conversation-reads.ts | 34 ++++ .../orca-runtime-agent-transitions.ts | 11 ++ .../construction/runtime-desktop-surface.ts | 1 + .../workers/reports/worker-quiet-report.ts | 109 +++++++++++ .../workers/reports/worker-quiet-runtime.ts | 178 ++++++++++++++++++ .../reports/worker-quiet-sweep.test.ts | 145 ++++++++++++++ .../workers/reports/worker-quiet-sweep.ts | 160 ++++++++++++++++ .../workspace-activity-facts-producer.ts | 2 +- 18 files changed, 778 insertions(+), 3 deletions(-) create mode 100644 src/main/agent-hooks/server/producer-progress.ts create mode 100644 src/main/runtime/orchestration/workers/reports/worker-quiet-report.ts create mode 100644 src/main/runtime/orchestration/workers/reports/worker-quiet-runtime.ts create mode 100644 src/main/runtime/orchestration/workers/reports/worker-quiet-sweep.test.ts create mode 100644 src/main/runtime/orchestration/workers/reports/worker-quiet-sweep.ts diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index 783cc6f251f..39e7deca489 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -80,6 +80,9 @@ Never: - An `escalation` with `stopReason` means the worker stopped without `worker_done`: steer it with `send`, stop and retry it, or tell the user. `exited` or `lost` means it is gone: retry it or tell the user. +- A `status` with `quietNotice` is advisory: the worker is still running and + silence may be normal. Don't stop or message it unless the user asks or you + know it should have finished. Continue other work or keep waiting. - A `worker_done` settles its Task; never mark a reported failure completed. - When every worker has settled, report to the user per Task: outcome, evidence, open blockers. diff --git a/src/cli/skills/bundled-skill-guides.ts b/src/cli/skills/bundled-skill-guides.ts index 720731c3019..67a82331580 100644 --- a/src/cli/skills/bundled-skill-guides.ts +++ b/src/cli/skills/bundled-skill-guides.ts @@ -4088,6 +4088,9 @@ const ORCHESTRATION_MARKDOWN = [ "- An `escalation` with `stopReason` means the worker stopped without", " `worker_done`: steer it with `send`, stop and retry it, or tell the user.", " `exited` or `lost` means it is gone: retry it or tell the user.", + "- A `status` with `quietNotice` is advisory: the worker is still running and", + " silence may be normal. Don't stop or message it unless the user asks or you", + " know it should have finished. Continue other work or keep waiting.", "- A `worker_done` settles its Task; never mark a reported failure completed.", "- When every worker has settled, report to the user per Task: outcome,", " evidence, open blockers.", diff --git a/src/main/agent-hooks/server/producer-progress.ts b/src/main/agent-hooks/server/producer-progress.ts new file mode 100644 index 00000000000..d2a2b0a53ed --- /dev/null +++ b/src/main/agent-hooks/server/producer-progress.ts @@ -0,0 +1,107 @@ +import { sameAgentStatusSessionOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' +import { isSameAgentProcess } from '../../../shared/agent-status/process/agent-process-presence' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' + +type ProgressOwner = Pick< + AgentHookEventPayload, + 'connectionId' | 'worktreeId' | 'agentPresence' | 'providerSession' +> & { agentType: string | undefined } + +export type ProducerProgress = { + lastProducerEventAt: number + tools: Map +} + +/** Producer observations have a separate clock because status leases and replays renew receivedAt. */ +export class ProducerProgressStore { + private readonly rows = new Map() + + get(paneKey: string): ProducerProgress | undefined { + return this.rows.get(paneKey) + } + + clear(): void { + this.rows.clear() + } + + delete(paneKey: string): void { + this.rows.delete(paneKey) + } + + move(from: string, to: string): void { + const row = this.rows.get(from) + this.rows.delete(from) + if (row) { + this.rows.set(to, row) + } + } + + retireOwner(next: AgentHookEventPayload): void { + const previous = this.rows.get(next.paneKey)?.owner + if ( + previous && + (!sameAgentStatusSessionOwner(previous, next) || + previous.agentType !== next.payload.agentType || + (previous.agentPresence?.process && + next.agentPresence?.process && + !isSameAgentProcess(previous.agentPresence.process, next.agentPresence.process))) + ) { + this.delete(next.paneKey) + } + } + + observe(event: AgentHookEventPayload, now: number, newOwner = false): void { + if (event.isReplay || event.providerSessionOnly) { + return + } + this.retireOwner(event) + let row = newOwner ? undefined : this.rows.get(event.paneKey) + if ( + !row || + (!event.toolAgentId && + (event.hookEventName === 'UserPromptSubmit' || event.hookEventName === 'SessionStart')) + ) { + row = { + lastProducerEventAt: now, + tools: new Map(), + owner: { + connectionId: event.connectionId, + worktreeId: event.worktreeId, + agentPresence: event.agentPresence, + providerSession: event.providerSession, + agentType: event.payload.agentType + } + } + this.rows.set(event.paneKey, row) + } + row.owner = { + connectionId: event.connectionId, + worktreeId: event.worktreeId ?? row.owner.worktreeId, + agentPresence: event.agentPresence ?? row.owner.agentPresence, + providerSession: event.providerSession ?? row.owner.providerSession, + agentType: event.payload.agentType + } + row.lastProducerEventAt = now + const key = JSON.stringify([event.toolAgentId ?? '', event.toolUseId ?? '']) + if (event.hookEventName === 'PreToolUse' && event.toolUseId) { + row.tools.set(key, { name: event.payload.toolName ?? 'a tool', startedAt: now }) + } else if ( + event.hookEventName === 'PostToolUse' || + event.hookEventName === 'PostToolUseFailure' + ) { + row.tools.delete(key) + } else if (event.hookEventName === 'SubagentStop') { + for (const call of row.tools.keys()) { + if (JSON.parse(call)[0] === event.toolAgentId) { + row.tools.delete(call) + } + } + } + for (const call of event.claudeSettledRequests ?? []) { + row.tools.delete(JSON.stringify([call.toolAgentId ?? '', call.toolUseId])) + } + if (event.payload.state === 'done') { + row.tools.clear() + } + } +} diff --git a/src/main/agent-hooks/server/server-authority-aliases.ts b/src/main/agent-hooks/server/server-authority-aliases.ts index a6b348207b2..9ed661f37ca 100644 --- a/src/main/agent-hooks/server/server-authority-aliases.ts +++ b/src/main/agent-hooks/server/server-authority-aliases.ts @@ -178,6 +178,7 @@ export abstract class AgentHookServerAuthorityAliases extends AgentHookServerAut | EnrichedAgentHookEventPayload | undefined const hadStatus = previousStatus !== undefined + this.producerProgress.move(previousOwnerPaneKey, toPaneKey) movePaneCacheState(this.state, previousOwnerPaneKey, toPaneKey) const movedStatus = this.state.lastStatusByPaneKey.get(toPaneKey) as | EnrichedAgentHookEventPayload diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index be3d6c2b5d1..d609f42e8f3 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -304,6 +304,7 @@ export abstract class AgentHookServerCleanup extends AgentHookServerAuthorityFen if (!existing) { return this.deleteTmuxSelectedStatus(resolvedPaneKey) ?? null } + this.producerProgress.delete(resolvedPaneKey) deleteLegacyAgentStatus(this.state, resolvedPaneKey) this.activeHookTurnCompletedAtByPaneKey.delete(resolvedPaneKey) if (!options?.preserveAuthority) { diff --git a/src/main/agent-hooks/server/server-ingest-normalization.ts b/src/main/agent-hooks/server/server-ingest-normalization.ts index d9cd3dcd580..06ae1dbb752 100644 --- a/src/main/agent-hooks/server/server-ingest-normalization.ts +++ b/src/main/agent-hooks/server/server-ingest-normalization.ts @@ -86,8 +86,16 @@ export abstract class AgentHookServerIngestNormalization extends AgentHookServer protected override applyNormalizedStatus( ...args: Parameters ): EnrichedAgentHookEventPayload | undefined { - const applied = super.applyNormalizedStatus(...args) const [incoming, , origin = 'hook'] = args + const now = Date.now() + const restated = this.restatingStatus + const applied = super.applyNormalizedStatus(...args) + if (applied) { + this.producerProgress.retireOwner(applied) + if (origin === 'hook' && !restated && incoming.hookEventName && !incoming.isReplay) { + this.producerProgress.observe(incoming, now) + } + } // Claude can still block the prompt after this hook, and its idle may already have landed. if ( applied?.payload.agentType === 'claude' && diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index a15b3514900..2153fdd8df5 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -219,6 +219,7 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges if (hookOwnsAgent && previous && Number.isFinite(yieldEndsAt)) { const yieldedTo = previous.receivedAt const delayMs = yieldEndsAt - now + const replay = { ...event, renewsProgramStatusLease: true as const } this.hookSilenceRechecks.defer(paneKey, delayMs + 1, (currentPaneKey) => { const row = this.state.lastStatusByPaneKey.get(currentPaneKey) // Re-offer only against the hook observation this report yielded to. @@ -229,13 +230,16 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges row.receivedAt === yieldedTo ) { const tabId = parsePaneKey(currentPaneKey)?.tabId ?? event.tabId - this.ingestTerminalStatus({ ...event, paneKey: currentPaneKey, tabId }) + this.ingestTerminalStatus({ ...replay, paneKey: currentPaneKey, tabId }) } }) } else { this.hookSilenceRechecks.cancel(paneKey) } } + if (event.fromProgramStatus && !event.renewsProgramStatusLease) { + this.producerProgress.observe({ paneKey, connectionId, payload }, now, newRun) + } if ( hookOwnsCommand || hookOwnsAgent || diff --git a/src/main/agent-hooks/server/server-lifecycle.ts b/src/main/agent-hooks/server/server-lifecycle.ts index ee11455bd04..913a583d2a0 100644 --- a/src/main/agent-hooks/server/server-lifecycle.ts +++ b/src/main/agent-hooks/server/server-lifecycle.ts @@ -294,6 +294,7 @@ export abstract class AgentHookServerLifecycle extends AgentHookServerStatusHook this.connectionTimestampWatermarkById.clear() this.evidenceObservedAtByPaneKey.clear() this.programStatusFacets.clear() + this.producerProgress.clear() this.activeHookTurnCompletedAtByPaneKey.clear() this.legacyPaneKeyAliases.clear() this.paneKeyAliasPersistenceListener = null diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 50540e4d621..c473b3c381e 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -54,11 +54,14 @@ import type { StatusFreshnessListener, StatusRowMutationListener } from './server-types' +import { ProducerProgressStore } from './producer-progress' import { RevisionedMap } from './revisioned-map' import { forgetAgentExit, type AgentExitEvidence } from './agent-exit-evidence' import type { LastStatusStore } from './last-status-store' export abstract class AgentHookServerState { + readonly producerProgress = new ProducerProgressStore() + protected canWriteLegacyStatusRow(entry: AgentHookEventPayload): boolean { return canAdmitLegacyAgentStatusEntry( this.state, diff --git a/src/main/host/electron-runtime-desktop-surface.ts b/src/main/host/electron-runtime-desktop-surface.ts index 410a94a3ce5..08c41014ab0 100644 --- a/src/main/host/electron-runtime-desktop-surface.ts +++ b/src/main/host/electron-runtime-desktop-surface.ts @@ -8,6 +8,12 @@ import { fetchWithElectronManualRedirects } from './electron-manual-redirect-fet import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../shared/sidebar-inputs-switch' export const electronRuntimeDesktopSurface: RuntimeDesktopSurface = { + onResume: (listener) => { + powerMonitor.on('resume', listener) + return () => { + powerMonitor.off('resume', listener) + } + }, translateNotification: translateMain, isAwayForMobileNotifications: () => readDesktopAwayState(powerMonitor), showNotification: ({ title, body }) => { diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-conversation-reads.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-conversation-reads.ts index d1312fd9201..4e2a7323aa5 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-conversation-reads.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-conversation-reads.ts @@ -60,6 +60,40 @@ export function createStructuredAgentSessionConversationReads(context: () => Rea readModelCatalog, attentionReads: { + workerProgress: (sessionId: string) => { + const session = context().sessions.get(sessionId) + const turn = session?.journal.runningTurn() + const child = session?.child + if (!session || !turn || !child) { + return null + } + const { journal } = session + let tool: { name: string; startedAt: number } | undefined + journal.visitItemsWithLinkage((id, _sequence, body, attribution) => { + if ( + body.kind !== 'tool-call' || + body.state !== 'running' || + journal.itemFence(id) !== child.fence || + attribution.turnScope?.kind !== 'turn' || + attribution.turnScope.turnItemId !== turn.item.itemId + ) { + return + } + const startedAt = journal.item(id)?.observedAt ?? turn.item.observedAt + if (!tool || startedAt < tool.startedAt) { + tool = { name: body.name, startedAt } + } + }) + return { + turnStartedAt: + turn.item.body.kind === 'turn' + ? (turn.item.body.startedAt ?? turn.item.observedAt) + : turn.item.observedAt, + lastProducerEventAt: journal.lastProviderActivityAt(child.fence), + tool + } + }, + workspace: async ( location: AgentSessionExecutionLocation ): Promise<(StructuredAttentionRead & { scope: AgentSessionExecutionLocation })[]> => { diff --git a/src/main/runtime/construction/orca-runtime-agent-transitions.ts b/src/main/runtime/construction/orca-runtime-agent-transitions.ts index cc3f80fe66e..6ae1a6c2c73 100644 --- a/src/main/runtime/construction/orca-runtime-agent-transitions.ts +++ b/src/main/runtime/construction/orca-runtime-agent-transitions.ts @@ -31,6 +31,8 @@ import { type TerminalAgentWorkspaceLabels } from '../push/notifications/terminal-agent-phone-push' +import { startWorkerQuietSweep } from '../orchestration/workers/reports/worker-quiet-runtime' + function unrefTimer(run: () => void, delayMs: number): { cancel: () => void } { const timer = setTimeout(run, delayMs) timer.unref?.() @@ -172,6 +174,14 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithWin attachAgentStatusStore(store: AgentStatusStoreView): () => void { // Attach connector watches at hook-store startup, before any connector call. this.externalConversations.current() + const stopQuietSweep = startWorkerQuietSweep({ + store, + getDb: () => this._orchestrationDb, + resolveTerminal: (paneKey) => + resolveTerminalWorkerDispatch(this.terminalWorkerResolution, paneKey), + readPty: (paneKey) => this.getPtyRecordForPaneKey(paneKey), + notify: this.workerTurnStopReportDeps.notify + }) const detachTransitions = this.agentTransitions.attach(store) const detachCrew = store.subscribeStatusRowMutations(() => this.crewChanges.notify(new Set(['status', 'names'])) @@ -183,6 +193,7 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithWin ? subscribeHookStatusTitles({ subscribeEnrichedStatus: subscribe }, this) : () => {} return () => { + stopQuietSweep() detachCrew() detachRows() this.crewChanges.notify(new Set(['status', 'names'])) diff --git a/src/main/runtime/construction/runtime-desktop-surface.ts b/src/main/runtime/construction/runtime-desktop-surface.ts index 1575e63a7bd..ce697a9cdbb 100644 --- a/src/main/runtime/construction/runtime-desktop-surface.ts +++ b/src/main/runtime/construction/runtime-desktop-surface.ts @@ -4,6 +4,7 @@ import type { BrowserWindow, IpcMainEvent, WebContents } from 'electron' * Node hosts legitimately lack these; terminal creation uses background spawn without a window (#10333), and notifications route to paired clients. */ export type RuntimeDesktopSurface = { + onResume?(listener: () => void): () => void /** Headless hosts retain the formatter's English defaults. */ translateNotification?(key: string, fallback: string): string /** This machine's own idle state; undefined is unknown. Absent on hosts with no desktop. */ diff --git a/src/main/runtime/orchestration/workers/reports/worker-quiet-report.ts b/src/main/runtime/orchestration/workers/reports/worker-quiet-report.ts new file mode 100644 index 00000000000..69cba6d385e --- /dev/null +++ b/src/main/runtime/orchestration/workers/reports/worker-quiet-report.ts @@ -0,0 +1,109 @@ +import type { OrchestrationDb } from '../../db/orchestration-db' +import { dispatchReportMailbox } from './dispatch-report-mailbox' +import { escalateWorkerFailure } from './worker-failure-escalation' +import { stopReportId, type WorkerTurnStopDispatch } from '../turn-stops/worker-turn-stop-report' +import type { QuietNotice, WorkerQuietObservation } from './worker-quiet-sweep' + +export function latestWorkerQuietNotice( + db: OrchestrationDb, + dispatchId: string +): QuietNotice | undefined { + const runId = db.getDispatchContextById(dispatchId)?.run_id ?? '' + const rows = db.db + .prepare(` + SELECT payload FROM messages WHERE run_id = ? AND CASE WHEN json_valid(payload) THEN json_extract(payload, '$.quietNotice.dispatchId') END = ? + UNION ALL + SELECT CASE WHEN json_valid(payload) THEN json_extract(payload, '$.payload') END AS payload FROM federation_relay_items + WHERE dispatch_id = ? AND direction = 'to_home' + `) + .all(runId, dispatchId, dispatchId) + let latest: QuietNotice | undefined + for (const row of rows) { + if (typeof row.payload !== 'string') { + continue + } + try { + const notice: QuietNotice | undefined = JSON.parse(row.payload).quietNotice + if ( + notice && + notice.dispatchId === dispatchId && + (!latest || notice.observedAt > latest.observedAt) + ) { + latest = notice + } + } catch { + /* Older mail can carry plain text payloads. */ + } + } + return latest +} + +export function reportWorkerQuiet( + db: OrchestrationDb, + target: WorkerTurnStopDispatch, + worker: WorkerQuietObservation & { from: string; agent: string }, + notice: QuietNotice, + notify: (handle: string, type: string) => void +): boolean { + const id = stopReportId(worker.dispatchId, `quiet:${worker.turnStartedAt}:${notice.ordinal}`) + const minutes = Math.floor( + (notice.observedAt - + (worker.tool?.startedAt ?? + worker.lastProducerEventAt ?? + worker.workingSince ?? + worker.turnStartedAt)) / + 60_000 + ) + const detail = + worker.lastProducerEventAt === undefined + ? `Orca can't see ${worker.agent}'s progress; it has shown working for ${minutes} min.` + : worker.tool + ? `${worker.agent} has been running ${worker.tool.name} for ${minutes} min.` + : `${worker.agent} has shown no progress for ${minutes} min.` + const subject = 'Worker is still running quietly' + const body = `Worker ${worker.from} (${worker.agent}) is still running. ${detail} This may be normal. Don't stop or message it unless the user asks or you know it should have finished.` + const taskId = target.kind === 'local' ? target.dispatch.task_id : target.attachment.task_id + const payload = { + taskId, + dispatchId: worker.dispatchId, + handle: worker.from, + quietNotice: notice + } + if (target.kind === 'local') { + escalateWorkerFailure( + db, + target.dispatch, + { + id, + from: worker.from, + notice: true, + mailbox: () => dispatchReportMailbox(db, target.dispatch), + describe: () => ({ subject, body }), + payload + }, + notify + ) + return db.getMessageById(id) !== undefined + } + try { + db.enqueueFederationRelay({ + dispatchId: worker.dispatchId, + direction: 'to_home', + kind: 'status', + messageId: id, + payload: JSON.stringify({ + from: worker.from, + subject, + body, + type: 'status', + priority: 'normal', + threadId: null, + payload: JSON.stringify(payload) + }) + }) + return true + } catch (error) { + console.warn('[orchestration] failed to relay a quiet worker notice', worker.dispatchId, error) + return false + } +} diff --git a/src/main/runtime/orchestration/workers/reports/worker-quiet-runtime.ts b/src/main/runtime/orchestration/workers/reports/worker-quiet-runtime.ts new file mode 100644 index 00000000000..27520477b8f --- /dev/null +++ b/src/main/runtime/orchestration/workers/reports/worker-quiet-runtime.ts @@ -0,0 +1,178 @@ +import type { AgentStatusStoreView } from '../../../sidebar-inputs/workspace-activity-facts-producer' +import type { OrchestrationDb } from '../../db/orchestration-db' +import type { RuntimePtyWorktreeRecord } from '../../../terminal/records/runtime-terminal-state-records' +import { getRuntimeDesktopSurface } from '../../../construction/runtime-desktop-surface' +import { WorkerQuietSweep, type WorkerQuietObservation } from './worker-quiet-sweep' +import { latestWorkerQuietNotice, reportWorkerQuiet } from './worker-quiet-report' +import type { WorkerTurnStopDispatch } from '../turn-stops/worker-turn-stop-report' +import type { resolveTerminalWorkerDispatch } from '../turn-stops/terminal-worker-turn-stops' +import type { + DispatchContextRow, + RemoteDispatchAttachmentRow +} from '../../db/orchestration-records' +import { + DISPATCH_CONTEXT_COLUMN_LIST, + REMOTE_DISPATCH_ATTACHMENT_COLUMN_LIST +} from '../../db/row-column-lists' +import { + resolveStructuredWorkerIdentity, + structuredWorkerSession +} from '../../terminal-authority/structured-sessions/structured-worker-authority' +import { getStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' + +export function startWorkerQuietSweep(deps: { + store: AgentStatusStoreView + getDb: () => OrchestrationDb | null + resolveTerminal: (paneKey: string) => ReturnType + readPty: (paneKey: string) => RuntimePtyWorktreeRecord | null + notify: (handle: string, type: string) => void +}): () => void { + const candidates = new Map< + string, + { target: WorkerTurnStopDispatch; from: string; agent: string } + >() + const sweep = new WorkerQuietSweep( + Date.now(), + (id) => { + const db = deps.getDb() + return db ? latestWorkerQuietNotice(db, id) : undefined + }, + (row, notice) => { + const candidate = candidates.get(row.dispatchId) + const db = deps.getDb() + return ( + !!db && + !!candidate && + reportWorkerQuiet(db, candidate.target, { ...row, ...candidate }, notice, deps.notify) + ) + } + ) + const run = (): void => { + try { + candidates.clear() + const db = deps.getDb() + if (!db) { + return + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the canonical column list covers the dispatch row. + const local = db.db + .prepare( + `SELECT ${DISPATCH_CONTEXT_COLUMN_LIST} FROM dispatch_contexts WHERE status IN ('pending', 'dispatched') AND capability_revoked_at IS NULL` + ) + .all() as DispatchContextRow[] + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the canonical column list covers the attachment row. + const remote = db.db + .prepare( + `SELECT ${REMOTE_DISPATCH_ATTACHMENT_COLUMN_LIST} FROM remote_dispatch_attachments WHERE state IN ('starting', 'ready', 'start_unknown')` + ) + .all() as RemoteDispatchAttachmentRow[] + type Target = + | { kind: 'local'; dispatch: DispatchContextRow } + | { kind: 'remote'; attachment: RemoteDispatchAttachmentRow } + const targets: Target[] = [ + ...local.map((dispatch): Target => ({ kind: 'local', dispatch })), + ...remote.map((attachment): Target => ({ kind: 'remote', attachment })) + ] + const observations: WorkerQuietObservation[] = [] + for (const target of targets) { + const dispatchId = + target.kind === 'local' ? target.dispatch.id : target.attachment.dispatch_id + const from = + target.kind === 'local' + ? target.dispatch.assignee_handle + : target.attachment.terminal_handle + const paneKey = + target.kind === 'local' ? target.dispatch.assignee_pane_key : target.attachment.pane_key + if (!from) { + continue + } + const openedAt = Date.parse( + `${(target.kind === 'local' + ? target.dispatch.created_at + : target.attachment.created_at + ).replace(' ', 'T')}Z` + ) + const identity = resolveStructuredWorkerIdentity(from, db) + if (identity) { + const running = structuredWorkerSession(identity) + if (running.kind !== 'here') { + continue + } + const host = getStructuredAgentSessionHost() + const progress = host?.attentionReads.workerProgress(running.sessionId) + if (!progress || host?.readStatusSummary(running.sessionId)?.status !== 'working') { + continue + } + candidates.set(dispatchId, { + target, + from, + agent: identity.agent ?? host?.sessionAgent(running.sessionId) ?? 'agent' + }) + observations.push({ dispatchId, working: true, ...progress }) + continue + } + if (!paneKey) { + continue + } + const resolved = deps.resolveTerminal(paneKey) + if ( + !resolved || + (resolved.target.kind === 'local' + ? resolved.target.dispatch.id + : resolved.target.attachment.dispatch_id) !== dispatchId + ) { + continue + } + const row = deps.store.getStatusSnapshotForPane(paneKey)[0] + const pty = deps.readPty(paneKey) + const progress = deps.store.producerProgress?.get(paneKey) + let tool: { name: string; startedAt: number } | undefined + for (const call of progress?.tools.values() ?? []) { + if (!tool || call.startedAt < tool.startedAt) { + tool = call + } + } + candidates.set(dispatchId, { + target, + from, + agent: row?.agentType ?? pty?.launchAgent ?? pty?.foregroundAgent ?? 'agent' + }) + observations.push({ + dispatchId, + turnStartedAt: row?.turnStartedAt ?? openedAt, + working: row + ? row.state === 'working' + : pty?.lastAgentStatus === 'working' && pty.lastAgentStatusObservedLive, + restoredUnconfirmed: row?.restoredUnconfirmed, + connected: pty?.connected ?? false, + connectionId: row?.connectionId, + workingSince: progress + ? undefined + : (pty?.lastAgentStatusStartedAtEpochMs ?? row?.stateStartedAt), + lastProducerEventAt: progress?.lastProducerEventAt, + tool: + tool ?? + (row?.agentType === 'claude' && row.workingMode === 'monitoring' + ? { name: 'background work', startedAt: row.stateStartedAt } + : undefined) + }) + } + sweep.sweep( + observations, + Date.now(), + targets.map((target) => + target.kind === 'local' ? target.dispatch.id : target.attachment.dispatch_id + ) + ) + } catch (error) { + console.warn('[orchestration] quiet worker sweep failed', error) + } + } + const detachResume = getRuntimeDesktopSurface().onResume?.(() => sweep.resume(Date.now())) + const timer = setInterval(run, 60_000) + timer.unref?.() + return () => { + clearInterval(timer) + detachResume?.() + } +} diff --git a/src/main/runtime/orchestration/workers/reports/worker-quiet-sweep.test.ts b/src/main/runtime/orchestration/workers/reports/worker-quiet-sweep.test.ts new file mode 100644 index 00000000000..210b1d6f0e8 --- /dev/null +++ b/src/main/runtime/orchestration/workers/reports/worker-quiet-sweep.test.ts @@ -0,0 +1,145 @@ +import { ProducerProgressStore } from '../../../../agent-hooks/server/producer-progress' +import { expect, it, vi } from 'vitest' +import { WorkerQuietSweep, type WorkerQuietObservation } from './worker-quiet-sweep' +import { reportWorkerQuiet, latestWorkerQuietNotice } from './worker-quiet-report' +import { OrchestrationDb } from '../../db/orchestration-db' +import '../../db/contract-constants' +import '../../db/messages/mailbox-routing-page' +import '../../db/dispatch-row-writer' +import '../../db/attempt-outcome-projection' +import { createRootDispatch } from '../../db/root-dispatch-test-fixture' + +it('only advises for a quiet working episode, respects tools, fallback, grace, and a single reminder', () => { + const producer = new ProducerProgressStore() + const event = { + paneKey: 'worker', + connectionId: null, + hookEventName: 'PreToolUse', + toolUseId: 'exec-2', + payload: { + state: 'working' as const, + prompt: '', + agentType: 'codex' as const, + toolName: 'Bash' + } + } + producer.observe({ ...event, toolAgentId: 'child-a' }, 0) + producer.observe({ ...event, toolAgentId: 'child-b' }, 0) + producer.observe({ ...event, toolAgentId: 'child-a', hookEventName: 'PostToolUseFailure' }, 1) + producer.observe({ ...event, isReplay: true }, 99) + expect(producer.get('worker')?.lastProducerEventAt).toBe(1) + expect([...producer.get('worker')!.tools.values()]).toEqual([{ name: 'Bash', startedAt: 0 }]) + producer.observe({ ...event, toolAgentId: 'child-b', hookEventName: 'PostToolUse' }, 2) + expect([...producer.get('worker')!.tools.values()]).toEqual([]) + const sent: { id: string; ordinal: number; at: number }[] = [] + const sweep = new WorkerQuietSweep( + 0, + () => undefined, + (row, notice) => { + sent.push({ id: row.dispatchId, ordinal: notice.ordinal, at: notice.observedAt }) + return true + } + ) + let rows: WorkerQuietObservation[] = [ + { dispatchId: 'quiet', turnStartedAt: 0, working: true, lastProducerEventAt: 0 }, + { + dispatchId: 'tool', + turnStartedAt: 0, + working: true, + lastProducerEventAt: 0, + tool: { name: 'Bash', startedAt: 0 } + }, + { dispatchId: 'fallback', turnStartedAt: 0, working: true }, + { dispatchId: 'restored', turnStartedAt: 0, working: true, restoredUnconfirmed: true }, + { dispatchId: 'idle', turnStartedAt: 0, working: false, lastProducerEventAt: 0 } + ] + for (let now = 0; now <= 3_600_000; now += 60_000) { + sweep.sweep(rows, now) + } + expect(sent).toEqual([ + { id: 'quiet', ordinal: 1, at: 900_000 }, + { id: 'quiet', ordinal: 2, at: 2_700_000 }, + { id: 'tool', ordinal: 1, at: 3_600_000 }, + { id: 'fallback', ordinal: 1, at: 3_600_000 } + ]) + rows = [{ dispatchId: 'quiet', turnStartedAt: 0, working: true, lastProducerEventAt: 3_600_000 }] + for (let now = 3_660_000; now <= 4_500_000; now += 60_000) { + sweep.sweep(rows, now) + } + expect(sent.at(-1)).toEqual({ id: 'quiet', ordinal: 3, at: 4_500_000 }) + sweep.resume(4_560_000) + sweep.sweep(rows, 4_560_000) + // A laptop sleep and a clock rollback both restart grace, never count as silence. + sweep.sweep(rows, 10_000_000) + sweep.sweep(rows, 1_000_000) + expect(sent).toHaveLength(5) + rows = [{ ...rows[0]!, connectionId: 'reconnected' }] + for (let now = 1_060_000; now <= 1_900_000; now += 60_000) { + sweep.sweep(rows, now) + } + expect(sent).toHaveLength(5) + rows = [{ ...rows[0]!, lastProducerEventAt: 1_900_000 }] + sweep.sweep(rows, 1_960_000) + for (let now = 2_020_000; now <= 2_800_000; now += 60_000) { + sweep.sweep(rows, now) + } + expect(sent.at(-1)).toEqual({ id: 'quiet', ordinal: 4, at: 2_800_000 }) +}) + +it('relays status/normal with deterministic ids and retains the turn ordinal across restart', () => { + const db = new OrchestrationDb(':memory:') + try { + const run = db.createRun({ + objective: 'quiet notices', + coordinatorHandle: 'term_coordinator', + coordinatorPaneKey: null + }) + const task = db.createTask({ spec: 'do work', runId: run.id }) + const dispatch = createRootDispatch(db, task.id, 'term_worker') + const target = { + kind: 'remote' as const, + attachment: { dispatch_id: dispatch.id, task_id: task.id } + } + const row = { + dispatchId: dispatch.id, + turnStartedAt: 0, + working: true, + lastProducerEventAt: 0, + from: 'term_worker', + agent: 'Codex' + } + const notice = { + dispatchId: dispatch.id, + turnStartedAt: 0, + ordinal: 1, + observedAt: 900_000, + intervalMs: 900_000 + } + expect(reportWorkerQuiet(db, target, row, notice, vi.fn())).toBe(true) + expect(reportWorkerQuiet(db, target, row, notice, vi.fn())).toBe(true) + expect(reportWorkerQuiet(db, { kind: 'local', dispatch }, row, notice, vi.fn())).toBe(true) + const local = db.getUnreadRunMailbox(run.id, 100, ['status']) + expect(local).toHaveLength(1) + expect(local[0]).toMatchObject({ type: 'status', priority: 'normal' }) + const relay = db.listPendingFederationRelay(dispatch.id, 'to_home') + expect(relay).toHaveLength(1) + expect(JSON.parse(relay[0]!.payload)).toMatchObject({ type: 'status', priority: 'normal' }) + expect(JSON.parse(JSON.parse(relay[0]!.payload).payload).stopReason).toBeUndefined() + expect(latestWorkerQuietNotice(db, dispatch.id)?.ordinal).toBe(1) + const sent: number[] = [] + const restarted = new WorkerQuietSweep( + 1_000_000, + (id) => latestWorkerQuietNotice(db, id), + (_row, next) => { + sent.push(next.ordinal) + return true + } + ) + for (let now = 1_000_000; now <= 5_000_000; now += 60_000) { + restarted.sweep([row], now) + } + expect(sent).toEqual([2]) + } finally { + db.close() + } +}) diff --git a/src/main/runtime/orchestration/workers/reports/worker-quiet-sweep.ts b/src/main/runtime/orchestration/workers/reports/worker-quiet-sweep.ts new file mode 100644 index 00000000000..1dfbf466770 --- /dev/null +++ b/src/main/runtime/orchestration/workers/reports/worker-quiet-sweep.ts @@ -0,0 +1,160 @@ +export type WorkerQuietObservation = { + dispatchId: string + turnStartedAt: number + working: boolean + restoredUnconfirmed?: boolean + connected?: boolean + connectionId?: string | null + workingSince?: number + lastProducerEventAt?: number + tool?: { name: string; startedAt: number } +} + +export type QuietNotice = { + dispatchId: string + turnStartedAt: number + ordinal: number + observedAt: number + intervalMs: number +} + +type Episode = { + turn: number + progress?: number + connected: boolean + connectionId?: string | null + grace: number + firstNoticeAt?: number + notices: number + ordinal: number + previous?: QuietNotice +} + +const SWEEP_MS = 60_000 + +/** Observations never authorize an action on the worker; only a rate-limited advisory. */ +export class WorkerQuietSweep { + private readonly episodes = new Map() + private readonly history = new Map() + private readonly recovered = new Set() + private lastSweepAt: number + private resumedAt: number + + constructor( + private readonly startedAt: number, + private readonly latest: (dispatchId: string) => QuietNotice | undefined, + private readonly send: (observation: WorkerQuietObservation, notice: QuietNotice) => boolean + ) { + this.lastSweepAt = startedAt + this.resumedAt = startedAt + } + + resume(now: number): void { + this.resumedAt = now + } + + sweep(observations: WorkerQuietObservation[], now: number, openDispatchIds?: string[]): void { + const gap = now - this.lastSweepAt + this.lastSweepAt = now + if (gap < 0 || gap > SWEEP_MS * 3) { + this.resume(now) + } + const observed = new Set(observations.map((row) => row.dispatchId)) + const open = openDispatchIds ? new Set(openDispatchIds) : observed + for (const id of this.episodes.keys()) { + if (!observed.has(id)) { + this.episodes.delete(id) + } + } + for (const id of this.history.keys()) { + if (!open.has(id)) { + this.history.delete(id) + this.recovered.delete(id) + } + } + for (const row of observations) { + if (!row.working || row.restoredUnconfirmed) { + this.episodes.delete(row.dispatchId) + continue + } + if (!this.history.has(row.dispatchId)) { + const latest = this.latest(row.dispatchId) + this.history.set(row.dispatchId, latest) + if (latest) { + this.recovered.add(row.dispatchId) + } + } + let episode = this.episodes.get(row.dispatchId) + const connected = row.connected !== false + if (!episode || episode.turn !== row.turnStartedAt) { + const previous = this.history.get(row.dispatchId) + episode = { + turn: row.turnStartedAt, + progress: row.lastProducerEventAt ?? row.workingSince, + connectionId: row.connectionId, + connected, + grace: row.lastProducerEventAt === undefined ? now : this.startedAt, + notices: + this.recovered.has(row.dispatchId) && previous?.turnStartedAt === row.turnStartedAt + ? 1 + : 0, + ordinal: previous?.turnStartedAt === row.turnStartedAt ? previous.ordinal : 0, + previous: + this.recovered.has(row.dispatchId) && previous?.turnStartedAt === row.turnStartedAt + ? previous + : undefined + } + this.episodes.set(row.dispatchId, episode) + } + if (episode.progress !== (row.lastProducerEventAt ?? row.workingSince)) { + episode.progress = row.lastProducerEventAt ?? row.workingSince + episode.notices = 0 + episode.firstNoticeAt = undefined + // A new observed episode can notify normally, even if an older episode notified recently. + episode.previous = undefined + this.recovered.delete(row.dispatchId) + } + if ((!episode.connected && connected) || episode.connectionId !== row.connectionId) { + episode.grace = now + } + episode.connectionId = row.connectionId + episode.connected = connected + if (!connected || episode.notices >= 2) { + continue + } + const since = Math.max( + row.lastProducerEventAt ?? episode.grace, + row.turnStartedAt, + row.workingSince ?? 0, + this.startedAt, + this.resumedAt, + episode.grace + ) + const interval = row.tool || row.lastProducerEventAt === undefined ? 3_600_000 : 900_000 + if (now - since < interval) { + continue + } + if (episode.firstNoticeAt !== undefined && now - episode.firstNoticeAt < interval * 2) { + continue + } + if (episode.previous && now - episode.previous.observedAt < episode.previous.intervalMs * 2) { + continue + } + const notice: QuietNotice = { + dispatchId: row.dispatchId, + turnStartedAt: row.turnStartedAt, + ordinal: episode.ordinal + 1, + observedAt: now, + intervalMs: interval + } + if (this.send(row, notice)) { + episode.ordinal = notice.ordinal + episode.notices++ + episode.firstNoticeAt ??= now + episode.previous = undefined + this.history.set(row.dispatchId, notice) + this.recovered.delete(row.dispatchId) + } + } + } +} diff --git a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts index 21445f85287..82c51a3fc23 100644 --- a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts +++ b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts @@ -31,7 +31,7 @@ export type AgentStatusStoreView = Pick< | 'subscribeStatusFreshness' > & /** The hook server's enriched rows, which main's generated titles follow. */ - Partial> + Partial> const AGENT_FRESHNESS_DEADLINE = 'agent-freshness'