From e3ac1f8b83de610ab774f6e44a5aba7ce9fd3c67 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 13 Sep 2026 16:54:48 -0700 Subject: [PATCH 1/2] refactor(attention): move the agent attention boundary off terminal panes The completion-attention pipeline asked PTY questions inline, so a non-terminal agent surface was structurally excluded from unread, delivery and acknowledgement. Extract a provider-neutral policy under `src/renderer/src/attention/` that reaches every surface fact through an adapter, and move the PTY-shaped predicates (`hasLivePtyForNotification`, `isCurrentLivePaneKey`, `isCurrentKnownPaneKey`, `isVisibleForegroundPaneKey`, plus the leaf/foreground resolution the auto-ack scan did inline) into `terminal-attention-surface.ts`, now their only call site. Unread markers carry the reason that wrote them (`agent-completion`, `terminal-bell`, `manual-mark-unread`, `legacy`); an unclassified boolean still on live state reads as `legacy` rather than being guessed or migrated. Main's `notifications:dispatch` closure becomes a delivery service with injected collaborators; the IPC handler is a thin adapter. Behaviour is unchanged: unread is still written before main's desktop gate, the tray dot before the cooldown/focus gates, and mobile fan-out before the desktop early returns. --- src/main/ipc/notifications.ts | 107 ++---- .../notification-delivery-service.test.ts | 163 +++++++++ .../notification-delivery-service.ts | 148 ++++++++ .../agent-attention-acknowledgement.ts | 151 ++++++++ .../src/attention/agent-attention-contract.ts | 85 +++++ .../attention/agent-attention-policy.test.ts | 181 ++++++++++ .../src/attention/agent-attention-policy.ts | 143 ++++++++ .../terminal-tab-activity-status.test.ts | 2 +- .../tab-bar/terminal-tab-activity-status.ts | 11 +- .../notification-dispatch-test-harness.ts | 150 ++++++++ .../parked-terminal-byte-watcher.test.ts | 6 +- .../parked-terminal-byte-watcher.ts | 4 +- ...n-hook-completion-bell-arbitration.test.ts | 5 +- ...y-connection-hook-idle-arbitration.test.ts | 4 +- ...nection-main-side-effect-authority.test.ts | 2 +- ...ection-runtime-owner-spawn-routing.test.ts | 9 +- .../terminal-pane/pty-connection-types.ts | 5 +- .../pane-pty-visibility-bind.ts | 4 +- .../terminal-attention-surface.test.ts | 151 ++++++++ .../terminal-attention-surface.ts | 94 +++++ .../terminal-pane-lifecycle-types.ts | 5 +- .../use-notification-dispatch.test.ts | 257 +++++--------- .../use-notification-dispatch.ts | 149 ++++---- .../worktree-jump-palette-recent-inclusion.ts | 5 +- .../hooks/useAutoAckViewedAgent.away.test.ts | 17 +- .../useAutoAckViewedAgent.clock-skew.test.ts | 2 +- ...eAutoAckViewedAgent.floating-panel.test.ts | 6 +- .../src/hooks/useAutoAckViewedAgent.test.ts | 332 ++++++++++-------- .../src/hooks/useAutoAckViewedAgent.ts | 295 ++++------------ src/renderer/src/lib/unread-badge-count.ts | 3 +- .../slices/agent-status-ack-cleanup.test.ts | 14 +- .../slices/tabs-unread-and-focus.test.ts | 18 +- .../terminal-write-identity-bailouts.test.ts | 2 +- .../slices/ui/ui-slice-activity-actions.ts | 3 +- .../src/store/terminals/terminal-actions.ts | 7 +- .../src/store/terminals/terminal-state.ts | 7 +- .../store/terminals/terminal-tab-attention.ts | 12 +- 37 files changed, 1780 insertions(+), 779 deletions(-) create mode 100644 src/main/notifications/notification-delivery-service.test.ts create mode 100644 src/main/notifications/notification-delivery-service.ts create mode 100644 src/renderer/src/attention/agent-attention-acknowledgement.ts create mode 100644 src/renderer/src/attention/agent-attention-contract.ts create mode 100644 src/renderer/src/attention/agent-attention-policy.test.ts create mode 100644 src/renderer/src/attention/agent-attention-policy.ts create mode 100644 src/renderer/src/components/terminal-pane/notification-dispatch-test-harness.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-attention-surface.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-attention-surface.ts diff --git a/src/main/ipc/notifications.ts b/src/main/ipc/notifications.ts index 274ab2719d85..d4b859f4d93f 100644 --- a/src/main/ipc/notifications.ts +++ b/src/main/ipc/notifications.ts @@ -9,13 +9,12 @@ import type { NotificationPermissionStatusResult } from '../../shared/notification-settings-types' import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { buildNotificationOptions } from './notification-options' import { readNotificationAuthorizationStatus } from './notification-authorization-status' import { setTrayAttention } from '../tray/system-tray' import { isMainWindowVisible } from '../window/main-window-visibility' import { activeNotificationsById } from './native-notification-lifecycle' import { deliverNativeNotification } from './native-notification-delivery' -import { reserveNotificationCooldown } from './notification-burst-cooldown' +import { createNotificationDeliveryService } from '../notifications/notification-delivery-service' import { registerNotificationSoundHandlers } from './notification-sound-ipc' import { openNotificationSystemSettings } from './notification-system-settings-link' import { @@ -29,8 +28,6 @@ import { export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntimeService): void { ipcMain.removeHandler('notifications:getDesktopAwayState') ipcMain.handle('notifications:getDesktopAwayState', () => readDesktopAwayState(powerMonitor)) - const recentDesktopNotifications = new Map() - const recentMobileNotifications = new Map() resetNotificationPermissionEvidence() ipcMain.removeHandler('notifications:openSystemSettings') @@ -106,95 +103,31 @@ export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntime return { dismissed } }) + const deliveryService = createNotificationDeliveryService({ + readNotificationSettings: () => store.getSettings().notifications, + findActiveWindow: () => + BrowserWindow.getAllWindows().find((window) => !window.isDestroyed()) ?? null, + isWindowVisible: isMainWindowVisible, + setTrayAttention, + isNotificationSupported: () => Notification.isSupported(), + dispatchMobileNotification: runtime + ? (payload) => runtime.dispatchMobileNotification(payload) + : null, + readAuthorizationStatus: readNotificationAuthorizationStatus, + recordDeliveryOutcome: recordNotificationDeliveryOutcome, + deliverNative: deliverNativeNotification, + platform: process.platform, + now: () => Date.now() + }) + ipcMain.removeHandler('notifications:dispatch') ipcMain.handle( 'notifications:dispatch', ( _event, args: NotificationDispatchRequest - ): NotificationDispatchResult | Promise => { - // Why: light the tray attention dot before the cooldown/focus/enabled gates so they can't hold it back (clears on window show/restore; see index.ts). - if (args.source === 'agent-task-complete' || args.source === 'terminal-bell') { - const activeWindow = BrowserWindow.getAllWindows().find((win) => !win.isDestroyed()) ?? null - if (!isMainWindowVisible(activeWindow)) { - setTrayAttention(true) - } - } - - const settings = store.getSettings().notifications - const desktopAllowed = - settings.enabled && - (args.source !== 'agent-task-complete' || settings.agentTaskComplete) && - (args.source !== 'terminal-bell' || settings.terminalBell) - - const notificationOptions = buildNotificationOptions(args) - - // Why: desktop focus only means this computer sees the worktree; the paired phone may still need the alert. - if (runtime && args.source !== 'test') { - const dedupeKey = args.worktreeId ?? args.worktreeLabel ?? 'global' - if ( - reserveNotificationCooldown( - recentMobileNotifications, - JSON.stringify([desktopAllowed, args.source, args.agentState, dedupeKey]), - Date.now() - ) - ) { - runtime.dispatchMobileNotification({ - type: 'notification', - emittedAt: Date.now(), - source: args.source, - ...(!desktopAllowed ? { desktopAllowed: false } : {}), - title: notificationOptions.title, - body: notificationOptions.body, - worktreeId: args.worktreeId, - ...(args.notificationId ? { notificationId: args.notificationId } : {}), - // Why: background push needs the agent's real state to pick "needs input" - // vs "finished" — and to stay silent while the agent is still working. - ...(args.agentState ? { agentState: args.agentState } : {}) - }) - } - } - - if (!desktopAllowed) { - return { delivered: false, reason: settings.enabled ? 'source-disabled' : 'disabled' } - } - - const browserWindow = - BrowserWindow.getAllWindows().find((window) => !window.isDestroyed()) ?? null - if ( - settings.suppressWhenFocused && - args.isActiveWorktree && - browserWindow && - browserWindow.isFocused() - ) { - return { delivered: false, reason: 'suppressed-focus' } - } - - // Why: the Settings test button is an explicit, often-repeated user action, so it bypasses burst dedupe. - if (args.source !== 'test') { - // Dedupe by worktree, not source — agent-finish and terminal-bell often fire in one chunk; surface only the first. - const dedupeKey = args.worktreeId ?? args.worktreeLabel ?? 'global' - if (!reserveNotificationCooldown(recentDesktopNotifications, dedupeKey, Date.now())) { - return { delivered: false, reason: 'cooldown' } - } - } - - if (!Notification.isSupported()) { - return { delivered: false, reason: 'not-supported' } - } - - if (process.platform !== 'darwin') { - return deliverNativeNotification(args, notificationOptions, settings) - } - // Why: macOS silently swallows notifications while permission is denied/undecided (verified macOS 26); skip so the renderer can show a fallback. - return readNotificationAuthorizationStatus().then((authorization) => { - if (authorization === 'denied' || authorization === 'not-determined') { - recordNotificationDeliveryOutcome('failed') - return { delivered: false, reason: 'blocked-by-system' } - } - return deliverNativeNotification(args, notificationOptions, settings) - }) - } + ): NotificationDispatchResult | Promise => + deliveryService.dispatch(args) ) registerNotificationSoundHandlers(store) diff --git a/src/main/notifications/notification-delivery-service.test.ts b/src/main/notifications/notification-delivery-service.test.ts new file mode 100644 index 000000000000..1e1b09bfc42e --- /dev/null +++ b/src/main/notifications/notification-delivery-service.test.ts @@ -0,0 +1,163 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { BrowserWindow } from 'electron' +import { createNotificationDeliveryService } from './notification-delivery-service' +import type { NotificationDeliveryDependencies } from './notification-delivery-service' +import type { + NotificationDispatchRequest, + NotificationSettings +} from '../../shared/notification-settings-types' + +function makeSettings(overrides: Partial = {}): NotificationSettings { + return { + enabled: true, + agentTaskComplete: true, + terminalBell: true, + suppressWhenFocused: false, + customSoundId: 'system', + customSoundPath: null, + customSoundVolume: 1, + ...overrides + } +} + +function makeRequest( + overrides: Partial = {} +): NotificationDispatchRequest { + return { + source: 'agent-task-complete', + worktreeId: 'wt-1', + worktreeLabel: 'wt-1', + ...overrides + } +} + +type Harness = { + deps: NotificationDeliveryDependencies + order: string[] + setTrayAttention: ReturnType + dispatchMobileNotification: ReturnType + deliverNative: ReturnType +} + +let now = 1_000 + +/** The delivery policy only asks a window whether it is focused. */ +function makeFocusedWindowStub(): BrowserWindow { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the service reads only isFocused(); a full BrowserWindow cannot be constructed outside Electron. + return { isFocused: () => true } as unknown as BrowserWindow +} + +function makeHarness(settings: NotificationSettings, windowVisible = false): Harness { + const order: string[] = [] + const setTrayAttention = vi.fn(() => order.push('tray')) + const dispatchMobileNotification = vi.fn(() => order.push('mobile')) + const deliverNative = vi.fn(() => { + order.push('native') + return { delivered: true } as const + }) + return { + order, + setTrayAttention, + dispatchMobileNotification, + deliverNative, + deps: { + readNotificationSettings: () => settings, + findActiveWindow: () => null, + isWindowVisible: () => windowVisible, + setTrayAttention, + isNotificationSupported: () => true, + dispatchMobileNotification, + readAuthorizationStatus: () => Promise.resolve('authorized'), + recordDeliveryOutcome: vi.fn(), + deliverNative, + platform: 'linux', + now: () => now + } + } +} + +beforeEach(() => { + now += 60_000 +}) + +describe('createNotificationDeliveryService', () => { + it('lights the tray dot before the enabled/cooldown gates can reject the event', () => { + const harness = makeHarness(makeSettings({ enabled: false })) + const result = createNotificationDeliveryService(harness.deps).dispatch(makeRequest()) + + expect(harness.setTrayAttention).toHaveBeenCalledWith(true) + expect(result).toEqual({ delivered: false, reason: 'disabled' }) + expect(harness.deliverNative).not.toHaveBeenCalled() + expect(harness.order[0]).toBe('tray') + }) + + it('leaves the tray dot alone while the window is visible', () => { + const harness = makeHarness(makeSettings(), true) + createNotificationDeliveryService(harness.deps).dispatch(makeRequest()) + expect(harness.setTrayAttention).not.toHaveBeenCalled() + }) + + it('fans out to mobile before the desktop-disabled early return', () => { + const harness = makeHarness(makeSettings({ agentTaskComplete: false })) + const result = createNotificationDeliveryService(harness.deps).dispatch(makeRequest()) + + expect(result).toEqual({ delivered: false, reason: 'source-disabled' }) + expect(harness.dispatchMobileNotification).toHaveBeenCalledWith( + expect.objectContaining({ desktopAllowed: false, source: 'agent-task-complete' }) + ) + expect(harness.order).toEqual(['tray', 'mobile']) + }) + + it('keeps the desktop source gates distinct per source', () => { + const harness = makeHarness(makeSettings({ terminalBell: false })) + const service = createNotificationDeliveryService(harness.deps) + expect(service.dispatch(makeRequest({ source: 'terminal-bell' }))).toEqual({ + delivered: false, + reason: 'source-disabled' + }) + expect(service.dispatch(makeRequest({ worktreeId: 'wt-2', worktreeLabel: 'wt-2' }))).toEqual({ + delivered: true + }) + }) + + it('suppresses a focused active workspace without touching mobile delivery', () => { + const harness = makeHarness(makeSettings({ suppressWhenFocused: true })) + const focusedWindow = makeFocusedWindowStub() + harness.deps.findActiveWindow = () => focusedWindow + const result = createNotificationDeliveryService(harness.deps).dispatch( + makeRequest({ isActiveWorktree: true }) + ) + + expect(result).toEqual({ delivered: false, reason: 'suppressed-focus' }) + expect(harness.dispatchMobileNotification).toHaveBeenCalledTimes(1) + }) + + it('dedupes desktop bursts per workspace but still reports the first delivery', () => { + const harness = makeHarness(makeSettings()) + const service = createNotificationDeliveryService(harness.deps) + expect(service.dispatch(makeRequest())).toEqual({ delivered: true }) + expect(service.dispatch(makeRequest({ source: 'terminal-bell' }))).toEqual({ + delivered: false, + reason: 'cooldown' + }) + }) + + it('skips mobile fan-out entirely when no runtime is paired', () => { + const harness = makeHarness(makeSettings()) + harness.deps.dispatchMobileNotification = null + expect(createNotificationDeliveryService(harness.deps).dispatch(makeRequest())).toEqual({ + delivered: true + }) + expect(harness.dispatchMobileNotification).not.toHaveBeenCalled() + }) + + it('reports blocked-by-system on macOS when permission is undecided', async () => { + const harness = makeHarness(makeSettings()) + harness.deps.platform = 'darwin' + harness.deps.readAuthorizationStatus = () => Promise.resolve('not-determined') + await expect( + createNotificationDeliveryService(harness.deps).dispatch(makeRequest()) + ).resolves.toEqual({ delivered: false, reason: 'blocked-by-system' }) + expect(harness.deliverNative).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/notifications/notification-delivery-service.ts b/src/main/notifications/notification-delivery-service.ts new file mode 100644 index 000000000000..7ca85c61f92d --- /dev/null +++ b/src/main/notifications/notification-delivery-service.ts @@ -0,0 +1,148 @@ +/** + * Desktop delivery policy for dispatched notifications. + * + * Lifted out of the `notifications:dispatch` IPC closure so the ordering that matters — + * tray attention before the gates, mobile fan-out before the desktop early returns — is + * expressed once against injected collaborators instead of ambient Electron singletons. + */ +import type { BrowserWindow } from 'electron' +import type { + NotificationDispatchRequest, + NotificationDispatchResult, + NotificationSettings +} from '../../shared/notification-settings-types' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import { buildNotificationOptions } from '../ipc/notification-options' +import { reserveNotificationCooldown } from '../ipc/notification-burst-cooldown' + +export type NotificationDeliveryDependencies = { + readNotificationSettings: () => NotificationSettings + /** The window the user would see the banner on, or null when none is open. */ + findActiveWindow: () => BrowserWindow | null + isWindowVisible: (window: BrowserWindow | null) => boolean + setTrayAttention: (attention: boolean) => void + isNotificationSupported: () => boolean + /** Null when no runtime is paired, so mobile fan-out is skipped entirely. */ + dispatchMobileNotification: OrcaRuntimeService['dispatchMobileNotification'] | null + readAuthorizationStatus: () => Promise< + 'authorized' | 'denied' | 'not-determined' | 'unknown' | null + > + recordDeliveryOutcome: (outcome: 'delivered' | 'failed') => void + deliverNative: ( + request: NotificationDispatchRequest, + options: ReturnType, + settings: NotificationSettings + ) => NotificationDispatchResult | Promise + platform: NodeJS.Platform + now: () => number +} + +export type NotificationDeliveryService = { + dispatch: ( + request: NotificationDispatchRequest + ) => NotificationDispatchResult | Promise +} + +export function createNotificationDeliveryService( + deps: NotificationDeliveryDependencies +): NotificationDeliveryService { + const recentDesktopNotifications = new Map() + const recentMobileNotifications = new Map() + + const dedupeKeyFor = (request: NotificationDispatchRequest): string => + request.worktreeId ?? request.worktreeLabel ?? 'global' + + return { + dispatch: (request) => { + // Why: light the tray attention dot before the cooldown/focus/enabled gates so they + // can't hold it back (clears on window show/restore; see index.ts). + if (request.source === 'agent-task-complete' || request.source === 'terminal-bell') { + if (!deps.isWindowVisible(deps.findActiveWindow())) { + deps.setTrayAttention(true) + } + } + + const settings = deps.readNotificationSettings() + const desktopAllowed = + settings.enabled && + (request.source !== 'agent-task-complete' || settings.agentTaskComplete) && + (request.source !== 'terminal-bell' || settings.terminalBell) + + const notificationOptions = buildNotificationOptions(request) + + // Why: desktop focus only means this computer sees the worktree; the paired phone may still need the alert. + if (deps.dispatchMobileNotification && request.source !== 'test') { + if ( + reserveNotificationCooldown( + recentMobileNotifications, + JSON.stringify([ + desktopAllowed, + request.source, + request.agentState, + dedupeKeyFor(request) + ]), + deps.now() + ) + ) { + deps.dispatchMobileNotification({ + type: 'notification', + emittedAt: deps.now(), + source: request.source, + ...(!desktopAllowed ? { desktopAllowed: false } : {}), + title: notificationOptions.title, + body: notificationOptions.body, + worktreeId: request.worktreeId, + ...(request.notificationId ? { notificationId: request.notificationId } : {}), + // Why: background push needs the agent's real state to pick "needs input" + // vs "finished" — and to stay silent while the agent is still working. + ...(request.agentState ? { agentState: request.agentState } : {}) + }) + } + } + + if (!desktopAllowed) { + return { delivered: false, reason: settings.enabled ? 'source-disabled' : 'disabled' } + } + + const browserWindow = deps.findActiveWindow() + if ( + settings.suppressWhenFocused && + request.isActiveWorktree && + browserWindow && + browserWindow.isFocused() + ) { + return { delivered: false, reason: 'suppressed-focus' } + } + + // Why: the Settings test button is an explicit, often-repeated user action, so it bypasses burst dedupe. + if (request.source !== 'test') { + // Dedupe by worktree, not source — agent-finish and terminal-bell often fire in one chunk; surface only the first. + if ( + !reserveNotificationCooldown( + recentDesktopNotifications, + dedupeKeyFor(request), + deps.now() + ) + ) { + return { delivered: false, reason: 'cooldown' } + } + } + + if (!deps.isNotificationSupported()) { + return { delivered: false, reason: 'not-supported' } + } + + if (deps.platform !== 'darwin') { + return deps.deliverNative(request, notificationOptions, settings) + } + // Why: macOS silently swallows notifications while permission is denied/undecided (verified macOS 26); skip so the renderer can show a fallback. + return deps.readAuthorizationStatus().then((authorization) => { + if (authorization === 'denied' || authorization === 'not-determined') { + deps.recordDeliveryOutcome('failed') + return { delivered: false, reason: 'blocked-by-system' } + } + return deps.deliverNative(request, notificationOptions, settings) + }) + } + } +} diff --git a/src/renderer/src/attention/agent-attention-acknowledgement.ts b/src/renderer/src/attention/agent-attention-acknowledgement.ts new file mode 100644 index 000000000000..69d678600248 --- /dev/null +++ b/src/renderer/src/attention/agent-attention-acknowledgement.ts @@ -0,0 +1,151 @@ +import { + readAgentAttentionUnreadReason, + type AgentAttentionRemainder, + type ReadableAgentAttentionUnread +} from './agent-attention-contract' + +/** Subject-keyed turn bookkeeping the acknowledgement policy reads; no surface shape here. */ +export type AgentAttentionTurnRecords = { + liveTurns: Record + /** Turns kept after their session ended, so a finished agent can still be acknowledged. */ + retainedTurns: Record + acknowledgedTurnStartedAt: Record +} + +export type AgentAttentionAcknowledgementSink = { + acknowledgeSubjects: (subjectKeys: string[]) => void + clearWorkspaceUnread: (workspaceId: string) => void + clearGroupUnread: (groupId: string) => void + clearSubjectUnread: (subjectKey: string) => void +} + +export function readAgentAttentionTurnStartedAt( + records: Pick, + subjectKey: string +): number | null { + return ( + records.liveTurns[subjectKey]?.stateStartedAt ?? + records.retainedTurns[subjectKey]?.entry.stateStartedAt ?? + null + ) +} + +/** + * Subjects on the viewed surface whose current turn has not been acknowledged yet. + * + * Why compare stateStartedAt (not updatedAt): same-state pings must not re-trigger an ack, + * matching the is-unvisited rule the workspace card uses. + */ +export function computeAgentAcknowledgementTargets( + records: AgentAttentionTurnRecords, + subjectKey: string | null +): string[] { + if (subjectKey === null) { + return [] + } + const targets: string[] = [] + const acknowledgedAt = records.acknowledgedTurnStartedAt[subjectKey] ?? 0 + const liveTurn = records.liveTurns[subjectKey] + if (liveTurn && acknowledgedAt < liveTurn.stateStartedAt) { + targets.push(subjectKey) + } + const retainedTurn = records.retainedTurns[subjectKey] + if (retainedTurn && acknowledgedAt < retainedTurn.entry.stateStartedAt) { + targets.push(subjectKey) + } + return targets +} + +/** The viewed subject when it currently holds an unread attention marker. */ +export function resolveViewedUnreadSubjectKey( + unreadBySubjectKey: Record, + subjectKey: string | null +): string | null { + if (subjectKey === null) { + return null + } + return readAgentAttentionUnreadReason(unreadBySubjectKey[subjectKey]) === null ? null : subjectKey +} + +/** + * Manual mark-unread protections that no longer apply: the user moved to another subject, or + * the agent took a new turn. + * + * Why keep on null: persisted UI hydrates before the turn snapshot lands, so an active subject + * with no row yet is "not known", not "moved on"; wiping it would lose the user's mark-unread. + */ +export function computeLapsedManualUnreadProtections( + records: Pick & { + manuallyUnreadTurnStartedAt: Record + }, + activeSubjectKeys: ReadonlySet +): string[] { + const lapsed: string[] = [] + for (const [subjectKey, turnStartedAt] of Object.entries(records.manuallyUnreadTurnStartedAt)) { + if (!activeSubjectKeys.has(subjectKey)) { + lapsed.push(subjectKey) + continue + } + const currentTurn = readAgentAttentionTurnStartedAt(records, subjectKey) + if (currentTurn !== null && currentTurn !== turnStartedAt) { + lapsed.push(subjectKey) + } + } + return lapsed +} + +/** + * Workspace unread is coarse, so a hidden sibling still wanting attention keeps it lit even + * while the user acknowledges the subject in front of them. + */ +export function shouldClearWorkspaceAttention( + remainder: AgentAttentionRemainder, + args: { viewedGroupId: string; clearedSubjectKeys: ReadonlySet } +): boolean { + if (!remainder.hasSurfaces) { + return true + } + for (const subjectKey of remainder.unreadSubjectKeys) { + if (!args.clearedSubjectKeys.has(subjectKey)) { + return false + } + } + for (const groupId of remainder.unreadGroupIds) { + if (groupId !== args.viewedGroupId) { + return false + } + } + return true +} + +export function applyAgentAttentionAcknowledgement( + sink: AgentAttentionAcknowledgementSink, + args: { + /** Null when a hidden sibling still owns the workspace's attention. */ + workspaceIdToClear: string | null + viewedGroupId: string + subjectKeys: string[] + viewedUnreadSubjectKey?: string | null + } +): void { + const subjectKeysToClear = new Set(args.subjectKeys) + if (args.viewedUnreadSubjectKey) { + subjectKeysToClear.add(args.viewedUnreadSubjectKey) + } + + if (args.subjectKeys.length === 0 && subjectKeysToClear.size === 0) { + return + } + + if (args.subjectKeys.length > 0) { + sink.acknowledgeSubjects(args.subjectKeys) + } + if (args.workspaceIdToClear !== null) { + // Why: the selected agent is now visible, so drop the Dock-driving workspace unread. + sink.clearWorkspaceUnread(args.workspaceIdToClear) + } + sink.clearGroupUnread(args.viewedGroupId) + for (const subjectKey of subjectKeysToClear) { + sink.clearSubjectUnread(subjectKey) + } +} diff --git a/src/renderer/src/attention/agent-attention-contract.ts b/src/renderer/src/attention/agent-attention-contract.ts new file mode 100644 index 000000000000..644691a2b3d1 --- /dev/null +++ b/src/renderer/src/attention/agent-attention-contract.ts @@ -0,0 +1,85 @@ +/** + * Provider-neutral agent attention boundary. + * + * Nothing in this folder may import a PTY, terminal leaf or terminal layout module: a + * surface adapter answers every question about where a subject lives and who can see it, + * so a non-terminal agent surface can supply its own adapter without touching the policy. + */ + +/** Why an unread marker exists. `legacy` is a marker written before reasons were recorded. */ +export type AgentAttentionUnreadReason = + | 'agent-completion' + | 'terminal-bell' + | 'manual-mark-unread' + | 'legacy' + +/** Stored marker shape: a classified reason, or the pre-reason boolean still on live state. */ +export type StoredAgentAttentionUnread = AgentAttentionUnreadReason | true + +/** What a reader may find, including a marker some other writer cleared to `false`. */ +export type ReadableAgentAttentionUnread = AgentAttentionUnreadReason | boolean | undefined + +/** Reads a marker without guessing its origin: an unclassified boolean reports as `legacy`. */ +export function readAgentAttentionUnreadReason( + marker: ReadableAgentAttentionUnread +): AgentAttentionUnreadReason | null { + if (marker === undefined || marker === false) { + return null + } + return marker === true ? 'legacy' : marker +} + +/** A workspace-scoped attention subject; `surfaceKey` addresses one surface inside it. */ +export type AgentAttentionSubject = { + workspaceId: string + surfaceKey?: string | undefined +} + +/** A subject that names a concrete surface, so the adapter can resolve its container. */ +export type AgentAttentionSurfaceSubject = { + workspaceId: string + surfaceKey: string +} + +/** What the boundary knows about the subject still being alive when it admits an event. */ +export type AgentAttentionLiveness = { + hasLiveSession: boolean + hasFreshActivityEvidence: boolean +} + +/** Whether a surface key still addresses the surface that produced the event. */ +export type AgentAttentionSurfaceAdmission = + | { admitted: true; groupId: string } + | { admitted: false; cause: 'unknown-surface' | 'superseded-surface' } + +/** Attention still held elsewhere in a workspace, as the owning surface sees it. */ +export type AgentAttentionRemainder = { + /** False when the workspace owns no surfaces at all, so nothing can hold its unread. */ + hasSurfaces: boolean + unreadSubjectKeys: readonly string[] + unreadGroupIds: readonly string[] +} + +/** + * The surface-shaped half of the boundary. One implementation per agent surface kind; + * the terminal implementation is the only holder of the PTY/leaf/layout predicates. + */ +export type AgentAttentionSurface = { + /** Is there still a running session behind this subject? */ + hasLiveSession: (subject: AgentAttentionSubject) => boolean + /** Resolve the surface to its current container, rejecting a stale or reused address. */ + admitSurface: ( + subject: AgentAttentionSurfaceSubject, + liveness: AgentAttentionLiveness + ) => AgentAttentionSurfaceAdmission + /** Is this exact surface the one the user is looking at right now? */ + isSurfaceViewed: (subject: AgentAttentionSurfaceSubject) => boolean + /** Fallback for events with no surface key: is the workspace itself on screen? */ + isWorkspaceViewed: (workspaceId: string) => boolean + /** In-app selection only — true even when the window is in the background. */ + isWorkspaceActive: (workspaceId: string) => boolean + /** The subject on screen inside a container, if the container shows one. */ + resolveViewedSubjectKey: (groupId: string) => string | null + /** Attention held by the workspace's other surfaces, for sibling protection. */ + collectWorkspaceAttentionRemainder: (workspaceId: string) => AgentAttentionRemainder +} diff --git a/src/renderer/src/attention/agent-attention-policy.test.ts b/src/renderer/src/attention/agent-attention-policy.test.ts new file mode 100644 index 000000000000..ac21cdd58cb3 --- /dev/null +++ b/src/renderer/src/attention/agent-attention-policy.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, it, vi } from 'vitest' +import type { AgentAttentionSurface } from './agent-attention-contract' +import { + applyAgentAttention, + resolveAgentAttention, + type AgentAttentionRequest, + type AgentAttentionSink +} from './agent-attention-policy' + +const WORKSPACE = 'wt-1' +const SUBJECT = 'tab-1:leaf-1' +const GROUP = 'tab-1' + +function makeSurface(overrides: Partial = {}): AgentAttentionSurface { + return { + hasLiveSession: () => true, + admitSurface: () => ({ admitted: true, groupId: GROUP }), + isSurfaceViewed: () => false, + isWorkspaceViewed: () => false, + isWorkspaceActive: () => false, + resolveViewedSubjectKey: () => null, + collectWorkspaceAttentionRemainder: () => ({ + hasSurfaces: true, + unreadSubjectKeys: [], + unreadGroupIds: [] + }), + ...overrides + } +} + +function completion(overrides: Partial = {}): AgentAttentionRequest { + return { + subject: { workspaceId: WORKSPACE, surfaceKey: SUBJECT }, + reason: 'agent-completion', + settlesTurn: true, + hasFreshActivityEvidence: false, + groupAttentionEnabled: false, + ...overrides + } +} + +function makeSink(): AgentAttentionSink & { calls: string[] } { + const calls: string[] = [] + return { + calls, + unread: { + markWorkspaceUnread: (workspaceId) => calls.push(`workspace:${workspaceId}`), + markSubjectUnread: (key, reason) => calls.push(`subject:${key}:${reason}`), + markGroupUnread: (key, reason) => calls.push(`group:${key}:${reason}`), + markSurfaceUnread: (key, reason) => calls.push(`surface:${key}:${reason}`) + }, + requestDelivery: (request) => calls.push(`deliver:${request.workspaceId}:${request.subjectKey}`) + } +} + +describe('resolveAgentAttention', () => { + it('rejects a subject with no live session and no fresh activity evidence', () => { + const decision = resolveAgentAttention( + completion(), + makeSurface({ hasLiveSession: () => false }) + ) + expect(decision).toEqual({ admitted: false, cause: 'no-live-session' }) + }) + + it('admits a dead surface when fresh activity evidence stands in for liveness', () => { + const admitSurface = vi.fn(() => ({ admitted: true, groupId: GROUP }) as const) + const decision = resolveAgentAttention( + completion({ hasFreshActivityEvidence: true }), + makeSurface({ hasLiveSession: () => false, admitSurface }) + ) + expect(decision.admitted).toBe(true) + // The surface must be told which evidence admitted the event so it can pick its gate. + expect(admitSurface).toHaveBeenCalledWith( + { workspaceId: WORKSPACE, surfaceKey: SUBJECT }, + { hasLiveSession: false, hasFreshActivityEvidence: true } + ) + }) + + it('rejects a superseded surface outright — no unread and no delivery', () => { + const decision = resolveAgentAttention( + completion(), + makeSurface({ admitSurface: () => ({ admitted: false, cause: 'superseded-surface' }) }) + ) + expect(decision).toEqual({ admitted: false, cause: 'superseded-surface' }) + + const sink = makeSink() + applyAgentAttention(decision, sink) + expect(sink.calls).toEqual([]) + }) + + it('rejects a surface key that resolves to no container', () => { + const decision = resolveAgentAttention( + completion(), + makeSurface({ admitSurface: () => ({ admitted: false, cause: 'unknown-surface' }) }) + ) + expect(decision).toEqual({ admitted: false, cause: 'unknown-surface' }) + }) + + it('admits a viewed surface for delivery but earns it no unread', () => { + const decision = resolveAgentAttention( + completion(), + makeSurface({ isSurfaceViewed: () => true }) + ) + expect(decision).toMatchObject({ admitted: true, unread: null }) + + const sink = makeSink() + applyAgentAttention(decision, sink) + expect(sink.calls).toEqual([`deliver:${WORKSPACE}:${SUBJECT}`]) + }) + + it('carries the unread reason into every store write', () => { + const decision = resolveAgentAttention( + completion({ groupAttentionEnabled: true }), + makeSurface() + ) + const sink = makeSink() + applyAgentAttention(decision, sink) + expect(sink.calls).toEqual([ + `workspace:${WORKSPACE}`, + `subject:${SUBJECT}:agent-completion`, + `group:${GROUP}:agent-completion`, + `surface:${SUBJECT}:agent-completion`, + `deliver:${WORKSPACE}:${SUBJECT}` + ]) + }) + + it('keeps container attention behind its presentation flag', () => { + const sink = makeSink() + applyAgentAttention(resolveAgentAttention(completion(), makeSurface()), sink) + expect(sink.calls).toEqual([ + `workspace:${WORKSPACE}`, + `subject:${SUBJECT}:agent-completion`, + `deliver:${WORKSPACE}:${SUBJECT}` + ]) + }) + + it('falls back to workspace visibility when the event names no surface', () => { + const isWorkspaceViewed = vi.fn(() => true) + const admitSurface = vi.fn() + const decision = resolveAgentAttention( + completion({ subject: { workspaceId: WORKSPACE } }), + makeSurface({ isWorkspaceViewed, admitSurface }) + ) + expect(decision).toMatchObject({ admitted: true, unread: null }) + expect(isWorkspaceViewed).toHaveBeenCalledWith(WORKSPACE) + // No surface key means there is no address to validate. + expect(admitSurface).not.toHaveBeenCalled() + }) + + it('delivers a bell without validating the surface address or writing unread', () => { + const admitSurface = vi.fn() + const isSurfaceViewed = vi.fn() + const decision = resolveAgentAttention( + completion({ reason: 'terminal-bell', settlesTurn: false }), + makeSurface({ admitSurface, isSurfaceViewed }) + ) + expect(decision).toMatchObject({ admitted: true, unread: null }) + expect(admitSurface).not.toHaveBeenCalled() + expect(isSurfaceViewed).not.toHaveBeenCalled() + + const sink = makeSink() + applyAgentAttention(decision, sink) + expect(sink.calls).toEqual([`deliver:${WORKSPACE}:${SUBJECT}`]) + }) + + it('reports in-app workspace selection to the delivery owner', () => { + const decision = resolveAgentAttention( + completion(), + makeSurface({ isWorkspaceActive: (workspaceId) => workspaceId === WORKSPACE }) + ) + expect(decision).toMatchObject({ admitted: true, delivery: { workspaceIsActive: true } }) + }) + + it('writes unread before requesting delivery so a suppressed banner still leaves a marker', () => { + const sink = makeSink() + applyAgentAttention(resolveAgentAttention(completion(), makeSurface()), sink) + expect(sink.calls.indexOf(`workspace:${WORKSPACE}`)).toBeLessThan( + sink.calls.indexOf(`deliver:${WORKSPACE}:${SUBJECT}`) + ) + }) +}) diff --git a/src/renderer/src/attention/agent-attention-policy.ts b/src/renderer/src/attention/agent-attention-policy.ts new file mode 100644 index 000000000000..7a075e50f6c5 --- /dev/null +++ b/src/renderer/src/attention/agent-attention-policy.ts @@ -0,0 +1,143 @@ +import type { + AgentAttentionSubject, + AgentAttentionSurface, + AgentAttentionUnreadReason +} from './agent-attention-contract' + +export type AgentAttentionRequest = { + subject: AgentAttentionSubject + reason: AgentAttentionUnreadReason + /** + * A settled turn owns the subject's attention, so its address is validated and unread is + * decided. A bare surface signal (a bell) only has to prove the subject is still alive. + */ + settlesTurn: boolean + /** Out-of-band proof the subject just produced work, used when no live session is visible. */ + hasFreshActivityEvidence: boolean + /** Presentation policy: also raise the container/surface attention markers. */ + groupAttentionEnabled: boolean +} + +export type AgentAttentionUnreadWrite = { + workspaceId: string + subjectKey: string | null + groupId: string | null + reason: AgentAttentionUnreadReason + groupAttentionEnabled: boolean +} + +export type AgentAttentionDeliveryRequest = { + workspaceId: string + subjectKey: string | null + /** Carried so the delivery owner can apply its own suppress-while-focused policy. */ + workspaceIsActive: boolean +} + +export type AgentAttentionDecision = + | { admitted: false; cause: 'no-live-session' | 'unknown-surface' | 'superseded-surface' } + | { + admitted: true + unread: AgentAttentionUnreadWrite | null + delivery: AgentAttentionDeliveryRequest + } + +export type AgentAttentionUnreadSink = { + /** Workspace unread is a persisted boolean shared with remote clients; it carries no reason. */ + markWorkspaceUnread: (workspaceId: string) => void + markSubjectUnread: (subjectKey: string, reason: AgentAttentionUnreadReason) => void + markGroupUnread: (groupId: string, reason: AgentAttentionUnreadReason) => void + markSurfaceUnread: (subjectKey: string, reason: AgentAttentionUnreadReason) => void +} + +export type AgentAttentionSink = { + unread: AgentAttentionUnreadSink + requestDelivery: (request: AgentAttentionDeliveryRequest) => void +} + +/** + * Decides what an attention event earns, asking the surface adapter for every fact. + * + * Admission and visibility are deliberately separate gates: a superseded surface is rejected + * outright (no unread, no delivery), while a surface the user is watching is admitted and + * delivered but earns no unread. + */ +export function resolveAgentAttention( + request: AgentAttentionRequest, + surface: AgentAttentionSurface +): AgentAttentionDecision { + const { workspaceId } = request.subject + const subjectKey = request.subject.surfaceKey ?? null + const hasLiveSession = surface.hasLiveSession(request.subject) + if (!hasLiveSession && !request.hasFreshActivityEvidence) { + return { admitted: false, cause: 'no-live-session' } + } + + let groupId: string | null = null + if (request.settlesTurn && subjectKey !== null) { + const admission = surface.admitSurface( + { workspaceId, surfaceKey: subjectKey }, + { hasLiveSession, hasFreshActivityEvidence: request.hasFreshActivityEvidence } + ) + if (!admission.admitted) { + return { admitted: false, cause: admission.cause } + } + groupId = admission.groupId + } + + const delivery: AgentAttentionDeliveryRequest = { + workspaceId, + subjectKey, + workspaceIsActive: surface.isWorkspaceActive(workspaceId) + } + if (!request.settlesTurn) { + return { admitted: true, unread: null, delivery } + } + + const viewed = + subjectKey === null + ? surface.isWorkspaceViewed(workspaceId) + : surface.isSurfaceViewed({ workspaceId, surfaceKey: subjectKey }) + return { + admitted: true, + unread: viewed + ? null + : { + workspaceId, + subjectKey, + groupId, + reason: request.reason, + groupAttentionEnabled: request.groupAttentionEnabled + }, + delivery + } +} + +export function applyAgentAttentionUnread( + write: AgentAttentionUnreadWrite, + sink: AgentAttentionUnreadSink +): void { + sink.markWorkspaceUnread(write.workspaceId) + if (write.subjectKey !== null) { + // Why: focus-return auto-ack needs an agent-specific marker; the generic surface marker + // below also covers bells and is gated behind the experimental attention setting. + sink.markSubjectUnread(write.subjectKey, write.reason) + } + if (write.groupAttentionEnabled && write.groupId !== null && write.subjectKey !== null) { + sink.markGroupUnread(write.groupId, write.reason) + sink.markSurfaceUnread(write.subjectKey, write.reason) + } +} + +/** Unread is written before delivery so a suppressed banner still leaves the marker behind. */ +export function applyAgentAttention( + decision: AgentAttentionDecision, + sink: AgentAttentionSink +): void { + if (!decision.admitted) { + return + } + if (decision.unread !== null) { + applyAgentAttentionUnread(decision.unread, sink.unread) + } + sink.requestDelivery(decision.delivery) +} diff --git a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts index 6e013ec22087..b27d8b0a4080 100644 --- a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts +++ b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts @@ -336,7 +336,7 @@ describe('hasUnreadAgentCompletionForTerminalTab', () => { it('changes only the owning tab when immutable marker snapshots add and clear unread', () => { const before = { [`tab-2:${SECOND_LEAF_ID}`]: true } const added = { ...before, [`${TAB_ID}:${FIRST_LEAF_ID}`]: true } - const cleared = { ...added, [`${TAB_ID}:${FIRST_LEAF_ID}`]: false } + const cleared = { ...added, [`${TAB_ID}:${FIRST_LEAF_ID}`]: undefined } expect(hasUnreadAgentCompletionForTerminalTab(before, TAB_ID)).toBe(false) expect(hasUnreadAgentCompletionForTerminalTab(added, TAB_ID)).toBe(true) diff --git a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts index 858cf024da2b..b097db3bba44 100644 --- a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts +++ b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts @@ -1,3 +1,4 @@ +import type { ReadableAgentAttentionUnread } from '@/attention/agent-attention-contract' import { isExplicitAgentStatusFresh } from '@/lib/agent-status' import { resolveWorktreeStatus, type WorktreeStatus } from '@/lib/worktree-status' import { @@ -255,8 +256,8 @@ export function terminalTabHasUnreadActivity({ unreadAgentCompletionPanes }: { terminalTabId: string - unreadTerminalTabs: Record - unreadAgentCompletionPanes: Record + unreadTerminalTabs: Record + unreadAgentCompletionPanes: Record }): boolean { return ( unreadTerminalTabs[terminalTabId] === true || @@ -266,12 +267,12 @@ export function terminalTabHasUnreadActivity({ // Why: production writes replace this map; WeakMap supports retained snapshots without pinning them. let unreadAgentCompletionTabIdsBySnapshot = new WeakMap< - Record, + Record, ReadonlySet >() function getUnreadAgentCompletionTabIds( - unreadAgentCompletionPanes: Record + unreadAgentCompletionPanes: Record ): ReadonlySet { const cached = unreadAgentCompletionTabIdsBySnapshot.get(unreadAgentCompletionPanes) if (cached) { @@ -293,7 +294,7 @@ function getUnreadAgentCompletionTabIds( /** Match pane-level unread completion markers to their owning terminal tab. */ export function hasUnreadAgentCompletionForTerminalTab( - unreadAgentCompletionPanes: Record | undefined, + unreadAgentCompletionPanes: Record | undefined, tabId: string ): boolean { return unreadAgentCompletionPanes 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 new file mode 100644 index 000000000000..809bbe60e1b9 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/notification-dispatch-test-harness.ts @@ -0,0 +1,150 @@ +import { vi } from 'vitest' +import type { Mock } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import type { TerminalLayoutSnapshot } from '../../../../shared/terminal-tab-types' + +// Why: the mocked store state lives here so each split suite's hoisted `vi.mock` factory can +// reach it through a lazy dynamic import (hoisted factories cannot close over imports). + +export const LIVE_LEAF_ID = '11111111-1111-4111-8111-111111111111' +export const STALE_LEAF_ID = '22222222-2222-4222-8222-222222222222' +export const PANE_KEY = `tab-1:${LIVE_LEAF_ID}` +export const STALE_PANE_KEY = `tab-1:${STALE_LEAF_ID}` + +export type NotificationDispatchMockState = { + activeWorktreeId: string | null + activeTabId: string | null + tabsByWorktree: Record + ptyIdsByTabId: Record + suppressedPtyExitIds: Record + terminalLayoutsByTabId: Record + browserTabsByWorktree: Record + retainedAgentsByPaneKey: Record + agentStatusByPaneKey: Record + worktreesByRepo: Record< + string, + { + id: string + repoId: string + displayName?: string + branch?: string + workspaceStatus?: string + }[] + > + repos: { id: string; displayName?: string; connectionId?: string | null }[] + settings: { + experimentalTerminalAttention?: boolean + notifications?: { + enabled?: boolean + agentTaskComplete?: boolean + customSoundPath?: string | null + customSoundId?: string | null + } + } + markWorktreeUnread: ReturnType + markTerminalTabUnread: ReturnType + markTerminalPaneUnread: ReturnType + markAgentCompletionPaneUnread: ReturnType +} + +/** Annotated explicitly so declaration emit never names @vitest/spy internals. */ +export const playDesktopNotificationSound: Mock<(...args: never[]) => unknown> = vi.fn() + +let mockState: NotificationDispatchMockState = buildNotificationDispatchMockState() + +export function getNotificationDispatchMockState(): NotificationDispatchMockState { + return mockState +} + +function buildNotificationDispatchMockState(): NotificationDispatchMockState { + return { + activeWorktreeId: 'wt-secondary', + activeTabId: 'tab-1', + tabsByWorktree: { 'wt-primary': [{ id: 'tab-1', ptyId: 'pty-1' }] }, + ptyIdsByTabId: { 'tab-1': ['pty-1'] }, + suppressedPtyExitIds: {}, + terminalLayoutsByTabId: { + 'tab-1': { + root: { type: 'leaf', leafId: LIVE_LEAF_ID }, + activeLeafId: LIVE_LEAF_ID, + expandedLeafId: null, + ptyIdsByLeafId: { [LIVE_LEAF_ID]: 'pty-1' } + } + }, + browserTabsByWorktree: {}, + retainedAgentsByPaneKey: {}, + agentStatusByPaneKey: { [PANE_KEY]: makeAgentStatus(PANE_KEY) }, + worktreesByRepo: { + repo1: [ + { id: 'wt-primary', repoId: 'repo1', displayName: 'master', branch: 'master' }, + { + id: 'wt-secondary', + repoId: 'repo1', + displayName: 'e2e-secondary', + branch: 'e2e-secondary' + } + ] + }, + repos: [{ id: 'repo1', displayName: 'orca', connectionId: null }], + settings: { experimentalTerminalAttention: true, notifications: { customSoundPath: null } }, + markWorktreeUnread: vi.fn(), + markTerminalTabUnread: vi.fn(), + markTerminalPaneUnread: vi.fn(), + markAgentCompletionPaneUnread: vi.fn() + } +} + +/** Rebuilds the mocked store and stubs the notification bridge; returns the fresh state. */ +export function resetNotificationDispatchMockState(): NotificationDispatchMockState { + vi.clearAllMocks() + mockState = buildNotificationDispatchMockState() + vi.stubGlobal('window', { + api: { notifications: { dispatch: vi.fn().mockResolvedValue({ delivered: true }) } } + }) + return mockState +} + +export function makeAgentStatus( + paneKey: string, + overrides: Partial = {} +): AgentStatusEntry { + const now = Date.now() + return { + state: 'done', + prompt: 'codex-hook-notify', + updatedAt: now, + stateStartedAt: now, + agentType: 'codex', + paneKey, + terminalTitle: 'codex', + stateHistory: [], + lastAssistantMessage: 'Done.', + ...overrides + } +} + +export function stubDocumentFocus({ + visibilityState, + focused +}: { + visibilityState: DocumentVisibilityState + focused: boolean +}): void { + vi.stubGlobal('document', { visibilityState, hasFocus: vi.fn(() => focused) }) +} + +export function getLastNotificationDispatchArg(): Record | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the window stub above installs a vi.fn() at this exact path. + const dispatch = window.api.notifications.dispatch as unknown as ReturnType + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: dispatch is only ever called with one NotificationDispatchRequest object. + return dispatch.mock.calls.at(-1)?.[0] as Record | undefined +} + +/** Shared `vi.mock` factories; hoisted factories must import this module lazily. */ +export function createNotificationDispatchStoreModuleMock(): Record { + return { useAppStore: { getState: () => getNotificationDispatchMockState() } } +} + +export function createDesktopNotificationSoundModuleMock(): Record { + return { playDesktopNotificationSound } +} diff --git a/src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts b/src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts index e33a10048fca..6442f5eb5f95 100644 --- a/src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts +++ b/src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts @@ -215,7 +215,7 @@ describe('startParkedTerminalByteWatcher', () => { flushSideEffects() expect(mockStoreState.markWorktreeUnread).toHaveBeenCalledWith(WORKTREE_ID) - expect(mockStoreState.markTerminalTabUnread).toHaveBeenCalledWith(TAB_ID) + expect(mockStoreState.markTerminalTabUnread).toHaveBeenCalledWith(TAB_ID, 'terminal-bell') expect(mockStoreState.markTerminalPaneUnread).not.toHaveBeenCalled() expect(dispatchTerminalNotification).not.toHaveBeenCalled() @@ -239,7 +239,7 @@ describe('startParkedTerminalByteWatcher', () => { emit('\x07') flushSideEffects() - expect(mockStoreState.markTerminalPaneUnread).toHaveBeenCalledWith(PANE_KEY) + expect(mockStoreState.markTerminalPaneUnread).toHaveBeenCalledWith(PANE_KEY, 'terminal-bell') dispose() }) @@ -773,7 +773,7 @@ describe('startParkedTerminalByteWatcher', () => { await dispatchFacts([{ kind: 'bell' }]) expect(mockStoreState.markWorktreeUnread).toHaveBeenCalledWith(WORKTREE_ID) - expect(mockStoreState.markTerminalTabUnread).toHaveBeenCalledWith(TAB_ID) + expect(mockStoreState.markTerminalTabUnread).toHaveBeenCalledWith(TAB_ID, 'terminal-bell') expect(dispatchTerminalNotification).not.toHaveBeenCalled() vi.advanceTimersByTime(NOTIFICATION_GRACE_MS) diff --git a/src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts b/src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts index f28685fb28f9..f3fa629df7ad 100644 --- a/src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts +++ b/src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts @@ -127,9 +127,9 @@ export function startParkedTerminalByteWatcher( onBell: (): void => { const state = useAppStore.getState() state.markWorktreeUnread(worktreeId) - state.markTerminalTabUnread(tabId) + state.markTerminalTabUnread(tabId, 'terminal-bell') if (state.settings?.experimentalTerminalAttention === true) { - state.markTerminalPaneUnread(paneKey) + state.markTerminalPaneUnread(paneKey, 'terminal-bell') } // Why: agents emit BEL in the same burst as working→idle, so delay only the OS notification to let the richer completion notification win. pendingBellNotification = true diff --git a/src/renderer/src/components/terminal-pane/pty-connection-hook-completion-bell-arbitration.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-hook-completion-bell-arbitration.test.ts index 74ef53788f84..e315563f0c66 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-hook-completion-bell-arbitration.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-hook-completion-bell-arbitration.test.ts @@ -523,7 +523,10 @@ describe('connectPanePty', () => { bellHandler() ;(onDataHandler as (data: string) => void)('a') - expect(deps.markTerminalPaneUnread).toHaveBeenCalledWith(makePaneKey('tab-1', LEAF_1)) + expect(deps.markTerminalPaneUnread).toHaveBeenCalledWith( + makePaneKey('tab-1', LEAF_1), + 'terminal-bell' + ) expect(deps.clearTerminalPaneUnread).not.toHaveBeenCalled() expect(transport.sendInput).toHaveBeenCalledWith('a') }) diff --git a/src/renderer/src/components/terminal-pane/pty-connection-hook-idle-arbitration.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-hook-idle-arbitration.test.ts index 956cca98943b..ce5834f100a1 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-hook-idle-arbitration.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-hook-idle-arbitration.test.ts @@ -210,8 +210,8 @@ describe('connectPanePty', () => { paneKey }) expect(mockStoreState.markWorktreeUnread).toHaveBeenCalledWith('wt-1') - expect(mockStoreState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(mockStoreState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockStoreState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'agent-completion') + expect(mockStoreState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey, 'agent-completion') expect(window.api.notifications.dispatch).toHaveBeenCalledWith( expect.objectContaining({ source: 'agent-task-complete', diff --git a/src/renderer/src/components/terminal-pane/pty-connection-main-side-effect-authority.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-main-side-effect-authority.test.ts index 25b4027c545d..d1b618e03308 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-main-side-effect-authority.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-main-side-effect-authority.test.ts @@ -235,7 +235,7 @@ describe('connectPanePty', () => { expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'Codex working') expect(deps.markWorktreeUnread).toHaveBeenCalledTimes(1) - expect(deps.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') + expect(deps.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'terminal-bell') expect(deps.dispatchNotification).not.toHaveBeenCalled() vi.advanceTimersByTime(250) expect(deps.dispatchNotification).toHaveBeenCalledWith( diff --git a/src/renderer/src/components/terminal-pane/pty-connection-runtime-owner-spawn-routing.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-runtime-owner-spawn-routing.test.ts index 668b93289429..72efb7c104a3 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-runtime-owner-spawn-routing.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-runtime-owner-spawn-routing.test.ts @@ -438,8 +438,11 @@ describe('connectPanePty', () => { bellHandler() expect(deps.markWorktreeUnread).toHaveBeenCalledTimes(1) - expect(deps.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(deps.markTerminalPaneUnread).toHaveBeenCalledWith(makePaneKey('tab-1', LEAF_1)) + expect(deps.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'terminal-bell') + expect(deps.markTerminalPaneUnread).toHaveBeenCalledWith( + makePaneKey('tab-1', LEAF_1), + 'terminal-bell' + ) expect(deps.dispatchNotification).not.toHaveBeenCalled() vi.advanceTimersByTime(250) expect(deps.dispatchNotification).toHaveBeenCalledWith( @@ -473,7 +476,7 @@ describe('connectPanePty', () => { bellHandler() expect(deps.markWorktreeUnread).toHaveBeenCalledTimes(1) - expect(deps.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') + expect(deps.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'terminal-bell') expect(deps.markTerminalPaneUnread).not.toHaveBeenCalled() }) diff --git a/src/renderer/src/components/terminal-pane/pty-connection-types.ts b/src/renderer/src/components/terminal-pane/pty-connection-types.ts index e691b5c87159..27a24c73621f 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-types.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-types.ts @@ -1,3 +1,4 @@ +import type { AgentAttentionUnreadReason } from '@/attention/agent-attention-contract' import type { PtyTransport } from './pty-transport' import type { SessionRestoredBannerReason } from './session-restored-banner-pane-state' import type { ReplayingPanesRef } from './replay-guard' @@ -107,8 +108,8 @@ export type PtyConnectionDeps = { directSshRetryAttemptId?: DirectSshPaneRetryAttemptId ) => void markWorktreeUnread: (worktreeId: string) => void - markTerminalTabUnread: (tabId: string) => void - markTerminalPaneUnread: (paneKey: string) => void + markTerminalTabUnread: (tabId: string, reason: AgentAttentionUnreadReason) => void + markTerminalPaneUnread: (paneKey: string, reason: AgentAttentionUnreadReason) => void clearWorktreeUnread: (worktreeId: string) => void clearTerminalTabUnread: (tabId: string) => void clearTerminalPaneUnread: (paneKey: string) => void diff --git a/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts b/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts index 3e52a5ad57c4..ced77bdaa782 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts @@ -229,9 +229,9 @@ export function installPanePtyVisibilityBind(session: ConnectPanePtySession): vo // PTY output here; any product-side suppression should be an explicit UX // decision higher up, not a transport-layer guess. session.deps.markWorktreeUnread(session.deps.worktreeId) - session.deps.markTerminalTabUnread(session.deps.tabId) + session.deps.markTerminalTabUnread(session.deps.tabId, 'terminal-bell') if (useAppStore.getState().settings?.experimentalTerminalAttention === true) { - session.deps.markTerminalPaneUnread(session.cacheKey) + session.deps.markTerminalPaneUnread(session.cacheKey, 'terminal-bell') } // Why: agent CLIs often emit BEL in the same completion burst as their // working->idle title change. Delay only the OS notification so the richer diff --git a/src/renderer/src/components/terminal-pane/terminal-attention-surface.test.ts b/src/renderer/src/components/terminal-pane/terminal-attention-surface.test.ts new file mode 100644 index 000000000000..6cc8ac71bf57 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-attention-surface.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, it } from 'vitest' +import { createTerminalAttentionSurface } from './terminal-attention-surface' +import { createTestStore, makeTab } from '@/store/slices/store-test-helpers' +import { makePaneKey } from '../../../../shared/stable-pane-id' + +const WORKSPACE = 'wt-1' +const TAB = 'tab-1' +const LEAF = '11111111-1111-4111-8111-111111111111' +const OTHER_LEAF = '22222222-2222-4222-8222-222222222222' +const PANE = makePaneKey(TAB, LEAF) + +type TestStore = ReturnType + +function seedLiveTab(): TestStore { + const store = createTestStore() + store.setState({ + tabsByWorktree: { [WORKSPACE]: [makeTab({ id: TAB, worktreeId: WORKSPACE })] }, + ptyIdsByTabId: { [TAB]: ['pty-1'] }, + terminalLayoutsByTabId: { + [TAB]: { + root: { type: 'leaf', leafId: LEAF }, + activeLeafId: LEAF, + expandedLeafId: null, + ptyIdsByLeafId: { [LEAF]: 'pty-1' } + } + } + }) + return store +} + +function surfaceFor(store: TestStore): ReturnType { + return createTerminalAttentionSurface(store.getState()) +} + +describe('createTerminalAttentionSurface', () => { + it('admits a live pane and reports its owning tab as the container', () => { + const surface = surfaceFor(seedLiveTab()) + expect(surface.hasLiveSession({ workspaceId: WORKSPACE, surfaceKey: PANE })).toBe(true) + expect( + surface.admitSurface( + { workspaceId: WORKSPACE, surfaceKey: PANE }, + { hasLiveSession: true, hasFreshActivityEvidence: false } + ) + ).toEqual({ admitted: true, groupId: TAB }) + }) + + it('rejects a leaf the tab layout no longer contains as superseded', () => { + const store = seedLiveTab() + const surface = surfaceFor(store) + expect( + surface.admitSurface( + { workspaceId: WORKSPACE, surfaceKey: makePaneKey(TAB, OTHER_LEAF) }, + { hasLiveSession: true, hasFreshActivityEvidence: false } + ) + ).toEqual({ admitted: false, cause: 'superseded-surface' }) + }) + + it('rejects a surface key that carries no tab id', () => { + const surface = surfaceFor(seedLiveTab()) + expect( + surface.admitSurface( + { workspaceId: WORKSPACE, surfaceKey: 'not-a-pane-key' }, + { hasLiveSession: true, hasFreshActivityEvidence: false } + ) + ).toEqual({ admitted: false, cause: 'unknown-surface' }) + }) + + it('falls back to the known-pane gate when no live pty backs the tab', () => { + const store = seedLiveTab() + store.setState({ ptyIdsByTabId: {} }) + expect( + surfaceFor(store).admitSurface( + { workspaceId: WORKSPACE, surfaceKey: PANE }, + { hasLiveSession: false, hasFreshActivityEvidence: true } + ) + ).toEqual({ admitted: true, groupId: TAB }) + }) + + it('rejects a known pane whose only pty hint is suppressed', () => { + const store = seedLiveTab() + store.setState({ + tabsByWorktree: { + [WORKSPACE]: [makeTab({ id: TAB, worktreeId: WORKSPACE, ptyId: 'pty-1' })] + }, + ptyIdsByTabId: {}, + suppressedPtyExitIds: { 'pty-1': true } + }) + expect( + surfaceFor(store).admitSurface( + { workspaceId: WORKSPACE, surfaceKey: PANE }, + { hasLiveSession: false, hasFreshActivityEvidence: true } + ) + ).toEqual({ admitted: false, cause: 'superseded-surface' }) + }) + + it('resolves the viewed subject from the tab layout active leaf', () => { + expect(surfaceFor(seedLiveTab()).resolveViewedSubjectKey(TAB)).toBe(PANE) + }) + + it('resolves no viewed subject when the active leaf is not a terminal leaf', () => { + const store = seedLiveTab() + store.setState({ + terminalLayoutsByTabId: { + [TAB]: { + root: { type: 'leaf', leafId: 'chat-leaf' }, + activeLeafId: 'chat-leaf', + expandedLeafId: null, + ptyIdsByLeafId: {} + } + } + }) + expect(surfaceFor(store).resolveViewedSubjectKey(TAB)).toBeNull() + }) + + it('counts only this workspace tabs when collecting outstanding attention', () => { + const store = seedLiveTab() + const foreignPane = makePaneKey('tab-elsewhere', OTHER_LEAF) + store.setState({ + unreadAgentCompletionPanes: { [PANE]: 'agent-completion', [foreignPane]: 'agent-completion' }, + unreadTerminalTabs: { [TAB]: 'terminal-bell', 'tab-elsewhere': 'terminal-bell' } + }) + expect(surfaceFor(store).collectWorkspaceAttentionRemainder(WORKSPACE)).toEqual({ + hasSurfaces: true, + unreadSubjectKeys: [PANE], + unreadGroupIds: [TAB] + }) + }) + + it('reports a workspace with no tabs as owning no surfaces', () => { + const store = createTestStore() + expect(surfaceFor(store).collectWorkspaceAttentionRemainder(WORKSPACE)).toEqual({ + hasSurfaces: false, + unreadSubjectKeys: [], + unreadGroupIds: [] + }) + }) + + it('treats only the active leaf of the active tab as viewed', () => { + const store = seedLiveTab() + store.setState({ activeWorktreeId: WORKSPACE, activeTabId: TAB }) + const hidden = createTerminalAttentionSurface(store.getState()) + expect(hidden.isWorkspaceActive(WORKSPACE)).toBe(true) + expect(hidden.isSurfaceViewed({ workspaceId: WORKSPACE, surfaceKey: PANE })).toBe(true) + expect( + hidden.isSurfaceViewed({ + workspaceId: WORKSPACE, + surfaceKey: makePaneKey(TAB, OTHER_LEAF) + }) + ).toBe(false) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/terminal-attention-surface.ts b/src/renderer/src/components/terminal-pane/terminal-attention-surface.ts new file mode 100644 index 000000000000..e200fd549a94 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-attention-surface.ts @@ -0,0 +1,94 @@ +/** + * Terminal implementation of the provider-neutral attention surface. + * + * This module is the only place the PTY/leaf/layout admission predicates are called from; + * the attention policy in `@/attention` reaches terminal state exclusively through it. + */ +import type { useAppStore } from '@/store' +import type { + AgentAttentionRemainder, + AgentAttentionSubject, + AgentAttentionSurface, + AgentAttentionSurfaceAdmission, + AgentAttentionSurfaceSubject, + AgentAttentionLiveness +} from '@/attention/agent-attention-contract' +import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../../../shared/stable-pane-id' +import { + getPaneKeyTabId, + hasLivePtyForNotification, + isCurrentKnownPaneKey, + isCurrentLivePaneKey +} from './terminal-notification-state' +import { + isOrcaWindowForegroundFocused, + isVisibleForegroundPaneKey +} from './terminal-notification-pane-visibility' + +type StoreSnapshot = ReturnType + +function admitTerminalPane( + state: StoreSnapshot, + subject: AgentAttentionSurfaceSubject, + liveness: AgentAttentionLiveness +): AgentAttentionSurfaceAdmission { + const tabId = getPaneKeyTabId(subject.surfaceKey) + if (tabId === null) { + return { admitted: false, cause: 'unknown-surface' } + } + // Why: delayed completion hooks from a closed split pane can arrive while another pane in + // the tab is still live; stale leaf completions must not create unread or OS notifications. + const isCurrentPane = liveness.hasLiveSession + ? isCurrentLivePaneKey(state, subject.workspaceId, subject.surfaceKey) + : isCurrentKnownPaneKey(state, subject.workspaceId, subject.surfaceKey) + return isCurrentPane + ? { admitted: true, groupId: tabId } + : { admitted: false, cause: 'superseded-surface' } +} + +function collectTerminalAttentionRemainder( + state: StoreSnapshot, + workspaceId: string +): AgentAttentionRemainder { + const tabIds = new Set((state.tabsByWorktree[workspaceId] ?? []).map((tab) => tab.id)) + if (tabIds.size === 0) { + return { hasSurfaces: false, unreadSubjectKeys: [], unreadGroupIds: [] } + } + const unreadSubjectKeys: string[] = [] + for (const paneKey of Object.keys(state.unreadAgentCompletionPanes)) { + const parsed = parsePaneKey(paneKey) + if (parsed && tabIds.has(parsed.tabId)) { + unreadSubjectKeys.push(paneKey) + } + } + const unreadGroupIds = Object.keys(state.unreadTerminalTabs).filter((tabId) => tabIds.has(tabId)) + return { hasSurfaces: true, unreadSubjectKeys, unreadGroupIds } +} + +function resolveViewedPaneKey(state: StoreSnapshot, tabId: string): string | null { + const leafId = state.terminalLayoutsByTabId[tabId]?.activeLeafId ?? null + return leafId !== null && isTerminalLeafId(leafId) ? makePaneKey(tabId, leafId) : null +} + +/** Binds the neutral surface contract to one store snapshot. */ +export function createTerminalAttentionSurface(state: StoreSnapshot): AgentAttentionSurface { + return { + // Why: shutdownWorktreeTerminals clears ptyIdsByTabId synchronously before killing PTYs + // asynchronously, so a late timer or accumulated-closure callback still dispatches. + // Checking liveness here catches every phantom source instead of cancelling each one. + hasLiveSession: (subject: AgentAttentionSubject) => + hasLivePtyForNotification(state, subject.workspaceId, subject.surfaceKey), + admitSurface: (subject, liveness) => admitTerminalPane(state, subject, liveness), + // Why: a focused workspace can still hide other tabs and split panes; only the exact + // active leaf counts as already viewed. + isSurfaceViewed: (subject) => + isVisibleForegroundPaneKey(state, subject.workspaceId, subject.surfaceKey), + // Why: activeWorktreeId is in-app selection only. A backgrounded Orca still needs unread. + isWorkspaceViewed: (workspaceId) => + state.activeWorktreeId === workspaceId && isOrcaWindowForegroundFocused(), + isWorkspaceActive: (workspaceId) => state.activeWorktreeId === workspaceId, + resolveViewedSubjectKey: (groupId) => resolveViewedPaneKey(state, groupId), + collectWorkspaceAttentionRemainder: (workspaceId) => + collectTerminalAttentionRemainder(state, workspaceId) + } +} diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-lifecycle-types.ts b/src/renderer/src/components/terminal-pane/terminal-pane-lifecycle-types.ts index bc0a45ac06ce..9a782f98dcfe 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-lifecycle-types.ts +++ b/src/renderer/src/components/terminal-pane/terminal-pane-lifecycle-types.ts @@ -1,3 +1,4 @@ +import type { AgentAttentionUnreadReason } from '@/attention/agent-attention-contract' import type { IDisposable } from '@xterm/xterm' import type { ParsedAgentStatusPayload } from '../../../../shared/agent-status-types' import type { TerminalKittyKeyboardModeTracker } from '../../../../shared/terminal-kitty-keyboard-mode-tracker' @@ -91,8 +92,8 @@ export type UseTerminalPaneLifecycleDeps = { directSshRetryAttemptId?: DirectSshPaneRetryAttemptId ) => void markWorktreeUnread: (worktreeId: string) => void - markTerminalTabUnread: (tabId: string) => void - markTerminalPaneUnread: (paneKey: string) => void + markTerminalTabUnread: (tabId: string, reason: AgentAttentionUnreadReason) => void + markTerminalPaneUnread: (paneKey: string, reason: AgentAttentionUnreadReason) => void clearWorktreeUnread: (worktreeId: string) => void clearTerminalTabUnread: (tabId: string) => void clearTerminalPaneUnread: (paneKey: string) => void diff --git a/src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts b/src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts index f014ccca49fc..71b62046cc57 100644 --- a/src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts +++ b/src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts @@ -1,158 +1,39 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { dispatchTerminalNotification } from './use-notification-dispatch' -import { - AGENT_STATUS_STALE_AFTER_MS, - type AgentStatusEntry -} from '../../../../shared/agent-status-types' -import type { TerminalLayoutSnapshot } from '../../../../shared/terminal-tab-types' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-types' import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' +import { + LIVE_LEAF_ID, + PANE_KEY, + STALE_LEAF_ID, + STALE_PANE_KEY, + getLastNotificationDispatchArg, + makeAgentStatus, + resetNotificationDispatchMockState, + stubDocumentFocus, + type NotificationDispatchMockState +} from './notification-dispatch-test-harness' + +vi.mock('@/store', async () => { + const harness = await import('./notification-dispatch-test-harness') + return harness.createNotificationDispatchStoreModuleMock() +}) -type MockState = { - activeWorktreeId: string | null - activeTabId: string | null - tabsByWorktree: Record - ptyIdsByTabId: Record - suppressedPtyExitIds: Record - terminalLayoutsByTabId: Record - browserTabsByWorktree: Record - retainedAgentsByPaneKey: Record - agentStatusByPaneKey: Record - worktreesByRepo: Record< - string, - { - id: string - repoId: string - displayName?: string - branch?: string - workspaceStatus?: string - }[] - > - repos: { id: string; displayName?: string; connectionId?: string | null }[] - settings: { - experimentalTerminalAttention?: boolean - notifications?: { - enabled?: boolean - customSoundPath?: string | null - customSoundId?: string | null - } - } - markWorktreeUnread: ReturnType - markTerminalTabUnread: ReturnType - markTerminalPaneUnread: ReturnType - markAgentCompletionPaneUnread: ReturnType -} - -const playDesktopNotificationSound = vi.hoisted(() => vi.fn()) -let mockState: MockState - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => mockState - } -})) - -vi.mock('@/lib/desktop-notification-sound', () => ({ - playDesktopNotificationSound -})) - -function makeAgentStatus( - paneKey: string, - overrides: Partial = {} -): AgentStatusEntry { - const now = Date.now() - return { - state: 'done', - prompt: 'codex-hook-notify', - updatedAt: now, - stateStartedAt: now, - agentType: 'codex', - paneKey, - terminalTitle: 'codex', - stateHistory: [], - lastAssistantMessage: 'Done.', - ...overrides - } -} - -function stubDocumentFocus({ - visibilityState, - focused -}: { - visibilityState: DocumentVisibilityState - focused: boolean -}): void { - vi.stubGlobal('document', { - visibilityState, - hasFocus: vi.fn(() => focused) - }) -} - -function getLastNotificationDispatchArg(): Record | undefined { - const dispatch = window.api.notifications.dispatch as unknown as ReturnType - return dispatch.mock.calls.at(-1)?.[0] as Record | undefined -} +vi.mock('@/lib/desktop-notification-sound', async () => { + const harness = await import('./notification-dispatch-test-harness') + return harness.createDesktopNotificationSoundModuleMock() +}) + +let mockState: NotificationDispatchMockState describe('dispatchTerminalNotification', () => { - const liveLeafId = '11111111-1111-4111-8111-111111111111' - const staleLeafId = '22222222-2222-4222-8222-222222222222' - const paneKey = `tab-1:${liveLeafId}` - const stalePaneKey = `tab-1:${staleLeafId}` + const liveLeafId = LIVE_LEAF_ID + const staleLeafId = STALE_LEAF_ID + const paneKey = PANE_KEY + const stalePaneKey = STALE_PANE_KEY beforeEach(() => { - vi.clearAllMocks() - mockState = { - activeWorktreeId: 'wt-secondary', - activeTabId: 'tab-1', - tabsByWorktree: { - 'wt-primary': [{ id: 'tab-1', ptyId: 'pty-1' }] - }, - ptyIdsByTabId: { - 'tab-1': ['pty-1'] - }, - suppressedPtyExitIds: {}, - terminalLayoutsByTabId: { - 'tab-1': { - root: { type: 'leaf', leafId: liveLeafId }, - activeLeafId: liveLeafId, - expandedLeafId: null, - ptyIdsByLeafId: { [liveLeafId]: 'pty-1' } - } - }, - browserTabsByWorktree: {}, - retainedAgentsByPaneKey: {}, - agentStatusByPaneKey: { - [paneKey]: makeAgentStatus(paneKey) - }, - worktreesByRepo: { - repo1: [ - { - id: 'wt-primary', - repoId: 'repo1', - displayName: 'master', - branch: 'master' - }, - { - id: 'wt-secondary', - repoId: 'repo1', - displayName: 'e2e-secondary', - branch: 'e2e-secondary' - } - ] - }, - repos: [{ id: 'repo1', displayName: 'orca', connectionId: null }], - settings: { experimentalTerminalAttention: true, notifications: { customSoundPath: null } }, - markWorktreeUnread: vi.fn(), - markTerminalTabUnread: vi.fn(), - markTerminalPaneUnread: vi.fn(), - markAgentCompletionPaneUnread: vi.fn() - } - vi.stubGlobal('window', { - api: { - notifications: { - dispatch: vi.fn().mockResolvedValue({ delivered: true }) - } - } - }) + mockState = resetNotificationDispatchMockState() }) afterEach(() => { @@ -187,8 +68,8 @@ describe('dispatchTerminalNotification', () => { }) ) expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') - expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'agent-completion') + expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey, 'agent-completion') }) it('builds the notification id from a completion snapshot, not the pinned working row', () => { @@ -301,8 +182,8 @@ describe('dispatchTerminalNotification', () => { }) ) expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') - expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'agent-completion') + expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey, 'agent-completion') }) it('uses tab liveness when the layout has the leaf but no leaf pty binding yet', () => { @@ -322,8 +203,8 @@ describe('dispatchTerminalNotification', () => { }) ) expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') - expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'agent-completion') + expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey, 'agent-completion') }) it('falls back to background-worktree unread when terminal attention is disabled', () => { @@ -339,7 +220,10 @@ describe('dispatchTerminalNotification', () => { expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') expect(mockState.markTerminalTabUnread).not.toHaveBeenCalled() expect(mockState.markTerminalPaneUnread).not.toHaveBeenCalled() - expect(mockState.markAgentCompletionPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockState.markAgentCompletionPaneUnread).toHaveBeenCalledWith( + paneKey, + 'agent-completion' + ) }) it('offers attention-only completion to main for independent mobile delivery', () => { @@ -351,11 +235,44 @@ describe('dispatchTerminalNotification', () => { }) expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') - expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'agent-completion') + expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey, 'agent-completion') + expect(window.api.notifications.dispatch).toHaveBeenCalled() + }) + + it('writes unread with the completion reason while the agent-complete banner toggle is off', () => { + // Why: the renderer never reads the desktop banner gate — main applies it after unread + // and mobile delivery, so a disabled banner must still leave unread + tray attention. + mockState.settings.notifications = { + ...mockState.settings.notifications, + enabled: true, + agentTaskComplete: false + } + + dispatchTerminalNotification('wt-primary', { + source: 'agent-task-complete', + terminalTitle: 'codex', + paneKey + }) + + expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') + expect(mockState.markAgentCompletionPaneUnread).toHaveBeenCalledWith( + paneKey, + 'agent-completion' + ) expect(window.api.notifications.dispatch).toHaveBeenCalled() }) + it('records a bell as a distinct reason and never as an agent completion', () => { + dispatchTerminalNotification('wt-primary', { source: 'terminal-bell', paneKey }) + + expect(mockState.markAgentCompletionPaneUnread).not.toHaveBeenCalled() + expect(mockState.markTerminalTabUnread).not.toHaveBeenCalled() + expect(window.api.notifications.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ source: 'terminal-bell', paneKey }) + ) + }) + it('does not mark the visible focused pane unread', () => { mockState.activeWorktreeId = 'wt-primary' stubDocumentFocus({ visibilityState: 'visible', focused: true }) @@ -397,8 +314,8 @@ describe('dispatchTerminalNotification', () => { expect(window.api.notifications.dispatch).toHaveBeenCalled() expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') - expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-2') - expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(hiddenPaneKey) + expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-2', 'agent-completion') + expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(hiddenPaneKey, 'agent-completion') }) it('marks a hidden split pane in the focused tab unread', () => { @@ -428,8 +345,11 @@ describe('dispatchTerminalNotification', () => { expect(window.api.notifications.dispatch).toHaveBeenCalled() expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') - expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(siblingPaneKey) + expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'agent-completion') + expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith( + siblingPaneKey, + 'agent-completion' + ) }) it('marks the selected worktree unread when Orca is backgrounded', () => { @@ -447,7 +367,10 @@ describe('dispatchTerminalNotification', () => { expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') expect(mockState.markTerminalTabUnread).not.toHaveBeenCalled() expect(mockState.markTerminalPaneUnread).not.toHaveBeenCalled() - expect(mockState.markAgentCompletionPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockState.markAgentCompletionPaneUnread).toHaveBeenCalledWith( + paneKey, + 'agent-completion' + ) }) it('drops a pane key when its tab is hydrated under another worktree', () => { @@ -503,8 +426,8 @@ describe('dispatchTerminalNotification', () => { }) ) expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') - expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'agent-completion') + expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey, 'agent-completion') }) it('uses accepted hook snapshot timing for the notification id when the live store row is gone before dispatch', () => { @@ -542,8 +465,8 @@ describe('dispatchTerminalNotification', () => { }) ) expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') - expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'agent-completion') + expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey, 'agent-completion') }) it('does not let fresh active status suppress a completion from another named agent', () => { @@ -699,8 +622,8 @@ describe('dispatchTerminalNotification', () => { }) ) expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') - expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1', 'agent-completion') + expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey, 'agent-completion') const dispatchArgs = getLastNotificationDispatchArg() expect(dispatchArgs?.agentState).toBeUndefined() expect(dispatchArgs?.agentPrompt).toBeUndefined() 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 3a75ecb16fed..3c4070b44aa2 100644 --- a/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts +++ b/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts @@ -15,17 +15,13 @@ import type { AgentCompletionDispatchMeta, AgentCompletionStatusSnapshot } from './agent-completion-coordinator-types' +import { countReposNeedingNotificationDisambiguation } from './terminal-notification-state' +import { createTerminalAttentionSurface } from './terminal-attention-surface' import { - countReposNeedingNotificationDisambiguation, - getPaneKeyTabId, - hasLivePtyForNotification, - isCurrentKnownPaneKey, - isCurrentLivePaneKey -} from './terminal-notification-state' -import { - isOrcaWindowForegroundFocused, - isVisibleForegroundPaneKey -} from './terminal-notification-pane-visibility' + applyAgentAttention, + resolveAgentAttention, + type AgentAttentionDeliveryRequest +} from '@/attention/agent-attention-policy' const AGENT_NOTIFICATION_SNAPSHOT_MAX_AGE_MS = 10_000 @@ -119,60 +115,23 @@ export function dispatchTerminalNotification( } const agentNotificationStateStartedAt = eventAgentStatusSnapshot?.stateStartedAt ?? freshStoredAgentStatus?.stateStartedAt - // Why: main-process hook IPC can update inactive/unmounted worktrees before - // the renderer's live-PTY map catches up. A fresh accepted hook snapshot is - // authoritative for agent completion; title/BEL-only paths still need PTY liveness. - const hasFreshAgentStatus = Boolean(agentStatus) - - // Why: shutdownWorktreeTerminals clears ptyIdsByTabId synchronously - // before killing PTYs asynchronously. Any notification arriving after - // that point is stale — e.g. a staleTitleTimer that fires 3 s after - // shutdown, or an agent tracker transition from accumulated closure - // state. Checking for live PTYs at dispatch time catches ALL phantom - // notification sources regardless of which timer or callback produced - // them, rather than trying to cancel each one individually. - const hasLivePty = hasLivePtyForNotification(state, worktreeId, event.paneKey) - if (!hasLivePty && !hasFreshAgentStatus) { + const attentionDecision = resolveAgentAttention( + { + subject: { workspaceId: worktreeId, surfaceKey: event.paneKey }, + reason: event.source === 'agent-task-complete' ? 'agent-completion' : 'terminal-bell', + settlesTurn: event.source === 'agent-task-complete', + // Why: main-process hook IPC can update inactive worktrees before the renderer's live-PTY + // map catches up. An accepted fresh hook snapshot is authority that the turn ended; + // title/BEL-only paths still need surface liveness. + hasFreshActivityEvidence: Boolean(agentStatus), + groupAttentionEnabled: state.settings?.experimentalTerminalAttention === true + }, + createTerminalAttentionSurface(state) + ) + if (!attentionDecision.admitted) { return } - if (event.source === 'agent-task-complete') { - const terminalAttentionEnabled = state.settings?.experimentalTerminalAttention === true - let tabId: string | null = null - if (event.paneKey) { - tabId = getPaneKeyTabId(event.paneKey) - // Why: delayed completion hooks from a closed split pane can arrive while - // another pane in the tab is still live; stale leaf completions must not - // create unread state or OS notifications. - const isCurrentPane = hasLivePty - ? isCurrentLivePaneKey(state, worktreeId, event.paneKey) - : isCurrentKnownPaneKey(state, worktreeId, event.paneKey) - if (!tabId || !isCurrentPane) { - return - } - } - - // Why: a focused worktree can still hide other terminal tabs/split panes; - // only the exact active pane counts as already viewed. - const shouldMarkUnread = event.paneKey - ? !isVisibleForegroundPaneKey(state, worktreeId, event.paneKey) - : state.activeWorktreeId !== worktreeId || !isOrcaWindowForegroundFocused() - if (shouldMarkUnread) { - // Why: activeWorktreeId is only in-app selection. If Orca is backgrounded, - // a selected chat finishing still needs unread/Dock attention. - state.markWorktreeUnread(worktreeId) - if (event.paneKey) { - // Why: focus-return auto-ack needs an agent-specific source marker; - // generic pane unread also covers BEL and must still show until interact. - state.markAgentCompletionPaneUnread(event.paneKey) - } - if (terminalAttentionEnabled && tabId && event.paneKey) { - state.markTerminalTabUnread(tabId) - state.markTerminalPaneUnread(event.paneKey) - } - } - } - // Desktop settings are applied in main after independent mobile delivery. // Why: prefer worktree.repoId over string-parsing the worktreeId. The @@ -209,34 +168,46 @@ export function dispatchTerminalNotification( }) : null - void window.api.notifications - .dispatch({ - source: event.source, - ...(notificationId ? { notificationId } : {}), - worktreeId, - paneKey: event.paneKey, - repoLabel: repo?.displayName, - worktreeLabel: worktree?.displayName || worktree?.branch || worktreeId, - hasMultipleActiveRepos: countReposNeedingNotificationDisambiguation(state) > 1, - terminalTitle: event.terminalTitle, - isActiveWorktree: state.activeWorktreeId === worktreeId, - ...agentSnapshot - }) - .then((result) => { - if (result.delivered) { - void playDesktopNotificationSound(customSoundId, customSoundVolume) - return - } - // Why: macOS is silently swallowing notifications (permission off or - // prompt unanswered) — surface an in-app pointer at the fix instead of - // letting the alert vanish without a trace. - if (result.reason === 'blocked-by-system') { - showBlockedNotificationFallbackToast() - } - }) - .catch((err) => { - console.warn('Failed to dispatch notification:', err) - }) + const requestDelivery = (request: AgentAttentionDeliveryRequest): void => { + void window.api.notifications + .dispatch({ + source: event.source, + ...(notificationId ? { notificationId } : {}), + worktreeId: request.workspaceId, + paneKey: request.subjectKey ?? undefined, + repoLabel: repo?.displayName, + worktreeLabel: worktree?.displayName || worktree?.branch || worktreeId, + hasMultipleActiveRepos: countReposNeedingNotificationDisambiguation(state) > 1, + terminalTitle: event.terminalTitle, + isActiveWorktree: request.workspaceIsActive, + ...agentSnapshot + }) + .then((result) => { + if (result.delivered) { + void playDesktopNotificationSound(customSoundId, customSoundVolume) + return + } + // Why: macOS is silently swallowing notifications (permission off or + // prompt unanswered) — surface an in-app pointer at the fix instead of + // letting the alert vanish without a trace. + if (result.reason === 'blocked-by-system') { + showBlockedNotificationFallbackToast() + } + }) + .catch((err) => { + console.warn('Failed to dispatch notification:', err) + }) + } + + applyAgentAttention(attentionDecision, { + unread: { + markWorkspaceUnread: state.markWorktreeUnread, + markSubjectUnread: state.markAgentCompletionPaneUnread, + markGroupUnread: state.markTerminalTabUnread, + markSurfaceUnread: state.markTerminalPaneUnread + }, + requestDelivery + }) } export function useNotificationDispatch( diff --git a/src/renderer/src/components/worktree-jump-palette-recent-inclusion.ts b/src/renderer/src/components/worktree-jump-palette-recent-inclusion.ts index 78e324e90845..61cc3960d07f 100644 --- a/src/renderer/src/components/worktree-jump-palette-recent-inclusion.ts +++ b/src/renderer/src/components/worktree-jump-palette-recent-inclusion.ts @@ -1,3 +1,4 @@ +import type { ReadableAgentAttentionUnread } from '@/attention/agent-attention-contract' import { resolveTerminalTabAttentionBadge, terminalTabHasUnreadActivity @@ -24,8 +25,8 @@ export function shouldIncludeOpenTabInRecentSection({ worktree: Worktree row: OpenTabRecentRow['row'] paneSources: TabPaneInputSources - unreadTerminalTabs: Record - unreadAgentCompletionPanes: Record + unreadTerminalTabs: Record + unreadAgentCompletionPanes: Record now: number }): boolean { if (worktree.isArchived) { diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts index 3f76d71c3777..73fd7574a794 100644 --- a/src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts @@ -39,7 +39,7 @@ beforeEach(() => { useAppStore .getState() .setAgentStatus(pane, { state: 'done', prompt: 'away test', agentType: 'codex' }) - useAppStore.getState().markAgentCompletionPaneUnread(pane) + useAppStore.getState().markAgentCompletionPaneUnread(pane, 'agent-completion') }) afterEach(() => { cleanup() @@ -53,7 +53,7 @@ it('leaves the focused pane unread while desktop is away, then acknowledges on u await act(async () => { await Promise.resolve() }) - expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe('agent-completion') expect(dismiss).not.toHaveBeenCalled() readAway.mockResolvedValue(false) const input = new Event('pointerdown') @@ -78,13 +78,13 @@ it('does not acknowledge when the presence query fails or the hook unmounts', as await act(async () => { resolve(false) }) - expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe('agent-completion') readAway.mockRejectedValue(new Error('unavailable')) renderHook(() => useAutoAckViewedAgent(false)) await act(async () => { await Promise.resolve() }) - expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe('agent-completion') expect(dismiss).not.toHaveBeenCalled() }) @@ -104,7 +104,7 @@ it('keeps native unknown presence conservative', async () => { await act(async () => {}) act(() => window.dispatchEvent(new Event('focus'))) await act(async () => {}) - expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe('agent-completion') expect(dismiss).not.toHaveBeenCalled() }) @@ -115,7 +115,7 @@ it.each(['focus', 'visibilitychange'])('rescans pending web attention on %s', as const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden') renderHook(() => useAutoAckViewedAgent(false)) await act(async () => {}) - expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe('agent-completion') expect(dismiss).not.toHaveBeenCalled() focus.mockReturnValue(true) visibility.mockReturnValue('visible') @@ -138,6 +138,7 @@ it('ignores unrelated writes while away but queries for a new completion', async useAppStore.setState({ unreadAgentCompletionPanes: { [pane]: true } }) }) expect(readAway).toHaveBeenCalledTimes(2) + // An unclassified legacy boolean marker still drives the away query and the ack. expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) readAway.mockResolvedValue(false) await act(async () => window.dispatchEvent(new Event('focus'))) @@ -163,7 +164,7 @@ it('rechecks focus after a pending presence query resolves', async () => { renderHook(() => useAutoAckViewedAgent(false)) vi.mocked(document.hasFocus).mockReturnValue(false) await act(async () => resolve(false)) - expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe('agent-completion') expect(dismiss).not.toHaveBeenCalled() vi.mocked(document.hasFocus).mockReturnValue(true) readAway.mockResolvedValue(false) @@ -183,7 +184,7 @@ it('rechecks the selected pane after a coalesced presence query resolves', async act(() => useAppStore.setState({ activeTabId: 'other-tab' })) expect(readAway).toHaveBeenCalledTimes(1) await act(async () => resolve(false)) - expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe('agent-completion') expect(dismiss).not.toHaveBeenCalled() readAway.mockResolvedValue(false) await act(async () => useAppStore.setState({ activeTabId: 'away-tab' })) diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.clock-skew.test.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.clock-skew.test.ts index 2664536c756b..0fb298472cd8 100644 --- a/src/renderer/src/hooks/useAutoAckViewedAgent.clock-skew.test.ts +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.clock-skew.test.ts @@ -106,7 +106,7 @@ describe('useAutoAckViewedAgent — clock-skewed execution host', () => { renderHook(() => useAutoAckViewedAgent(false)) const calls = instrumentAcknowledgeAgents() - useAppStore.getState().markTerminalTabUnread('tab-unrelated') + useAppStore.getState().markTerminalTabUnread('tab-unrelated', 'terminal-bell') expect(calls).toEqual([]) }) diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.floating-panel.test.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.floating-panel.test.ts index ce19e70b5c45..99ddd3ac249d 100644 --- a/src/renderer/src/hooks/useAutoAckViewedAgent.floating-panel.test.ts +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.floating-panel.test.ts @@ -65,7 +65,7 @@ describe('useAutoAckViewedAgent — floating workspace panel visibility', () => ) // The dot is the only signal a closed panel has, so a store write while hidden must not ack it. - useAppStore.getState().markAgentCompletionPaneUnread(FLOATING_PANE_KEY) + useAppStore.getState().markAgentCompletionPaneUnread(FLOATING_PANE_KEY, 'agent-completion') expect(selectFloatingWorkspaceHasUnread(useAppStore.getState())).toBe(true) hook.rerender({ floatingPanelVisible: true }) @@ -98,8 +98,8 @@ describe('useAutoAckViewedAgent — floating workspace panel visibility', () => { initialProps: { floatingPanelVisible: false } } ) - useAppStore.getState().markAgentCompletionPaneUnread(MAIN_PANE_KEY) - useAppStore.getState().markAgentCompletionPaneUnread(FLOATING_PANE_KEY) + useAppStore.getState().markAgentCompletionPaneUnread(MAIN_PANE_KEY, 'agent-completion') + useAppStore.getState().markAgentCompletionPaneUnread(FLOATING_PANE_KEY, 'agent-completion') expect(selectFloatingWorkspaceHasUnread(useAppStore.getState())).toBe(true) hook.rerender({ floatingPanelVisible: true }) diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.test.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.test.ts index 80769c0334b8..c2925ec1d6c6 100644 --- a/src/renderer/src/hooks/useAutoAckViewedAgent.test.ts +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.test.ts @@ -1,12 +1,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest' +import { resolveAutoAckTabTargets } from './useAutoAckViewedAgent' import { - acknowledgeViewedAgentAttention, - computeAutoAckTargets, + applyAgentAttentionAcknowledgement, + computeAgentAcknowledgementTargets, computeLapsedManualUnreadProtections, - computeViewedAgentCompletionPaneKey, - resolveAutoAckTabTargets, - shouldClearViewedAgentWorktreeUnread -} from './useAutoAckViewedAgent' + resolveViewedUnreadSubjectKey, + shouldClearWorkspaceAttention +} from '@/attention/agent-attention-acknowledgement' +import { createTerminalAttentionSurface } from '@/components/terminal-pane/terminal-attention-surface' import { createTestStore, makeTab } from '../store/slices/store-test-helpers' import { selectFloatingWorkspaceHasUnread } from '../store/selectors' import type { RetainedAgentEntry } from '../store/slices/agent-status' @@ -16,6 +17,21 @@ import { makePaneKey } from '../../../shared/stable-pane-id' const CODEX_LEAF_ID = '11111111-1111-4111-8111-111111111111' const OTHER_LEAF_ID = '22222222-2222-4222-8222-222222222222' +type TestStore = ReturnType + +/** Subject-keyed turn view the neutral acknowledgement policy reads. */ +function ackTargets(store: TestStore, tabId: string, leafId: string): string[] { + const state = store.getState() + return computeAgentAcknowledgementTargets( + { + liveTurns: state.agentStatusByPaneKey, + retainedTurns: state.retainedAgentsByPaneKey, + acknowledgedTurnStartedAt: state.acknowledgedAgentsByPaneKey + }, + makePaneKey(tabId, leafId) + ) +} + // Why: regression coverage for the codex inline-agent row that stayed bold // after returning from another workspace (docs/codex-agent-row-bold-stuck.md). // The race: codex emits `Stop` (state=done), then its TUI title reverts to a @@ -25,12 +41,12 @@ const OTHER_LEAF_ID = '22222222-2222-4222-8222-222222222222' // Pre-fix: useAutoAckViewedAgent only walked the live map, so the retained // row's stateStartedAt > ackAt forever. Fix: walk both maps. // -// We test the pure helper (computeAutoAckTargets) rather than the hook so the +// We test the pure helper (computeAgentAcknowledgementTargets) rather than the hook so the // vitest 'node' environment doesn't need to mock document.visibilityState, // document.hasFocus, or the focus/visibilitychange event surface. The hook's // gate logic is unchanged by this fix — only the scan body was extended. -describe('computeAutoAckTargets — codex retain race regression', () => { +describe('computeAgentAcknowledgementTargets — codex retain race regression', () => { afterEach(() => { vi.useRealTimers() }) @@ -83,9 +99,9 @@ describe('computeAutoAckTargets — codex retain race regression', () => { store.getState().retainAgents([retentionSnapshot]) expect(store.getState().retainedAgentsByPaneKey[paneKey]).toBeDefined() - // 5. The user is back on the codex tab. computeAutoAckTargets must see + // 5. The user is back on the codex tab. computeAgentAcknowledgementTargets must see // the retained row and surface it for ack — pre-fix this returned []. - const targets = computeAutoAckTargets(store.getState(), activeTabId, CODEX_LEAF_ID) + const targets = ackTargets(store, activeTabId, CODEX_LEAF_ID) expect(targets).toEqual([paneKey]) }) @@ -114,14 +130,14 @@ describe('computeAutoAckTargets — codex retain race regression', () => { store.getState().removeAgentStatus(paneKey) // First scan: the retained row is unvisited. - expect(computeAutoAckTargets(store.getState(), activeTabId, CODEX_LEAF_ID)).toEqual([paneKey]) + expect(ackTargets(store, activeTabId, CODEX_LEAF_ID)).toEqual([paneKey]) // Simulate the ack effect. vi.setSystemTime(new Date('2026-05-05T12:00:01.000Z')) store.getState().acknowledgeAgents([paneKey]) // Second scan: idempotent — nothing to ack. - expect(computeAutoAckTargets(store.getState(), activeTabId, CODEX_LEAF_ID)).toEqual([]) + expect(ackTargets(store, activeTabId, CODEX_LEAF_ID)).toEqual([]) }) it('skips retained rows whose paneKey is on a different tab', () => { @@ -147,7 +163,7 @@ describe('computeAutoAckTargets — codex retain race regression', () => { // Active tab differs — the retained row must NOT be acked while the user // is looking at a different tab; the bold-until-viewed signal must // survive the tab switch. - expect(computeAutoAckTargets(store.getState(), 'tab-codex', CODEX_LEAF_ID)).toEqual([]) + expect(ackTargets(store, 'tab-codex', CODEX_LEAF_ID)).toEqual([]) }) it('skips sibling panes in the same terminal tab', () => { @@ -167,9 +183,7 @@ describe('computeAutoAckTargets — codex retain race regression', () => { agentType: 'claude' }) - expect(computeAutoAckTargets(store.getState(), activeTabId, CODEX_LEAF_ID)).toEqual([ - activePaneKey - ]) + expect(ackTargets(store, activeTabId, CODEX_LEAF_ID)).toEqual([activePaneKey]) }) it('acks a paneKey present in BOTH live and retained without throwing', () => { @@ -200,7 +214,7 @@ describe('computeAutoAckTargets — codex retain race regression', () => { } ]) - const targets = computeAutoAckTargets(store.getState(), activeTabId, CODEX_LEAF_ID) + const targets = ackTargets(store, activeTabId, CODEX_LEAF_ID) // Two pushes, same paneKey — duplicates are intentional and harmless; // acknowledgeAgents short-circuits per key. expect(targets.length).toBeLessThanOrEqual(2) @@ -209,100 +223,91 @@ describe('computeAutoAckTargets — codex retain race regression', () => { }) }) -describe('acknowledgeViewedAgentAttention', () => { +describe('applyAgentAttentionAcknowledgement', () => { it('acks the visible agent and clears unread worktree/tab/pane attention', () => { const actions = { - acknowledgeAgents: vi.fn(), - clearWorktreeUnread: vi.fn(), - clearTerminalTabUnread: vi.fn(), - clearTerminalPaneUnread: vi.fn() + acknowledgeSubjects: vi.fn(), + clearWorkspaceUnread: vi.fn(), + clearGroupUnread: vi.fn(), + clearSubjectUnread: vi.fn() } const paneKey = makePaneKey('tab-1', CODEX_LEAF_ID) - acknowledgeViewedAgentAttention(actions, { - activeWorktreeId: 'wt-1', - activeTabId: 'tab-1', - paneKeys: [paneKey] + applyAgentAttentionAcknowledgement(actions, { + workspaceIdToClear: 'wt-1', + viewedGroupId: 'tab-1', + subjectKeys: [paneKey] }) - expect(actions.acknowledgeAgents).toHaveBeenCalledWith([paneKey]) - expect(actions.clearWorktreeUnread).toHaveBeenCalledWith('wt-1') - expect(actions.clearTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(actions.clearTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(actions.acknowledgeSubjects).toHaveBeenCalledWith([paneKey]) + expect(actions.clearWorkspaceUnread).toHaveBeenCalledWith('wt-1') + expect(actions.clearGroupUnread).toHaveBeenCalledWith('tab-1') + expect(actions.clearSubjectUnread).toHaveBeenCalledWith(paneKey) }) it('does nothing when there are no visible agent targets', () => { const actions = { - acknowledgeAgents: vi.fn(), - clearWorktreeUnread: vi.fn(), - clearTerminalTabUnread: vi.fn(), - clearTerminalPaneUnread: vi.fn() + acknowledgeSubjects: vi.fn(), + clearWorkspaceUnread: vi.fn(), + clearGroupUnread: vi.fn(), + clearSubjectUnread: vi.fn() } - acknowledgeViewedAgentAttention(actions, { - activeWorktreeId: 'wt-1', - activeTabId: 'tab-1', - paneKeys: [] + applyAgentAttentionAcknowledgement(actions, { + workspaceIdToClear: 'wt-1', + viewedGroupId: 'tab-1', + subjectKeys: [] }) - expect(actions.acknowledgeAgents).not.toHaveBeenCalled() - expect(actions.clearWorktreeUnread).not.toHaveBeenCalled() - expect(actions.clearTerminalTabUnread).not.toHaveBeenCalled() - expect(actions.clearTerminalPaneUnread).not.toHaveBeenCalled() + expect(actions.acknowledgeSubjects).not.toHaveBeenCalled() + expect(actions.clearWorkspaceUnread).not.toHaveBeenCalled() + expect(actions.clearGroupUnread).not.toHaveBeenCalled() + expect(actions.clearSubjectUnread).not.toHaveBeenCalled() }) it('clears visible pane unread even when there is no agent row to acknowledge', () => { const actions = { - acknowledgeAgents: vi.fn(), - clearWorktreeUnread: vi.fn(), - clearTerminalTabUnread: vi.fn(), - clearTerminalPaneUnread: vi.fn() + acknowledgeSubjects: vi.fn(), + clearWorkspaceUnread: vi.fn(), + clearGroupUnread: vi.fn(), + clearSubjectUnread: vi.fn() } const paneKey = makePaneKey('tab-1', CODEX_LEAF_ID) - acknowledgeViewedAgentAttention(actions, { - activeWorktreeId: 'wt-1', - activeTabId: 'tab-1', - paneKeys: [], - activePaneKey: paneKey + applyAgentAttentionAcknowledgement(actions, { + workspaceIdToClear: 'wt-1', + viewedGroupId: 'tab-1', + subjectKeys: [], + viewedUnreadSubjectKey: paneKey }) - expect(actions.acknowledgeAgents).not.toHaveBeenCalled() - expect(actions.clearWorktreeUnread).toHaveBeenCalledWith('wt-1') - expect(actions.clearTerminalTabUnread).toHaveBeenCalledWith('tab-1') - expect(actions.clearTerminalPaneUnread).toHaveBeenCalledWith(paneKey) + expect(actions.acknowledgeSubjects).not.toHaveBeenCalled() + expect(actions.clearWorkspaceUnread).toHaveBeenCalledWith('wt-1') + expect(actions.clearGroupUnread).toHaveBeenCalledWith('tab-1') + expect(actions.clearSubjectUnread).toHaveBeenCalledWith(paneKey) }) }) -describe('computeViewedAgentCompletionPaneKey', () => { +describe('resolveViewedUnreadSubjectKey', () => { it('returns the exact active pane unread marker', () => { const paneKey = makePaneKey('tab-1', CODEX_LEAF_ID) - expect( - computeViewedAgentCompletionPaneKey( - { - unreadAgentCompletionPanes: { - [paneKey]: true - } - }, - 'tab-1', - CODEX_LEAF_ID - ) - ).toBe(paneKey) + expect(resolveViewedUnreadSubjectKey({ [paneKey]: 'agent-completion' }, paneKey)).toBe(paneKey) + }) + + it('reads an unclassified legacy boolean marker as unread', () => { + const paneKey = makePaneKey('tab-1', CODEX_LEAF_ID) + + expect(resolveViewedUnreadSubjectKey({ [paneKey]: true }, paneKey)).toBe(paneKey) }) it('skips unread markers for hidden sibling panes', () => { const siblingPaneKey = makePaneKey('tab-1', OTHER_LEAF_ID) expect( - computeViewedAgentCompletionPaneKey( - { - unreadAgentCompletionPanes: { - [siblingPaneKey]: true - } - }, - 'tab-1', - CODEX_LEAF_ID + resolveViewedUnreadSubjectKey( + { [siblingPaneKey]: 'agent-completion' }, + makePaneKey('tab-1', CODEX_LEAF_ID) ) ).toBeNull() }) @@ -313,74 +318,88 @@ describe('agent completion pane unread store marker', () => { const store = createTestStore() const paneKey = makePaneKey('tab-1', CODEX_LEAF_ID) - store.getState().markAgentCompletionPaneUnread(paneKey) - expect(store.getState().unreadAgentCompletionPanes).toEqual({ [paneKey]: true }) + store.getState().markAgentCompletionPaneUnread(paneKey, 'agent-completion') + expect(store.getState().unreadAgentCompletionPanes).toEqual({ + [paneKey]: 'agent-completion' + }) store.getState().clearTerminalPaneUnread(paneKey) expect(store.getState().unreadAgentCompletionPanes).toEqual({}) }) }) -describe('shouldClearViewedAgentWorktreeUnread', () => { +describe('shouldClearWorkspaceAttention through the terminal surface', () => { + function seedWorkspace(seed: { + tabIds: string[] + unreadAgentCompletionPanes: Record + unreadTerminalTabs?: Record + }): TestStore { + const store = createTestStore() + store.setState({ + tabsByWorktree: { + 'wt-1': seed.tabIds.map((id) => makeTab({ id, worktreeId: 'wt-1' })) + }, + unreadAgentCompletionPanes: seed.unreadAgentCompletionPanes, + unreadTerminalTabs: seed.unreadTerminalTabs ?? {} + }) + return store + } + + function clearsWorkspace(store: TestStore, clearedSubjectKeys: Set): boolean { + const surface = createTerminalAttentionSurface(store.getState()) + return shouldClearWorkspaceAttention(surface.collectWorkspaceAttentionRemainder('wt-1'), { + viewedGroupId: 'tab-1', + clearedSubjectKeys + }) + } + it('clears worktree unread when the visible pane owns the only agent source', () => { const paneKey = makePaneKey('tab-1', CODEX_LEAF_ID) + const store = seedWorkspace({ + tabIds: ['tab-1'], + unreadAgentCompletionPanes: { [paneKey]: 'agent-completion' } + }) - expect( - shouldClearViewedAgentWorktreeUnread( - { - tabsByWorktree: { 'wt-1': [{ id: 'tab-1' }] }, - unreadAgentCompletionPanes: { [paneKey]: true }, - unreadTerminalTabs: {} - }, - { - activeWorktreeId: 'wt-1', - activeTabId: 'tab-1', - paneKeysToClear: new Set([paneKey]) - } - ) - ).toBe(true) + expect(clearsWorkspace(store, new Set([paneKey]))).toBe(true) }) it('keeps worktree unread when a hidden tab still owns agent attention', () => { const activePaneKey = makePaneKey('tab-1', CODEX_LEAF_ID) const hiddenPaneKey = makePaneKey('tab-2', OTHER_LEAF_ID) + const store = seedWorkspace({ + tabIds: ['tab-1', 'tab-2'], + unreadAgentCompletionPanes: { + [activePaneKey]: 'agent-completion', + [hiddenPaneKey]: 'agent-completion' + } + }) - expect( - shouldClearViewedAgentWorktreeUnread( - { - tabsByWorktree: { 'wt-1': [{ id: 'tab-1' }, { id: 'tab-2' }] }, - unreadAgentCompletionPanes: { - [activePaneKey]: true, - [hiddenPaneKey]: true - }, - unreadTerminalTabs: {} - }, - { - activeWorktreeId: 'wt-1', - activeTabId: 'tab-1', - paneKeysToClear: new Set([activePaneKey]) - } - ) - ).toBe(false) + expect(clearsWorkspace(store, new Set([activePaneKey]))).toBe(false) }) it('keeps worktree unread when a hidden tab has terminal unread attention', () => { const activePaneKey = makePaneKey('tab-1', CODEX_LEAF_ID) + const store = seedWorkspace({ + tabIds: ['tab-1', 'tab-2'], + unreadAgentCompletionPanes: { [activePaneKey]: 'agent-completion' }, + unreadTerminalTabs: { 'tab-2': 'terminal-bell' } + }) - expect( - shouldClearViewedAgentWorktreeUnread( - { - tabsByWorktree: { 'wt-1': [{ id: 'tab-1' }, { id: 'tab-2' }] }, - unreadAgentCompletionPanes: { [activePaneKey]: true }, - unreadTerminalTabs: { 'tab-2': true } - }, - { - activeWorktreeId: 'wt-1', - activeTabId: 'tab-1', - paneKeysToClear: new Set([activePaneKey]) - } - ) - ).toBe(false) + expect(clearsWorkspace(store, new Set([activePaneKey]))).toBe(false) + }) + + it('ignores unread panes owned by another workspace', () => { + const activePaneKey = makePaneKey('tab-1', CODEX_LEAF_ID) + const foreignPaneKey = makePaneKey('tab-elsewhere', OTHER_LEAF_ID) + const store = seedWorkspace({ + tabIds: ['tab-1'], + unreadAgentCompletionPanes: { + [activePaneKey]: 'agent-completion', + [foreignPaneKey]: 'agent-completion' + } + }) + + expect(clearsWorkspace(store, new Set([activePaneKey]))).toBe(true) }) }) @@ -460,30 +479,42 @@ describe('floating workspace auto-ack against the attention dot', () => { ] } }) - store.getState().markAgentCompletionPaneUnread(floatingPaneKey) + store.getState().markAgentCompletionPaneUnread(floatingPaneKey, 'agent-completion') return store } - function runAutoAckScan( - store: ReturnType, - floatingPanelVisible: boolean - ): void { + function runAutoAckScan(store: TestStore, floatingPanelVisible: boolean): void { const state = store.getState() for (const target of resolveAutoAckTabTargets(state, { floatingPanelVisible })) { - const activePaneKey = computeViewedAgentCompletionPaneKey(state, target.tabId, CODEX_LEAF_ID) - const paneKeysToClear = new Set(activePaneKey ? [activePaneKey] : []) - acknowledgeViewedAgentAttention(store.getState(), { - activeWorktreeId: shouldClearViewedAgentWorktreeUnread(store.getState(), { - activeWorktreeId: target.worktreeId, - activeTabId: target.tabId, - paneKeysToClear - }) - ? target.worktreeId - : null, - activeTabId: target.tabId, - paneKeys: [], - activePaneKey - }) + const current = store.getState() + const surface = createTerminalAttentionSurface(current) + const viewedUnreadSubjectKey = resolveViewedUnreadSubjectKey( + current.unreadAgentCompletionPanes, + makePaneKey(target.tabId, CODEX_LEAF_ID) + ) + const clearedSubjectKeys = new Set(viewedUnreadSubjectKey ? [viewedUnreadSubjectKey] : []) + const workspaceId = target.worktreeId + applyAgentAttentionAcknowledgement( + { + acknowledgeSubjects: current.acknowledgeAgents, + clearWorkspaceUnread: current.clearWorktreeUnread, + clearGroupUnread: current.clearTerminalTabUnread, + clearSubjectUnread: current.clearTerminalPaneUnread + }, + { + workspaceIdToClear: + workspaceId !== null && + shouldClearWorkspaceAttention(surface.collectWorkspaceAttentionRemainder(workspaceId), { + viewedGroupId: target.tabId, + clearedSubjectKeys + }) + ? workspaceId + : null, + viewedGroupId: target.tabId, + subjectKeys: [], + viewedUnreadSubjectKey + } + ) } } @@ -514,9 +545,9 @@ describe('computeLapsedManualUnreadProtections', () => { // scan in that window must not treat "no row yet" as "the agent moved on". const lapsed = computeLapsedManualUnreadProtections( { - agentStatusByPaneKey: {}, - retainedAgentsByPaneKey: {}, - manuallyUnreadTurnsByPaneKey: { [paneKey]: 1_000 } + liveTurns: {}, + retainedTurns: {}, + manuallyUnreadTurnStartedAt: { [paneKey]: 1_000 } }, new Set([paneKey]) ) @@ -529,8 +560,9 @@ describe('computeLapsedManualUnreadProtections', () => { const turn = store.getState().agentStatusByPaneKey[paneKey]!.stateStartedAt const lapsed = computeLapsedManualUnreadProtections( { - ...store.getState(), - manuallyUnreadTurnsByPaneKey: { [paneKey]: turn - 1, [otherPaneKey]: 5 } + liveTurns: store.getState().agentStatusByPaneKey, + retainedTurns: store.getState().retainedAgentsByPaneKey, + manuallyUnreadTurnStartedAt: { [paneKey]: turn - 1, [otherPaneKey]: 5 } }, new Set([paneKey]) ) @@ -542,7 +574,11 @@ describe('computeLapsedManualUnreadProtections', () => { store.getState().setAgentStatus(paneKey, { state: 'done', prompt: 'p', agentType: 'claude' }) const turn = store.getState().agentStatusByPaneKey[paneKey]!.stateStartedAt const lapsed = computeLapsedManualUnreadProtections( - { ...store.getState(), manuallyUnreadTurnsByPaneKey: { [paneKey]: turn } }, + { + liveTurns: store.getState().agentStatusByPaneKey, + retainedTurns: store.getState().retainedAgentsByPaneKey, + manuallyUnreadTurnStartedAt: { [paneKey]: turn } + }, new Set([paneKey]) ) expect(lapsed).toEqual([]) diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.ts index 7da0993cdaf2..6dba315b1cb7 100644 --- a/src/renderer/src/hooks/useAutoAckViewedAgent.ts +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.ts @@ -8,191 +8,25 @@ import { import { useAppStore } from '@/store' import { isWebClientLocation } from '@/lib/web-client-location' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import type { AgentStatusEntry } from '../../../shared/agent-status-types' -import type { RetainedAgentEntry } from '@/store/slices/agent-status' -import type { TerminalLayoutSnapshot } from '../../../shared/terminal-tab-types' -import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../../shared/stable-pane-id' - -function resolveActiveLeafId( - state: { terminalLayoutsByTabId: Record }, - activeTabId: string -): string | null { - const leafId = state.terminalLayoutsByTabId[activeTabId]?.activeLeafId ?? null - return leafId && isTerminalLeafId(leafId) ? leafId : null -} - -/** - * Returns paneKeys to ack for the active tab/leaf; exported for the - * codex-row-bold regression test (docs/codex-agent-row-bold-stuck.md). - * - * Why: split tabs host multiple agent panes, so match exact `${tabId}:${leafId}` — a tab-prefix match would ack undisplayed siblings. - */ -export function computeAutoAckTargets( - state: { - agentStatusByPaneKey: Record - retainedAgentsByPaneKey: Record - acknowledgedAgentsByPaneKey: Record - }, - activeTabId: string, - activeLeafId: string | null -): string[] { - if (!activeLeafId || !isTerminalLeafId(activeLeafId)) { - return [] - } - const targetKey = makePaneKey(activeTabId, activeLeafId) - const targets: string[] = [] - const liveEntry = state.agentStatusByPaneKey[targetKey] - if (liveEntry) { - const ackAt = state.acknowledgedAgentsByPaneKey[targetKey] ?? 0 - // Why: compare stateStartedAt (not updatedAt) so same-state pings don't re-trigger ack, matching WorktreeCardAgents' is-unvisited rule. - if (ackAt < liveEntry.stateStartedAt) { - targets.push(targetKey) - } - } - const retained = state.retainedAgentsByPaneKey[targetKey] - if (retained) { - const ackAt = state.acknowledgedAgentsByPaneKey[targetKey] ?? 0 - if (ackAt < retained.entry.stateStartedAt) { - targets.push(targetKey) - } - } - return targets -} - -export function computeViewedAgentCompletionPaneKey( - state: { - unreadAgentCompletionPanes: Record - }, - activeTabId: string, - activeLeafId: string | null -): string | null { - if (!activeLeafId || !isTerminalLeafId(activeLeafId)) { - return null - } - - const targetKey = makePaneKey(activeTabId, activeLeafId) - return state.unreadAgentCompletionPanes[targetKey] ? targetKey : null -} - -function getAgentTurnTimestamp( - state: { - agentStatusByPaneKey: Record - retainedAgentsByPaneKey: Record - }, - paneKey: string -): number | null { - return ( - state.agentStatusByPaneKey[paneKey]?.stateStartedAt ?? - state.retainedAgentsByPaneKey[paneKey]?.entry.stateStartedAt ?? - null - ) -} - -export function shouldClearViewedAgentWorktreeUnread( - state: { - tabsByWorktree: Record - unreadAgentCompletionPanes: Record - unreadTerminalTabs: Record - }, - args: { - activeWorktreeId: string | null - activeTabId: string - paneKeysToClear: Set - } -): boolean { - if (!args.activeWorktreeId) { - return false - } - - const tabIds = new Set((state.tabsByWorktree[args.activeWorktreeId] ?? []).map((tab) => tab.id)) - if (tabIds.size === 0) { - return true - } - - // Why: worktree unread is coarse — don't clear for the visible pane if a hidden tab/pane in the same worktree still owns unread attention. - for (const paneKey of Object.keys(state.unreadAgentCompletionPanes)) { - if (args.paneKeysToClear.has(paneKey)) { - continue - } - const parsed = parsePaneKey(paneKey) - if (parsed && tabIds.has(parsed.tabId)) { - return false - } - } - - for (const tabId of Object.keys(state.unreadTerminalTabs)) { - if (tabId !== args.activeTabId && tabIds.has(tabId)) { - return false - } - } - - return true -} - -/** - * Manual mark-unread protections that no longer apply: the user moved to another pane, or the - * agent took a new turn. Exported for the startup-race test. - */ -export function computeLapsedManualUnreadProtections( - state: { - agentStatusByPaneKey: Record - retainedAgentsByPaneKey: Record - manuallyUnreadTurnsByPaneKey: Record - }, - activePaneKeys: ReadonlySet -): string[] { - const lapsed: string[] = [] - for (const [paneKey, turnTimestamp] of Object.entries(state.manuallyUnreadTurnsByPaneKey)) { - if (!activePaneKeys.has(paneKey)) { - lapsed.push(paneKey) - continue - } - const currentTurn = getAgentTurnTimestamp(state, paneKey) - // Why keep on null: persisted UI hydrates before the status snapshot lands, so an active - // pane with no row yet is "not known", not "moved on"; wiping it would lose the mark-unread - // the user made before relaunch. - if (currentTurn !== null && currentTurn !== turnTimestamp) { - lapsed.push(paneKey) - } - } - return lapsed -} - -type ViewedAgentAttentionActions = { - acknowledgeAgents: (paneKeys: string[]) => void - clearWorktreeUnread: (worktreeId: string) => void - clearTerminalTabUnread: (tabId: string) => void - clearTerminalPaneUnread: (paneKey: string) => void -} - -export function acknowledgeViewedAgentAttention( - state: ViewedAgentAttentionActions, - args: { - activeWorktreeId: string | null - activeTabId: string - paneKeys: string[] - activePaneKey?: string | null - } -): void { - const paneKeysToClear = new Set(args.paneKeys) - if (args.activePaneKey) { - paneKeysToClear.add(args.activePaneKey) - } - - if (args.paneKeys.length === 0 && paneKeysToClear.size === 0) { - return - } - - if (args.paneKeys.length > 0) { - state.acknowledgeAgents(args.paneKeys) - } - if (args.activeWorktreeId) { - // Why: the selected agent is now visible, so clear the Dock-driving worktree unread without a click. - state.clearWorktreeUnread(args.activeWorktreeId) - } - state.clearTerminalTabUnread(args.activeTabId) - for (const paneKey of paneKeysToClear) { - state.clearTerminalPaneUnread(paneKey) +import { createTerminalAttentionSurface } from '@/components/terminal-pane/terminal-attention-surface' +import { + applyAgentAttentionAcknowledgement, + computeAgentAcknowledgementTargets, + computeLapsedManualUnreadProtections, + readAgentAttentionTurnStartedAt, + resolveViewedUnreadSubjectKey, + shouldClearWorkspaceAttention, + type AgentAttentionTurnRecords +} from '@/attention/agent-attention-acknowledgement' + +type StoreSnapshot = ReturnType + +/** Subject-keyed view of the store's turn bookkeeping for the neutral acknowledgement policy. */ +function readTurnRecords(state: StoreSnapshot): AgentAttentionTurnRecords { + return { + liveTurns: state.agentStatusByPaneKey, + retainedTurns: state.retainedAgentsByPaneKey, + acknowledgedTurnStartedAt: state.acknowledgedAgentsByPaneKey } } @@ -261,6 +95,7 @@ export function useAutoAckViewedAgent(floatingPanelVisible: boolean): void { const targets = resolveAutoAckTabTargets(s, { floatingPanelVisible: floatingPanelVisibleRef.current }) + const surface = createTerminalAttentionSurface(s) // Why no protection reset here: zero targets just means nothing is on screen // (Settings, browser, an overlay) — a transient view switch must not lapse an // explicit mark-unread the user just made. @@ -269,11 +104,12 @@ export function useAutoAckViewedAgent(floatingPanelVisible: boolean): void { } // Browsers have no native idle capability; their visible/focused gates still apply. if (!options?.presenceConfirmed && !isWebClientLocation()) { + const records = readTurnRecords(s) const hasAttention = targets.some(({ tabId }) => { - const leafId = resolveActiveLeafId(s, tabId) + const subjectKey = surface.resolveViewedSubjectKey(tabId) return ( - computeAutoAckTargets(s, tabId, leafId).length > 0 || - computeViewedAgentCompletionPaneKey(s, tabId, leafId) !== null + computeAgentAcknowledgementTargets(records, subjectKey).length > 0 || + resolveViewedUnreadSubjectKey(s.unreadAgentCompletionPanes, subjectKey) !== null ) }) if (hasAttention) { @@ -282,16 +118,23 @@ export function useAutoAckViewedAgent(floatingPanelVisible: boolean): void { } } - const activePaneKeys = new Set() + const activeSubjectKeys = new Set() for (const target of targets) { - const activeLeafId = resolveActiveLeafId(s, target.tabId) - if (activeLeafId) { - activePaneKeys.add(makePaneKey(target.tabId, activeLeafId)) + const subjectKey = surface.resolveViewedSubjectKey(target.tabId) + if (subjectKey) { + activeSubjectKeys.add(subjectKey) } } - // Protection lapses when the user moves on to another pane or the agent takes a new - // turn; a still-active pane with an unchanged turn keeps its explicit mark-unread. - const lapsedProtections = computeLapsedManualUnreadProtections(s, activePaneKeys) + // Protection lapses when the user moves on to another subject or the agent takes a new + // turn; a still-active subject with an unchanged turn keeps its explicit mark-unread. + const lapsedProtections = computeLapsedManualUnreadProtections( + { + liveTurns: s.agentStatusByPaneKey, + retainedTurns: s.retainedAgentsByPaneKey, + manuallyUnreadTurnStartedAt: s.manuallyUnreadTurnsByPaneKey + }, + activeSubjectKeys + ) if (lapsedProtections.length > 0) { s.clearManuallyUnreadTurns(lapsedProtections) } @@ -300,32 +143,46 @@ export function useAutoAckViewedAgent(floatingPanelVisible: boolean): void { // Why re-read: acking target[0] writes to the store, which re-enters this scan synchronously // and may already have handled target[1]; `s` is a pre-write snapshot that would re-ack it. const current = useAppStore.getState() - const tabId = target.tabId - const activeLeafId = resolveActiveLeafId(current, tabId) - const toAck = computeAutoAckTargets(current, tabId, activeLeafId).filter( - (paneKey) => - current.manuallyUnreadTurnsByPaneKey[paneKey] !== - getAgentTurnTimestamp(current, paneKey) + const currentSurface = createTerminalAttentionSurface(current) + const currentRecords = readTurnRecords(current) + const groupId = target.tabId + const subjectKey = currentSurface.resolveViewedSubjectKey(groupId) + const toAck = computeAgentAcknowledgementTargets(currentRecords, subjectKey).filter( + (key) => + current.manuallyUnreadTurnsByPaneKey[key] !== + readAgentAttentionTurnStartedAt(currentRecords, key) ) - const activePaneKey = computeViewedAgentCompletionPaneKey(current, tabId, activeLeafId) - if (toAck.length > 0 || activePaneKey) { - const paneKeysToClear = new Set(toAck) - if (activePaneKey) { - paneKeysToClear.add(activePaneKey) + const viewedUnreadSubjectKey = resolveViewedUnreadSubjectKey( + current.unreadAgentCompletionPanes, + subjectKey + ) + if (toAck.length > 0 || viewedUnreadSubjectKey) { + const clearedSubjectKeys = new Set(toAck) + if (viewedUnreadSubjectKey) { + clearedSubjectKeys.add(viewedUnreadSubjectKey) } - const worktreeId = target.worktreeId - acknowledgeViewedAgentAttention(current, { - activeWorktreeId: shouldClearViewedAgentWorktreeUnread(current, { - activeWorktreeId: worktreeId, - activeTabId: tabId, - paneKeysToClear - }) - ? worktreeId - : null, - activeTabId: tabId, - paneKeys: toAck, - activePaneKey - }) + const workspaceId = target.worktreeId + applyAgentAttentionAcknowledgement( + { + acknowledgeSubjects: current.acknowledgeAgents, + clearWorkspaceUnread: current.clearWorktreeUnread, + clearGroupUnread: current.clearTerminalTabUnread, + clearSubjectUnread: current.clearTerminalPaneUnread + }, + { + workspaceIdToClear: + workspaceId !== null && + shouldClearWorkspaceAttention( + currentSurface.collectWorkspaceAttentionRemainder(workspaceId), + { viewedGroupId: groupId, clearedSubjectKeys } + ) + ? workspaceId + : null, + viewedGroupId: groupId, + subjectKeys: toAck, + viewedUnreadSubjectKey + } + ) } } } diff --git a/src/renderer/src/lib/unread-badge-count.ts b/src/renderer/src/lib/unread-badge-count.ts index 4995615971d9..50e04f61eee2 100644 --- a/src/renderer/src/lib/unread-badge-count.ts +++ b/src/renderer/src/lib/unread-badge-count.ts @@ -1,3 +1,4 @@ +import type { StoredAgentAttentionUnread } from '@/attention/agent-attention-contract' import type { TerminalTab } from '../../../shared/terminal-tab-types' import type { Worktree } from '../../../shared/worktree/types' @@ -8,7 +9,7 @@ export type UnreadBadgeTab = Pick export type UnreadBadgeCountSources = { worktreesByRepo: Readonly> tabsByWorktree: Readonly> - unreadTerminalTabs: Readonly> + unreadTerminalTabs: Readonly> } export function getUnreadBadgeCount({ diff --git a/src/renderer/src/store/slices/agent-status-ack-cleanup.test.ts b/src/renderer/src/store/slices/agent-status-ack-cleanup.test.ts index 773e3879aba0..e3d276a05c40 100644 --- a/src/renderer/src/store/slices/agent-status-ack-cleanup.test.ts +++ b/src/renderer/src/store/slices/agent-status-ack-cleanup.test.ts @@ -185,8 +185,8 @@ describe('acknowledgeAgents clears the unread agent-completion marker', () => { it('drops the pane from unreadAgentCompletionPanes', () => { const store = createTestStore() store.getState().setAgentStatus('tab-1:0', { state: 'done', prompt: 'p', agentType: 'claude' }) - store.getState().markAgentCompletionPaneUnread('tab-1:0') - expect(store.getState().unreadAgentCompletionPanes['tab-1:0']).toBe(true) + store.getState().markAgentCompletionPaneUnread('tab-1:0', 'agent-completion') + expect(store.getState().unreadAgentCompletionPanes['tab-1:0']).toBe('agent-completion') store.getState().acknowledgeAgents(['tab-1:0']) @@ -195,14 +195,14 @@ describe('acknowledgeAgents clears the unread agent-completion marker', () => { it('leaves other panes and the terminal-bell unread map untouched', () => { const store = createTestStore() - store.getState().markAgentCompletionPaneUnread('tab-1:0') - store.getState().markAgentCompletionPaneUnread('tab-2:0') - store.getState().markTerminalPaneUnread('tab-1:0') + store.getState().markAgentCompletionPaneUnread('tab-1:0', 'agent-completion') + store.getState().markAgentCompletionPaneUnread('tab-2:0', 'agent-completion') + store.getState().markTerminalPaneUnread('tab-1:0', 'terminal-bell') store.getState().acknowledgeAgents(['tab-1:0']) - expect(store.getState().unreadAgentCompletionPanes['tab-2:0']).toBe(true) + expect(store.getState().unreadAgentCompletionPanes['tab-2:0']).toBe('agent-completion') // Why: a BEL is a separate signal; acking the agent must not silence it. - expect(store.getState().unreadTerminalPanes['tab-1:0']).toBe(true) + expect(store.getState().unreadTerminalPanes['tab-1:0']).toBe('terminal-bell') }) }) diff --git a/src/renderer/src/store/slices/tabs-unread-and-focus.test.ts b/src/renderer/src/store/slices/tabs-unread-and-focus.test.ts index f27a091e6221..0248f057c76f 100644 --- a/src/renderer/src/store/slices/tabs-unread-and-focus.test.ts +++ b/src/renderer/src/store/slices/tabs-unread-and-focus.test.ts @@ -142,9 +142,9 @@ describe('TabsSlice', () => { }) // Fire a bell on Group A's visible tab: under ghostty semantics the indicator still appears — only clearTerminalTabUnread dismisses it. - store.getState().markTerminalTabUnread(tabA.entityId) + store.getState().markTerminalTabUnread(tabA.entityId, 'terminal-bell') - expect(store.getState().unreadTerminalTabs[tabA.entityId]).toBe(true) + expect(store.getState().unreadTerminalTabs[tabA.entityId]).toBe('terminal-bell') }) it('does mark a tab that is not the active tab of any visible group', () => { @@ -181,9 +181,9 @@ describe('TabsSlice', () => { }) // tabA2 is NOT the active tab of any group — a bell on it is legitimate. - store.getState().markTerminalTabUnread(tabA2.entityId) + store.getState().markTerminalTabUnread(tabA2.entityId, 'terminal-bell') - expect(store.getState().unreadTerminalTabs[tabA2.entityId]).toBe(true) + expect(store.getState().unreadTerminalTabs[tabA2.entityId]).toBe('terminal-bell') }) // Why: under show-until-interact, BEL fires unconditionally even on a non-terminal/offscreen surface — a legitimate unread. @@ -211,9 +211,9 @@ describe('TabsSlice', () => { } }) - store.getState().markTerminalTabUnread(tab.entityId) + store.getState().markTerminalTabUnread(tab.entityId, 'terminal-bell') - expect(store.getState().unreadTerminalTabs[tab.entityId]).toBe(true) + expect(store.getState().unreadTerminalTabs[tab.entityId]).toBe('terminal-bell') }) it('is a no-op when the tab is already flagged', () => { @@ -241,7 +241,7 @@ describe('TabsSlice', () => { }) const before = store.getState().unreadTerminalTabs - store.getState().markTerminalTabUnread(tab.entityId) + store.getState().markTerminalTabUnread(tab.entityId, 'terminal-bell') // Same object reference => no state mutation occurred. expect(store.getState().unreadTerminalTabs).toBe(before) @@ -270,9 +270,9 @@ describe('TabsSlice', () => { } }) - store.getState().markTerminalTabUnread(agentTabId) + store.getState().markTerminalTabUnread(agentTabId, 'terminal-bell') - expect(store.getState().unreadTerminalTabs[agentTabId]).toBe(true) + expect(store.getState().unreadTerminalTabs[agentTabId]).toBe('terminal-bell') }) }) diff --git a/src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts b/src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts index c68f58436c83..14aecc47129d 100644 --- a/src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts +++ b/src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts @@ -198,7 +198,7 @@ describe('setTabLayout identity bailout', () => { const normalized = store.getState().terminalLayoutsByTabId['tab-1'] expect(normalized.ptyIdsByLeafId).not.toEqual(duplicate.ptyIdsByLeafId) - store.getState().markTerminalPaneUnread('tab-1:leaf-a') + store.getState().markTerminalPaneUnread('tab-1:leaf-a', 'terminal-bell') const beforeUnread = { ...store.getState().unreadTerminalPanes } for (let i = 0; i < REPEATS; i += 1) { diff --git a/src/renderer/src/store/slices/ui/ui-slice-activity-actions.ts b/src/renderer/src/store/slices/ui/ui-slice-activity-actions.ts index 0ae704a5702f..29fbd1e05065 100644 --- a/src/renderer/src/store/slices/ui/ui-slice-activity-actions.ts +++ b/src/renderer/src/store/slices/ui/ui-slice-activity-actions.ts @@ -1,3 +1,4 @@ +import type { StoredAgentAttentionUnread } from '@/attention/agent-attention-contract' import type { UISlice, UISliceGet, UISliceSet } from './ui-slice-contract' import { collectAcknowledgedAgentNotificationId, @@ -29,7 +30,7 @@ export function createUiActivityActions(set: UISliceSet, _get: UISliceGet): Acti const now = Date.now() const migrationUnsupported = Object.values(s.migrationUnsupportedByPtyId ?? {}) let next: Record | null = null - let nextUnreadCompletions: Record | null = null + let nextUnreadCompletions: Record | null = null for (const key of paneKeys) { if (s.unreadAgentCompletionPanes[key]) { nextUnreadCompletions ??= { ...s.unreadAgentCompletionPanes } diff --git a/src/renderer/src/store/terminals/terminal-actions.ts b/src/renderer/src/store/terminals/terminal-actions.ts index acb2af3756ed..4038ed22091c 100644 --- a/src/renderer/src/store/terminals/terminal-actions.ts +++ b/src/renderer/src/store/terminals/terminal-actions.ts @@ -1,3 +1,4 @@ +import type { AgentAttentionUnreadReason } from '@/attention/agent-attention-contract' import type { TerminalState } from './terminal-state' import type { Tab } from '../../../../shared/tab-types' import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/terminal-tab-types' @@ -117,9 +118,9 @@ export type TerminalActions = { clearTabLaunchAgent: (tabId: string) => void setRuntimePaneTitle: (tabId: string, paneId: number, title: string) => void clearRuntimePaneTitle: (tabId: string, paneId: number) => void - markTerminalTabUnread: (tabId: string) => void - markTerminalPaneUnread: (paneKey: string) => void - markAgentCompletionPaneUnread: (paneKey: string) => void + markTerminalTabUnread: (tabId: string, reason: AgentAttentionUnreadReason) => void + markTerminalPaneUnread: (paneKey: string, reason: AgentAttentionUnreadReason) => void + markAgentCompletionPaneUnread: (paneKey: string, reason: AgentAttentionUnreadReason) => void clearTerminalTabUnread: (tabId: string) => void clearTerminalPaneUnread: (paneKey: string) => void setTabCustomTitle: ( diff --git a/src/renderer/src/store/terminals/terminal-state.ts b/src/renderer/src/store/terminals/terminal-state.ts index 42852e1a7146..766f65f5ad84 100644 --- a/src/renderer/src/store/terminals/terminal-state.ts +++ b/src/renderer/src/store/terminals/terminal-state.ts @@ -1,3 +1,4 @@ +import type { StoredAgentAttentionUnread } from '@/attention/agent-attention-contract' import type { ClosedTerminalTabTombstonesByTabId } from '../../../../shared/closed-terminal-tab-tombstones' import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/terminal-tab-types' import type { TuiAgent } from '../../../../shared/tui-agent' @@ -29,9 +30,9 @@ export type TerminalState = { activeTabIdByWorktree: Record ptyIdsByTabId: Record runtimePaneTitlesByTabId: Record> - unreadTerminalTabs: Record - unreadTerminalPanes: Record - unreadAgentCompletionPanes: Record + unreadTerminalTabs: Record + unreadTerminalPanes: Record + unreadAgentCompletionPanes: Record /** Scoped exit suppression and reference-counted shutdown ownership prevent teardown races. */ suppressedPtyExitIds: Record pendingPtyShutdownIds: Record diff --git a/src/renderer/src/store/terminals/terminal-tab-attention.ts b/src/renderer/src/store/terminals/terminal-tab-attention.ts index 3ba849617633..66cf9298bdbc 100644 --- a/src/renderer/src/store/terminals/terminal-tab-attention.ts +++ b/src/renderer/src/store/terminals/terminal-tab-attention.ts @@ -17,7 +17,7 @@ export function createTerminalTabAttentionActions( | 'setTabColor' > { return { - markTerminalTabUnread: (tabId) => { + markTerminalTabUnread: (tabId, reason) => { const state = get() const ownerTab = Object.values(state.tabsByWorktree ?? {}) .flat() @@ -30,18 +30,18 @@ export function createTerminalTabAttentionActions( if (s.unreadTerminalTabs[tabId]) { return s } - return { unreadTerminalTabs: { ...s.unreadTerminalTabs, [tabId]: true as const } } + return { unreadTerminalTabs: { ...s.unreadTerminalTabs, [tabId]: reason } } }) }, - markTerminalPaneUnread: (paneKey) => { + markTerminalPaneUnread: (paneKey, reason) => { set((s) => { if (s.unreadTerminalPanes[paneKey]) { return s } - return { unreadTerminalPanes: { ...s.unreadTerminalPanes, [paneKey]: true as const } } + return { unreadTerminalPanes: { ...s.unreadTerminalPanes, [paneKey]: reason } } }) }, - markAgentCompletionPaneUnread: (paneKey) => { + markAgentCompletionPaneUnread: (paneKey, reason) => { set((s) => { if (s.unreadAgentCompletionPanes[paneKey]) { return s @@ -49,7 +49,7 @@ export function createTerminalTabAttentionActions( return { unreadAgentCompletionPanes: { ...s.unreadAgentCompletionPanes, - [paneKey]: true as const + [paneKey]: reason } } }) From 0d35d6d950a8e46599d08f5f0b67478ce0fd19b7 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 13 Sep 2026 17:39:29 -0700 Subject: [PATCH 2/2] fix(attention): recognize classified tab unread markers --- .../terminal-tab-activity-status.test.ts | 23 +++++++++++++++++++ .../tab-bar/terminal-tab-activity-status.ts | 7 ++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts index b27d8b0a4080..8511fff19131 100644 --- a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts +++ b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts @@ -390,6 +390,29 @@ describe('resolveTerminalTabAttentionBadge', () => { }) describe('terminalTabHasUnreadActivity', () => { + it.each(['terminal-bell', 'agent-completion', 'manual-mark-unread', 'legacy'] as const)( + 'recognizes a classified %s tab marker without a completion pane', + (reason) => { + expect( + terminalTabHasUnreadActivity({ + terminalTabId: TAB_ID, + unreadTerminalTabs: { [TAB_ID]: reason }, + unreadAgentCompletionPanes: {} + }) + ).toBe(true) + } + ) + + it.each([false, undefined])('ignores a cleared tab marker (%s)', (marker) => { + expect( + terminalTabHasUnreadActivity({ + terminalTabId: TAB_ID, + unreadTerminalTabs: { [TAB_ID]: marker }, + unreadAgentCompletionPanes: {} + }) + ).toBe(false) + }) + it('is true for a tab bell or completion pane', () => { expect( terminalTabHasUnreadActivity({ diff --git a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts index b097db3bba44..7a31cdb8ace2 100644 --- a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts +++ b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts @@ -1,4 +1,7 @@ -import type { ReadableAgentAttentionUnread } from '@/attention/agent-attention-contract' +import { + readAgentAttentionUnreadReason, + type ReadableAgentAttentionUnread +} from '@/attention/agent-attention-contract' import { isExplicitAgentStatusFresh } from '@/lib/agent-status' import { resolveWorktreeStatus, type WorktreeStatus } from '@/lib/worktree-status' import { @@ -260,7 +263,7 @@ export function terminalTabHasUnreadActivity({ unreadAgentCompletionPanes: Record }): boolean { return ( - unreadTerminalTabs[terminalTabId] === true || + readAgentAttentionUnreadReason(unreadTerminalTabs[terminalTabId]) !== null || hasUnreadAgentCompletionForTerminalTab(unreadAgentCompletionPanes, terminalTabId) ) }