From 0dcc811e07bf0cd1dcbafb5ffd62883b58c6247a Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:09:15 +0000 Subject: [PATCH] fix(notifications): leave dispatched workers' finished turns to their coordinator (#36968) --- .../structured-attention-localization.test.ts | 1 + .../runtime/orca-runtime-agent-transitions.ts | 2 + ...red-agent-session-mobile-attention.test.ts | 25 +++++ ...ructured-agent-session-mobile-attention.ts | 17 +++- ...tured-agent-session-mobile-restore.test.ts | 1 + ...ed-agent-session-mobile-retirement.test.ts | 1 + .../runtime/terminal-agent-phone-push.test.ts | 27 ++++++ src/main/runtime/terminal-agent-phone-push.ts | 15 ++- .../workspaces/workspace-process-listing.ts | 3 + .../src/attention/agent-attention-policy.ts | 12 ++- .../structured-attention-dispatch.test.ts | 25 ++++- .../structured-attention-dispatch.ts | 7 +- .../notification-dispatch-test-harness.ts | 7 +- ...ication-dispatch-dispatched-worker.test.ts | 94 +++++++++++++++++++ .../use-notification-dispatch.ts | 26 ++++- src/shared/dispatched-worker-attention.ts | 35 +++++++ ...d-attention-headless-delivery.unit.test.ts | 1 + ...ttention-host-read-retirement.unit.test.ts | 1 + ...attention-read-retirement.test-fixture.tsx | 1 + ...red-attention-read-retirement.unit.test.ts | 1 + 20 files changed, 292 insertions(+), 10 deletions(-) create mode 100644 src/renderer/src/components/terminal-pane/use-notification-dispatch-dispatched-worker.test.ts create mode 100644 src/shared/dispatched-worker-attention.ts diff --git a/src/main/host/structured-attention-localization.test.ts b/src/main/host/structured-attention-localization.test.ts index d4962c6c331..081e0a8a898 100644 --- a/src/main/host/structured-attention-localization.test.ts +++ b/src/main/host/structured-attention-localization.test.ts @@ -48,6 +48,7 @@ function hostNotifications() { readNotificationSettings: getDefaultNotificationSettings, readWorkspaceLabels: () => ({ worktreeLabel: 'Notes' }), isWorkspaceMuted: () => false, + readOrchestration: () => undefined, dispatch: (event) => controller.dispatch(event), reconcile: (state) => controller.reconcileStructuredPromptAttention(state), now: () => 60_000 diff --git a/src/main/runtime/orca-runtime-agent-transitions.ts b/src/main/runtime/orca-runtime-agent-transitions.ts index 2211b354eea..3b9d2ed241d 100644 --- a/src/main/runtime/orca-runtime-agent-transitions.ts +++ b/src/main/runtime/orca-runtime-agent-transitions.ts @@ -44,6 +44,8 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithWin readWorkspaceLabels: (worktreeId, paneKey) => this.readTerminalAgentWorkspaceLabels(worktreeId, paneKey), isWorkspaceMuted: (worktreeId) => this.isWorkspaceNotificationMuted(worktreeId), + readOrchestration: (paneKey) => this.getAgentStatusOrchestrationContextForPaneKey(paneKey), + readTerminalTitle: (paneKey) => this.getPtyRecordForPaneKey(paneKey)?.lastOscTitle ?? null, readHookRow: (paneKey) => this.agentTransitions.latestRow(paneKey), translate: (key, fallback) => getRuntimeDesktopSurface().translateNotification?.(key, fallback) ?? fallback, diff --git a/src/main/runtime/structured-agent-session-mobile-attention.test.ts b/src/main/runtime/structured-agent-session-mobile-attention.test.ts index be2f3ee1150..30e156f98ac 100644 --- a/src/main/runtime/structured-agent-session-mobile-attention.test.ts +++ b/src/main/runtime/structured-agent-session-mobile-attention.test.ts @@ -6,6 +6,10 @@ import type { import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' import type { NotificationSettings } from '../../shared/notification-settings-types' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../shared/agent-session/view/structured-agent-session-projection' import { createStructuredAttentionMobileDelivery, @@ -75,6 +79,7 @@ function harness(overrides: Partial = {}) readNotificationSettings: () => settings(), readWorkspaceLabels: () => ({ repoLabel: 'orca', worktreeLabel: 'feature' }), isWorkspaceMuted: () => false, + readOrchestration: () => undefined, dispatch: (event) => sent.push(event), reconcile: (state) => reconciled.push(state), now: () => 42, @@ -93,6 +98,26 @@ describe('structured attention mobile delivery', () => { expect(isWorkspaceMuted).toHaveBeenCalledWith(SCOPE) }) + it('leaves a dispatched chat worker’s finished turn to its coordinator, and still sends its prompts', () => { + const readOrchestration = vi.fn(() => ({ + taskId: 'task_1', + dispatchId: 'ctx_1', + parentPaneKey: 'tab-c:leaf-c' + })) + const h = harness({ readOrchestration }) + h.delivery.deliver(completion('success'), SUMMARY) + h.delivery.deliver(completion('failure'), SUMMARY) + h.delivery.deliver(completion('success', true), SUMMARY) + // A failed turn that leaves a prompt waiting is still the person's to answer. + h.delivery.deliver(completion('failure', true), SUMMARY) + h.delivery.deliver(PROMPT, SUMMARY) + expect(h.sent.map((event) => event.agentState)).toEqual(['blocked', 'done', 'blocked']) + // The key the session's chat row carries in the host's orchestration projection. + expect(readOrchestration).toHaveBeenCalledWith( + structuredAgentSessionPaneKey(structuredAgentSessionTabId('session-1'), 'session-1') + ) + }) + it('still sends when labels cannot be read, worded generically', () => { const h = harness({ readWorkspaceLabels: () => { diff --git a/src/main/runtime/structured-agent-session-mobile-attention.ts b/src/main/runtime/structured-agent-session-mobile-attention.ts index db6a93a3565..5a0adbc1d6f 100644 --- a/src/main/runtime/structured-agent-session-mobile-attention.ts +++ b/src/main/runtime/structured-agent-session-mobile-attention.ts @@ -9,6 +9,8 @@ import { type AgentSessionAttentionEdge } from '../../shared/agent-session/agent-session-attention' import type { AgentSessionExecutionLocation } from '../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentStatusOrchestrationContext } from '../../shared/agent-status-types' +import { isCoordinatorOnlyChatNews } from '../../shared/dispatched-worker-attention' import type { NotificationDispatchRequest, NotificationSettings @@ -32,6 +34,8 @@ export type StructuredAttentionMobileDeliveryDeps = { readWorkspaceLabels: (scope: AgentSessionExecutionLocation) => StructuredAttentionWorkspaceLabels /** In-memory only, like the labels: "Notify About Hidden Workspaces" is off and the Filters hide it. */ isWorkspaceMuted: (scope: AgentSessionExecutionLocation) => boolean + /** The dispatch context the session's chat row carries, by that row's pane key. */ + readOrchestration: (paneKey: string) => AgentStatusOrchestrationContext | undefined dispatch: (event: MobileNotificationDispatchEvent) => void /** Withdraws a notification this host delivered; a no-op for one it never sent. */ reconcile: (state: StructuredAttentionState) => void @@ -85,7 +89,15 @@ export function createStructuredAttentionMobileDelivery( return } const { scope, sessionId } = edge.type === 'prompt' ? edge.prompt : edge.completion - if (deps.isWorkspaceMuted(scope)) { + // The host has no window tab id; the phone matches this session-derived key to the chat. + const paneKey = structuredAgentSessionPaneKey( + structuredAgentSessionTabId(sessionId), + sessionId + ) + if ( + deps.isWorkspaceMuted(scope) || + isCoordinatorOnlyChatNews(edge, news.agentState, () => deps.readOrchestration(paneKey)) + ) { return } const settings = deps.readNotificationSettings()! @@ -117,8 +129,7 @@ export function createStructuredAttentionMobileDelivery( title, body, worktreeId: scope.workspaceId, - // The host has no window tab id; the phone matches this session-derived key to the chat. - paneKey: structuredAgentSessionPaneKey(structuredAgentSessionTabId(sessionId), sessionId), + paneKey, notificationId: attentionKey, attentionKey, ...(structuredAttentionOrigin(edge) diff --git a/src/main/runtime/structured-agent-session-mobile-restore.test.ts b/src/main/runtime/structured-agent-session-mobile-restore.test.ts index d8ec3a3cd2e..093caffa86f 100644 --- a/src/main/runtime/structured-agent-session-mobile-restore.test.ts +++ b/src/main/runtime/structured-agent-session-mobile-restore.test.ts @@ -39,6 +39,7 @@ function wire(host: StructuredAgentSessionHost, controller: RuntimeMobileNotific }), readWorkspaceLabels: () => ({}), isWorkspaceMuted: () => false, + readOrchestration: () => undefined, dispatch: (event) => controller.dispatch(event), reconcile: (state) => controller.reconcileStructuredPromptAttention(state), now: () => NOW diff --git a/src/main/runtime/structured-agent-session-mobile-retirement.test.ts b/src/main/runtime/structured-agent-session-mobile-retirement.test.ts index 41031f95235..ee81aac7ce3 100644 --- a/src/main/runtime/structured-agent-session-mobile-retirement.test.ts +++ b/src/main/runtime/structured-agent-session-mobile-retirement.test.ts @@ -97,6 +97,7 @@ describe('host prompt delivery and retirement', () => { }), readWorkspaceLabels: () => ({}), isWorkspaceMuted: () => false, + readOrchestration: () => undefined, dispatch: (event) => controller.dispatch(event), reconcile: (state) => controller.reconcileStructuredPromptAttention(state), now: () => 42 diff --git a/src/main/runtime/terminal-agent-phone-push.test.ts b/src/main/runtime/terminal-agent-phone-push.test.ts index 0ed95930acf..fd787d8128f 100644 --- a/src/main/runtime/terminal-agent-phone-push.test.ts +++ b/src/main/runtime/terminal-agent-phone-push.test.ts @@ -47,6 +47,8 @@ function harness( settings?: Partial muted?: boolean hookRow?: AgentStatusIpcPayload | null + dispatched?: boolean + title?: string } = {} ) { const clock = { now: 10_000 } @@ -73,6 +75,11 @@ function harness( }), readWorkspaceLabels: () => ({ repoLabel: 'orca', worktreeLabel: 'feature' }), isWorkspaceMuted: () => state.muted, + readOrchestration: () => + options.dispatched + ? { taskId: 'task_1', dispatchId: 'ctx_1', parentTerminalHandle: 'term_coordinator' } + : undefined, + readTerminalTitle: () => options.title ?? null, readHookRow: () => state.hookRow, dispatch: (event) => sent.push(event), setTimer: (run, delayMs) => { @@ -231,6 +238,26 @@ describe('TerminalAgentPhonePush', () => { expect(sent).toEqual([]) }) + it('leaves a dispatched worker’s finish to its coordinator, and still pushes its prompt', () => { + const { push, sent, state, advance, finish } = harness({ dispatched: true }) + finish() + advance(AGENT_DONE_QUIET_MS) + expect(sent).toEqual([]) + state.hookRow = row({ state: 'waiting', stateStartedAt: 6_000 }) + push.observe(moved('needs-input', 'needs-you')) + expect(sent.map((event) => event.agentState)).toEqual(['waiting']) + }) + + it('pushes a dispatched worker’s finish whose title still waits for approval, as the window does', () => { + const { sent, advance, finish } = harness({ + dispatched: true, + title: 'Codex - waiting for approval' + }) + finish() + advance(AGENT_DONE_QUIET_MS) + expect(sent).toHaveLength(1) + }) + it('marks the push not desktop-allowed when agent notifications are off', () => { const { sent, finish } = harness({ settings: { agentTaskComplete: false } }) finish() diff --git a/src/main/runtime/terminal-agent-phone-push.ts b/src/main/runtime/terminal-agent-phone-push.ts index 0f0c175bb95..b30fd13285b 100644 --- a/src/main/runtime/terminal-agent-phone-push.ts +++ b/src/main/runtime/terminal-agent-phone-push.ts @@ -3,6 +3,8 @@ import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' import { agentMainAgentVerdict } from '../../shared/agent-main-agent-verdict' import { buildAgentNotificationId } from '../../shared/agent-notification-id' import type { AgentStatusIpcPayload } from '../../shared/agent-status-ipc-payload' +import type { AgentStatusOrchestrationContext } from '../../shared/agent-status-types' +import { isCoordinatorOnlyNews, withApprovalTitle } from '../../shared/dispatched-worker-attention' import { reserveNotificationCooldown } from '../../shared/notification-burst-cooldown' import type { NotificationDispatchRequest, @@ -26,6 +28,8 @@ export type TerminalAgentPhonePushDeps = { /** In-memory only, as the window's: the alert must not wait on a lookup. */ readWorkspaceLabels: (worktreeId: string, paneKey: string) => TerminalAgentWorkspaceLabels isWorkspaceMuted: (worktreeId: string) => boolean + readOrchestration: (paneKey: string) => AgentStatusOrchestrationContext | undefined + readTerminalTitle: (paneKey: string) => string | null readHookRow: (paneKey: string) => AgentStatusIpcPayload | null translate?: (key: string, fallback: string) => string dispatch: (event: MobileNotificationDispatchEvent) => void @@ -93,7 +97,16 @@ export class TerminalAgentPhonePush { private send(news: PaneNews): void { // Recheck window ownership at delivery to avoid duplicating a newly opened window's push. - if (this.deps.hasWindow() || this.deps.isWorkspaceMuted(news.worktreeId)) { + const { agentState, paneKey } = news.event + if ( + this.deps.hasWindow() || + this.deps.isWorkspaceMuted(news.worktreeId) || + (paneKey && + isCoordinatorOnlyNews( + withApprovalTitle(agentState, this.deps.readTerminalTitle(paneKey)), + () => this.deps.readOrchestration(paneKey) + )) + ) { return } const settings = this.deps.readNotificationSettings() diff --git a/src/main/runtime/workspaces/workspace-process-listing.ts b/src/main/runtime/workspaces/workspace-process-listing.ts index 6580302e87e..b6402c525fc 100644 --- a/src/main/runtime/workspaces/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/workspace-process-listing.ts @@ -302,6 +302,9 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends OrcaRuntimeWithWorktr readWorkspaceLabels: (scope) => readStructuredAttentionWorkspaceLabels(this.requireStore(), scope), isWorkspaceMuted: (scope) => this.isWorkspaceNotificationMuted(scope.workspaceId), + // The same contexts the session's chat row carries. + readOrchestration: (paneKey) => + this.agentOrchestrationProjection.buildByPaneKey()?.[paneKey], dispatch: (event) => this.mobileNotifications.dispatch(event), reconcile: (state) => this.mobileNotifications.reconcileStructuredPromptAttention(state), now: () => Date.now() diff --git a/src/renderer/src/attention/agent-attention-policy.ts b/src/renderer/src/attention/agent-attention-policy.ts index 92ca63c0284..31397cb974c 100644 --- a/src/renderer/src/attention/agent-attention-policy.ts +++ b/src/renderer/src/attention/agent-attention-policy.ts @@ -11,6 +11,8 @@ export type AgentAttentionRequest = { settlesTurn: boolean /** Out-of-band proof the subject just produced work, used when no live session is visible. */ hasFreshActivityEvidence: boolean + /** A dispatched worker finished: its coordinator gets the result, so the person gets nothing. */ + coordinatorOnlyNews?: boolean } export type AgentAttentionUnreadWrite = { @@ -30,7 +32,12 @@ export type AgentAttentionDeliveryRequest = { export type AgentAttentionDecision = | { admitted: false - cause: 'muted-workspace' | 'no-live-session' | 'unknown-surface' | 'superseded-surface' + cause: + | 'muted-workspace' + | 'coordinator-only-news' + | 'no-live-session' + | 'unknown-surface' + | 'superseded-surface' } | { admitted: true @@ -54,6 +61,9 @@ export function resolveAgentAttention( if (surface.isWorkspaceMuted(workspaceId)) { return { admitted: false, cause: 'muted-workspace' } } + if (request.coordinatorOnlyNews) { + return { admitted: false, cause: 'coordinator-only-news' } + } const subjectKey = request.subject.surfaceKey ?? null const hasLiveSession = surface.hasLiveSession(request.subject) if (!hasLiveSession && !request.hasFreshActivityEvidence) { diff --git a/src/renderer/src/components/native-chat/structured-attention-dispatch.test.ts b/src/renderer/src/components/native-chat/structured-attention-dispatch.test.ts index 998c8b18e3c..a54f61de5ff 100644 --- a/src/renderer/src/components/native-chat/structured-attention-dispatch.test.ts +++ b/src/renderer/src/components/native-chat/structured-attention-dispatch.test.ts @@ -7,7 +7,10 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { AgentSessionTurnCompletion } from '../../../../shared/agent-session/view/agent-session-turn-completion-wire' import { agentSessionAttentionKey } from '../../../../shared/agent-session/agent-session-attention' import { agentJournalSubmissionKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import { structuredAgentSessionPaneKey } from '../../../../shared/agent-session/view/structured-agent-session-projection' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../../shared/agent-session/view/structured-agent-session-projection' import { createTestStore, makeTabGroup, @@ -117,6 +120,7 @@ function seed(overrides?: { unreadTerminalTabs: {}, unreadTerminalPanes: {}, unreadAgentCompletionPanes: {}, + runtimeAgentOrchestrationByPaneKey: {}, settings: settingsWith(overrides?.groupAttention ?? true), floatingWorkspacePanelOpen: overrides?.floatingPanelOpen ?? false, // Persistence is not what this test is about; the folder path would otherwise call out to IPC. @@ -332,6 +336,25 @@ describe('dispatchStructuredTurnCompletionAttention', () => { expect(onlyDispatch()).toMatchObject({ agentState: 'done' }) }) + it('leaves a dispatched chat worker’s finished turn to its coordinator, but still calls the user to its prompt', () => { + store.setState({ + runtimeAgentOrchestrationByPaneKey: { + [structuredAgentSessionPaneKey(structuredAgentSessionTabId(SESSION), SESSION)]: { + taskId: 'task_1', + dispatchId: 'ctx_1', + parentPaneKey: 'tab-c:leaf-c' + } + } + }) + dispatchStructuredTurnCompletionAttention(structuredTab(), completion()) + expect(indicators()).toEqual(NOTHING_LIT) + expect(dispatched).toEqual([]) + + dispatchStructuredTurnCompletionAttention(structuredTab(), completion({ awaitingUser: true })) + expect(indicators().paneDot).toBe('agent-completion') + expect(onlyDispatch()).toMatchObject({ agentState: 'blocked' }) + }) + it('says done even while the status row still reads working, because the host settled the turn', () => { // Completion can outrun status projection; row state would wrongly announce settled work as still working. const paneKey = structuredAgentSessionPaneKey(CHAT_TAB, SESSION) diff --git a/src/renderer/src/components/native-chat/structured-attention-dispatch.ts b/src/renderer/src/components/native-chat/structured-attention-dispatch.ts index 53eff834d6c..961a15fe540 100644 --- a/src/renderer/src/components/native-chat/structured-attention-dispatch.ts +++ b/src/renderer/src/components/native-chat/structured-attention-dispatch.ts @@ -24,6 +24,8 @@ import { readAgentAttentionNotificationSound } from '@/attention/agent-attention-notification-delivery' import { useAppStore } from '@/store' +import { canonicalOrchestrationForRow } from '@/runtime/visible-agent-orchestration' +import { isCoordinatorOnlyChatNews } from '../../../../shared/dispatched-worker-attention' import { getNotificationWorkspaceLabels } from '../terminal-pane/terminal-notification-state' import { createStructuredAttentionSurface } from './structured-attention-surface' import type { StructuredTab } from './structured-agent-session-tabs' @@ -80,7 +82,10 @@ function dispatchStructuredAttention( // A prompt earns unread like a settled turn, as the hook lane's blocked row does. settlesTurn: true, // Host journal edges prove fresh activity even without a rendered transcript; still require current tab ownership. - hasFreshActivityEvidence: true + hasFreshActivityEvidence: true, + coordinatorOnlyNews: isCoordinatorOnlyChatNews(edge, news.agentState, () => + canonicalOrchestrationForRow(state, paneKey) + ) }, createStructuredAttentionSurface(state) ) diff --git a/src/renderer/src/components/terminal-pane/notification-dispatch-test-harness.ts b/src/renderer/src/components/terminal-pane/notification-dispatch-test-harness.ts index 5069a057cb3..4f78578a46e 100644 --- a/src/renderer/src/components/terminal-pane/notification-dispatch-test-harness.ts +++ b/src/renderer/src/components/terminal-pane/notification-dispatch-test-harness.ts @@ -1,6 +1,9 @@ import { vi } from 'vitest' import type { Mock } from 'vitest' -import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import type { + AgentStatusEntry, + AgentStatusOrchestrationContext +} from '../../../../shared/agent-status-types' import type { TerminalLayoutSnapshot } from '../../../../shared/terminal-tab-types' import type { Tab, TabGroup } from '../../../../shared/tab-types' @@ -32,6 +35,7 @@ export type NotificationDispatchMockState = { { launchConfig: { agentArgs: string }; identity: { agentType?: string } } > agentStatusByPaneKey: Record + runtimeAgentOrchestrationByPaneKey: Record worktreesByRepo: Record< string, { @@ -101,6 +105,7 @@ function buildNotificationDispatchMockState(): NotificationDispatchMockState { retainedAgentsByPaneKey: {}, agentLaunchConfigByPaneKey: {}, agentStatusByPaneKey: { [PANE_KEY]: makeAgentStatus(PANE_KEY) }, + runtimeAgentOrchestrationByPaneKey: {}, worktreesByRepo: { repo1: [ { id: 'wt-primary', repoId: 'repo1', displayName: 'master', branch: 'master' }, diff --git a/src/renderer/src/components/terminal-pane/use-notification-dispatch-dispatched-worker.test.ts b/src/renderer/src/components/terminal-pane/use-notification-dispatch-dispatched-worker.test.ts new file mode 100644 index 00000000000..b87b2a058eb --- /dev/null +++ b/src/renderer/src/components/terminal-pane/use-notification-dispatch-dispatched-worker.test.ts @@ -0,0 +1,94 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { setPresenceGated } from '@/hooks/agent-auto-ack-presence' +import { dispatchTerminalNotification } from './use-notification-dispatch' +import { + PANE_KEY, + makeAgentStatus, + resetNotificationDispatchMockState, + type NotificationDispatchMockState +} from './notification-dispatch-test-harness' + +const NOW = 1_800_000_000_000 +const paneKey = PANE_KEY + +beforeEach(() => { + vi.spyOn(Date, 'now').mockReturnValue(NOW) + setPresenceGated(false) +}) +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + setPresenceGated(true) +}) + +vi.mock('@/store', async () => { + const harness = await import('./notification-dispatch-test-harness') + return harness.createNotificationDispatchStoreModuleMock() +}) + +vi.mock('@/lib/desktop-notification-sound', async () => { + const harness = await import('./notification-dispatch-test-harness') + return harness.createDesktopNotificationSoundModuleMock() +}) + +let mockState: NotificationDispatchMockState + +describe('dispatchTerminalNotification for a dispatched worker', () => { + beforeEach(() => { + mockState = resetNotificationDispatchMockState() + mockState.runtimeAgentOrchestrationByPaneKey[paneKey] = { + taskId: 'task_1', + dispatchId: 'ctx_1', + parentPaneKey: 'tab-c:leaf-c' + } + }) + + it('leaves its hook-proven finished turn to its coordinator', () => { + dispatchTerminalNotification('wt-primary', { + source: 'agent-task-complete', + terminalTitle: 'codex', + paneKey + }) + expect(mockState.markAgentAttentionUnread).not.toHaveBeenCalled() + expect(window.api.notifications.dispatch).not.toHaveBeenCalled() + }) + + // Each of these stops either needs the person or reported to no one. + it.each([ + { + stop: 'a hook row waiting on a prompt', + row: () => makeAgentStatus(paneKey, { state: 'waiting', stateStartedAt: NOW + 1 }), + title: 'codex', + fromSnapshot: true + }, + // The fresh `done` row is the previous turn's; the approval title is this one's. + { + stop: 'a title waiting for approval', + row: undefined, + title: 'Codex - waiting for approval' + }, + { stop: 'a hookless title-only stop', row: null, title: 'codex' }, + { + stop: 'an agent that exited mid-turn', + row: () => makeAgentStatus(paneKey, { state: 'working' }), + title: 'claude', + exited: true + } + ])('still calls the user to $stop', ({ row, title, fromSnapshot, exited }) => { + const entry = row === null ? null : row?.() + if (entry === null) { + delete mockState.agentStatusByPaneKey[paneKey] + } else if (entry) { + mockState.agentStatusByPaneKey[paneKey] = entry + } + dispatchTerminalNotification('wt-primary', { + source: 'agent-task-complete', + terminalTitle: title, + paneKey, + ...(fromSnapshot && entry ? { agentStatusSnapshot: entry } : {}), + ...(exited ? { agentCompletionSource: 'process-exit' as const } : {}) + }) + expect(mockState.markAgentAttentionUnread).toHaveBeenCalled() + expect(window.api.notifications.dispatch).toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts b/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts index a915e20cbd8..bb4b8c5eb75 100644 --- a/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts +++ b/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts @@ -14,8 +14,14 @@ import { agentMainAgentVerdict } from '../../../../shared/agent-main-agent-verdi import { shareCompatibleTitleIdentityGroup } from '../../../../shared/agent-title-owner' import { isFreshNonDoneAgentStatus, - type AgentStatusEntry + type AgentStatusEntry, + type AgentStatusState } from '../../../../shared/agent-status-types' +import { + isCoordinatorOnlyNews, + withApprovalTitle +} from '../../../../shared/dispatched-worker-attention' +import { canonicalOrchestrationForRow } from '@/runtime/visible-agent-orchestration' import { isSupersededAgentCompletionSnapshot } from './agent-completion-snapshot-staleness' import { isAutoApprovedAntigravityPermission } from './antigravity-auto-approved-permission' import type { @@ -37,6 +43,15 @@ import { const AGENT_NOTIFICATION_SNAPSHOT_MAX_AGE_MS = 10_000 +/** Only a hook row proves a finish its coordinator hears about; a title waiting for approval outranks one. */ +function completionTurnState( + event: TerminalNotificationEvent, + agentStatus: Pick | undefined +): AgentStatusState | undefined { + // A title-only stop, or an agent that died mid-turn, reported to no one, so the person hears it. + return withApprovalTitle(agentStatus?.state, event.terminalTitle) +} + function agentSnapshotMatchesExplicitTitle( snapshot: { agentType?: string | null } | undefined, explicitTitleAgentType: string | null @@ -127,7 +142,14 @@ export function dispatchTerminalNotification( reason: event.source === 'agent-task-complete' ? 'agent-completion' : 'terminal-bell', settlesTurn: event.source === 'agent-task-complete', // Fresh accepted hooks can arrive before inactive-worktree PTY hydration; title/BEL-only completion still requires live surface evidence. - hasFreshActivityEvidence: Boolean(agentStatus) + hasFreshActivityEvidence: Boolean(agentStatus), + coordinatorOnlyNews: + event.source === 'agent-task-complete' && + isCoordinatorOnlyNews(completionTurnState(event, agentStatus), () => + event.paneKey === undefined + ? undefined + : canonicalOrchestrationForRow(state, event.paneKey) + ) }, createTerminalAttentionSurface(state) ) diff --git a/src/shared/dispatched-worker-attention.ts b/src/shared/dispatched-worker-attention.ts new file mode 100644 index 00000000000..fa5667a99e3 --- /dev/null +++ b/src/shared/dispatched-worker-attention.ts @@ -0,0 +1,35 @@ +import type { AgentSessionAttentionEdge } from './agent-session/agent-session-attention' +import { detectAgentStatusFromTitle } from './agent-detection' +import type { AgentStatusOrchestrationContext, AgentStatusState } from './agent-status-types' + +type ReadOrchestration = () => AgentStatusOrchestrationContext | undefined + +/** A dispatched worker's finished turn is news for the agent it reports to; only a stop that needs the person (a prompt) reaches them. A context with no parent (a coordinator's self-dispatch) is the person's own agent. */ +export function isCoordinatorOnlyNews( + agentState: AgentStatusState | undefined, + readOrchestration: ReadOrchestration +): boolean { + if (agentState !== 'done') { + return false + } + const orchestration = readOrchestration() + return Boolean(orchestration?.parentPaneKey || orchestration?.parentTerminalHandle) +} + +/** The same rule for a chat edge: a failed turn that leaves a prompt waiting still needs the person. */ +export function isCoordinatorOnlyChatNews( + edge: AgentSessionAttentionEdge, + agentState: AgentStatusState, + readOrchestration: ReadOrchestration +): boolean { + const leavesPrompt = edge.type === 'completion' && edge.completion.awaitingUser === true + return !leavesPrompt && isCoordinatorOnlyNews(agentState, readOrchestration) +} + +/** A title waiting for approval outranks the hook row's state, whatever the hooks last said. */ +export function withApprovalTitle( + agentState: State, + title: string | null | undefined +): State | 'blocked' { + return title && detectAgentStatusFromTitle(title) === 'permission' ? 'blocked' : agentState +} diff --git a/tests/e2e/structured-attention-headless-delivery.unit.test.ts b/tests/e2e/structured-attention-headless-delivery.unit.test.ts index 9a4ee6182cc..0348873fc63 100644 --- a/tests/e2e/structured-attention-headless-delivery.unit.test.ts +++ b/tests/e2e/structured-attention-headless-delivery.unit.test.ts @@ -25,6 +25,7 @@ it('loads and delivers actual host notifications in plain Node without Electron readNotificationSettings: getDefaultNotificationSettings, readWorkspaceLabels: () => ({worktreeLabel:'Notes'}), isWorkspaceMuted: () => false, + readOrchestration: () => undefined, dispatch: event => controller.dispatch(event), reconcile: state => controller.reconcileStructuredPromptAttention(state), now: () => 60_000 diff --git a/tests/e2e/structured-attention-host-read-retirement.unit.test.ts b/tests/e2e/structured-attention-host-read-retirement.unit.test.ts index 4722485ab8d..d9a412eebf9 100644 --- a/tests/e2e/structured-attention-host-read-retirement.unit.test.ts +++ b/tests/e2e/structured-attention-host-read-retirement.unit.test.ts @@ -95,6 +95,7 @@ function attentionPath(directory: string) { }), readWorkspaceLabels: () => ({}), isWorkspaceMuted: () => false, + readOrchestration: () => undefined, dispatch: (event) => controller.dispatch(event), reconcile: (state) => controller.reconcileStructuredPromptAttention(state), now: () => 42 diff --git a/tests/e2e/structured-attention-read-retirement.test-fixture.tsx b/tests/e2e/structured-attention-read-retirement.test-fixture.tsx index 4c80347e8ef..71f0a3ec1ca 100644 --- a/tests/e2e/structured-attention-read-retirement.test-fixture.tsx +++ b/tests/e2e/structured-attention-read-retirement.test-fixture.tsx @@ -211,6 +211,7 @@ beforeEach(() => { readNotificationSettings: () => ({ ...NOTIFICATION_SETTINGS, suppressWhenFocused: false }), readWorkspaceLabels: () => ({}), isWorkspaceMuted: () => false, + readOrchestration: () => undefined, dispatch: (event) => controller.dispatch(event), reconcile: (state) => controller.reconcileStructuredPromptAttention(state), now: () => 42 diff --git a/tests/e2e/structured-attention-read-retirement.unit.test.ts b/tests/e2e/structured-attention-read-retirement.unit.test.ts index a1bc61c992e..18ce71c3f61 100644 --- a/tests/e2e/structured-attention-read-retirement.unit.test.ts +++ b/tests/e2e/structured-attention-read-retirement.unit.test.ts @@ -185,6 +185,7 @@ describe('Explicit desktop read acknowledgements', () => { readNotificationSettings: () => ({ ...NOTIFICATION_SETTINGS, suppressWhenFocused: false }), readWorkspaceLabels: () => ({}), isWorkspaceMuted: () => false, + readOrchestration: () => undefined, dispatch: (event) => fixture.controller.dispatch(event), reconcile: (state) => fixture.controller.reconcileStructuredPromptAttention(state), now: () => 42