From 8959535f1b068fa93fd40f39a9917df0dea0b8d0 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Tue, 2 Jun 2026 21:01:23 -0400 Subject: [PATCH] Auto-dismiss agent notifications on acknowledgement (#4518) Co-authored-by: Orca --- .../mobile-notifications.test.ts | 95 ++++++++++- .../src/notifications/mobile-notifications.ts | 52 +++++- .../notification-routing.test.ts | 6 +- .../src/notifications/notification-routing.ts | 5 + src/main/ipc/notifications.test.ts | 88 ++++++++++ src/main/ipc/notifications.ts | 46 +++++- src/main/runtime/orca-runtime.ts | 17 +- src/main/runtime/rpc/methods/notifications.ts | 2 +- src/preload/api-types.ts | 2 + src/preload/index.ts | 3 + .../use-notification-dispatch.test.ts | 9 ++ .../use-notification-dispatch.ts | 10 ++ src/renderer/src/store/slices/ui.test.ts | 153 ++++++++++++++++++ src/renderer/src/store/slices/ui.ts | 67 +++++++- src/renderer/src/web/web-preload-api.ts | 1 + src/shared/agent-notification-id.test.ts | 46 ++++++ src/shared/agent-notification-id.ts | 25 +++ src/shared/types.ts | 5 + 18 files changed, 621 insertions(+), 11 deletions(-) create mode 100644 src/shared/agent-notification-id.test.ts create mode 100644 src/shared/agent-notification-id.ts diff --git a/mobile/src/notifications/mobile-notifications.test.ts b/mobile/src/notifications/mobile-notifications.test.ts index 32893cc30..f0c264628 100644 --- a/mobile/src/notifications/mobile-notifications.test.ts +++ b/mobile/src/notifications/mobile-notifications.test.ts @@ -1,13 +1,16 @@ -import { describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import * as Notifications from 'expo-notifications' import { subscribeToDesktopNotifications } from './mobile-notifications' import type { RpcClient } from '../transport/rpc-client' +import { loadPushNotificationsEnabled } from '../storage/preferences' vi.mock('expo-notifications', () => ({ AndroidImportance: { HIGH: 'high' }, setNotificationChannelAsync: vi.fn(), getPermissionsAsync: vi.fn(), requestPermissionsAsync: vi.fn(), - scheduleNotificationAsync: vi.fn() + scheduleNotificationAsync: vi.fn(), + dismissNotificationAsync: vi.fn() })) vi.mock('react-native', () => ({ @@ -19,6 +22,16 @@ vi.mock('../storage/preferences', () => ({ })) describe('subscribeToDesktopNotifications', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + async function flushAsync(): Promise { + for (let i = 0; i < 10; i += 1) { + await Promise.resolve() + } + } + it('drops the local stream when disposed before the desktop returns ready', () => { const unsubscribeStream = vi.fn() const client = { @@ -33,4 +46,82 @@ describe('subscribeToDesktopNotifications', () => { expect(unsubscribeStream).toHaveBeenCalledTimes(1) expect(client.sendRequest).not.toHaveBeenCalled() }) + + it('stores scheduled notification identifiers, replaces duplicates, and dismisses by id', async () => { + vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) + vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ + status: 'granted', + canAskAgain: true + } as never) + vi.mocked(Notifications.scheduleNotificationAsync) + .mockResolvedValueOnce('scheduled-1') + .mockResolvedValueOnce('scheduled-2') + vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) + let onEvent: ((data: unknown) => void) | null = null + const client = { + subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => { + onEvent = callback + return vi.fn() + }), + getState: vi.fn(() => 'connected'), + sendRequest: vi.fn() + } as unknown as RpcClient + + subscribeToDesktopNotifications(client, 'host-1') + onEvent?.({ + type: 'notification', + source: 'agent-task-complete', + title: 'Done', + body: 'Finished.', + worktreeId: 'repo::/tmp/worktree', + notificationId: 'agent:one' + }) + await flushAsync() + onEvent?.({ + type: 'notification', + source: 'agent-task-complete', + title: 'Done again', + body: 'Finished again.', + notificationId: 'agent:one' + }) + await flushAsync() + expect(Notifications.scheduleNotificationAsync).toHaveBeenCalledTimes(2) + onEvent?.({ type: 'dismiss', notificationId: 'agent:one' }) + await flushAsync() + + expect(Notifications.scheduleNotificationAsync).toHaveBeenCalledTimes(2) + expect(Notifications.scheduleNotificationAsync).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ + content: expect.objectContaining({ + data: expect.objectContaining({ + hostId: 'host-1', + notificationId: 'agent:one', + worktreeId: 'repo::/tmp/worktree' + }) + }) + }) + ) + expect(Notifications.dismissNotificationAsync).toHaveBeenNthCalledWith(1, 'scheduled-1') + expect(Notifications.dismissNotificationAsync).toHaveBeenNthCalledWith(2, 'scheduled-2') + }) + + it('treats unknown dismiss events as no-ops', async () => { + vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) + let onEvent: ((data: unknown) => void) | null = null + const client = { + subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => { + onEvent = callback + return vi.fn() + }), + getState: vi.fn(() => 'connected'), + sendRequest: vi.fn() + } as unknown as RpcClient + + subscribeToDesktopNotifications(client, 'host-unknown') + onEvent?.({ type: 'dismiss', notificationId: 'agent:missing' }) + await flushAsync() + + expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalled() + }) }) diff --git a/mobile/src/notifications/mobile-notifications.ts b/mobile/src/notifications/mobile-notifications.ts index a8e9caa48..03441b6f7 100644 --- a/mobile/src/notifications/mobile-notifications.ts +++ b/mobile/src/notifications/mobile-notifications.ts @@ -10,6 +10,12 @@ type NotificationEvent = { title: string body: string worktreeId?: string + notificationId?: string +} + +type DismissNotificationEvent = { + type: 'dismiss' + notificationId: string } type SubscribeResult = { @@ -17,6 +23,12 @@ type SubscribeResult = { subscriptionId: string } +const scheduledNotificationIdsByHostAndNotificationId = new Map() + +function getStoredNotificationKey(hostId: string, notificationId: string): string { + return `${encodeURIComponent(hostId)}:${encodeURIComponent(notificationId)}` +} + export type NotificationPermissionState = { granted: boolean status: string @@ -67,7 +79,18 @@ async function showLocalNotification(event: NotificationEvent, hostId: string): return } - await Notifications.scheduleNotificationAsync({ + const storedKey = event.notificationId + ? getStoredNotificationKey(hostId, event.notificationId) + : null + const previousIdentifier = storedKey + ? scheduledNotificationIdsByHostAndNotificationId.get(storedKey) + : undefined + if (storedKey && previousIdentifier) { + await Notifications.dismissNotificationAsync(previousIdentifier).catch(() => {}) + scheduledNotificationIdsByHostAndNotificationId.delete(storedKey) + } + + const scheduledIdentifier = await Notifications.scheduleNotificationAsync({ content: { title: event.title, body: event.body, @@ -76,6 +99,25 @@ async function showLocalNotification(event: NotificationEvent, hostId: string): }, trigger: null }) + if (storedKey) { + scheduledNotificationIdsByHostAndNotificationId.set(storedKey, scheduledIdentifier) + } +} + +async function dismissLocalNotification( + event: DismissNotificationEvent, + hostId: string +): Promise { + if (!event.notificationId) { + return + } + const storedKey = getStoredNotificationKey(hostId, event.notificationId) + const identifier = scheduledNotificationIdsByHostAndNotificationId.get(storedKey) + if (!identifier) { + return + } + scheduledNotificationIdsByHostAndNotificationId.delete(storedKey) + await Notifications.dismissNotificationAsync(identifier).catch(() => {}) } // Why: each host connection gets its own notification subscription. When the @@ -93,7 +135,11 @@ export function subscribeToDesktopNotifications(client: RpcClient, hostId: strin } const unsubscribeStream = client.subscribe('notifications.subscribe', {}, (data: unknown) => { - const event = data as NotificationEvent | SubscribeResult | { type: 'end' } + const event = data as + | NotificationEvent + | DismissNotificationEvent + | SubscribeResult + | { type: 'end' } if (event.type === 'ready') { subscriptionId = (event as SubscribeResult).subscriptionId if (disposed) { @@ -113,6 +159,8 @@ export function subscribeToDesktopNotifications(client: RpcClient, hostId: strin } if (event.type === 'notification') { void showLocalNotification(event as NotificationEvent, hostId) + } else if (event.type === 'dismiss') { + void dismissLocalNotification(event as DismissNotificationEvent, hostId) } }) diff --git a/mobile/src/notifications/notification-routing.test.ts b/mobile/src/notifications/notification-routing.test.ts index 68e701810..ebf09e74d 100644 --- a/mobile/src/notifications/notification-routing.test.ts +++ b/mobile/src/notifications/notification-routing.test.ts @@ -7,14 +7,16 @@ describe('notification routing', () => { buildLocalNotificationData( { source: 'agent-task-complete', - worktreeId: 'repo::/Users/me/orca/workspaces/feature' + worktreeId: 'repo::/Users/me/orca/workspaces/feature', + notificationId: 'agent:one' }, 'host-1' ) ).toEqual({ source: 'agent-task-complete', hostId: 'host-1', - worktreeId: 'repo::/Users/me/orca/workspaces/feature' + worktreeId: 'repo::/Users/me/orca/workspaces/feature', + notificationId: 'agent:one' }) }) diff --git a/mobile/src/notifications/notification-routing.ts b/mobile/src/notifications/notification-routing.ts index b8db59d41..f38a06ec1 100644 --- a/mobile/src/notifications/notification-routing.ts +++ b/mobile/src/notifications/notification-routing.ts @@ -3,12 +3,14 @@ export type DesktopNotificationSource = 'agent-task-complete' | 'terminal-bell' export type DesktopNotificationEvent = { source: DesktopNotificationSource worktreeId?: string + notificationId?: string } export type LocalNotificationData = { source: DesktopNotificationSource hostId: string worktreeId?: string + notificationId?: string } export type NotificationNavigationOptions = { @@ -30,6 +32,9 @@ export function buildLocalNotificationData( if (event.worktreeId) { data.worktreeId = event.worktreeId } + if (event.notificationId) { + data.notificationId = event.notificationId + } return data } diff --git a/src/main/ipc/notifications.test.ts b/src/main/ipc/notifications.test.ts index e2785ce73..3ada19171 100644 --- a/src/main/ipc/notifications.test.ts +++ b/src/main/ipc/notifications.test.ts @@ -115,6 +115,14 @@ describe('registerNotificationHandlers', () => { return call[1] as (event: unknown, args: unknown) => unknown } + function getDismissHandler(): (event: unknown, args: unknown) => unknown { + const call = handleMock.mock.calls.find((c: unknown[]) => c[0] === 'notifications:dismiss') + if (!call) { + throw new Error('notifications:dismiss handler not registered') + } + return call[1] as (event: unknown, args: unknown) => unknown + } + function getOpenSystemSettingsHandler(): (event: unknown) => unknown { const call = handleMock.mock.calls.find( (c: unknown[]) => c[0] === 'notifications:openSystemSettings' @@ -748,6 +756,7 @@ describe('registerNotificationHandlers', () => { ).toEqual({ delivered: false, reason: 'not-supported' }) expect(dispatchMobileNotification).toHaveBeenCalledWith({ + type: 'notification', source: 'agent-task-complete', title: 'feat/notis - Hermes finished', body: 'The diff updates notification formatting.', @@ -895,6 +904,85 @@ describe('registerNotificationHandlers', () => { expect(dispatchMobileNotification).not.toHaveBeenCalled() }) + it('dismisses active native notifications and fans out mobile dismissal once per id', () => { + const dispatchMobileNotification = vi.fn() + const dismissMobileNotification = vi.fn() + registerNotificationHandlers( + { + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: true, + terminalBell: true, + suppressWhenFocused: false + } + }) + } as never, + { dispatchMobileNotification, dismissMobileNotification } as never + ) + + const dispatchHandler = getDispatchHandler() + expect( + dispatchHandler({}, { source: 'agent-task-complete', notificationId: 'agent:one' }) + ).toEqual({ delivered: true }) + + const dismissHandler = getDismissHandler() + expect(dismissHandler({}, ['agent:one', 'agent:one', ''])).toEqual({ dismissed: 1 }) + + expect(notificationCloseMock).toHaveBeenCalledTimes(1) + expect(notificationRemoveListenerMock).toHaveBeenCalledWith('close', expect.any(Function)) + expect(dismissMobileNotification).toHaveBeenCalledTimes(1) + expect(dismissMobileNotification).toHaveBeenCalledWith('agent:one') + }) + + it('fans out mobile dismissal even when there is no active native notification', () => { + const dismissMobileNotification = vi.fn() + registerNotificationHandlers( + { + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: true, + terminalBell: true, + suppressWhenFocused: false + } + }) + } as never, + { dismissMobileNotification } as never + ) + + const dismissHandler = getDismissHandler() + expect(dismissHandler({}, ['agent:missing'])).toEqual({ dismissed: 0 }) + + expect(notificationCloseMock).not.toHaveBeenCalled() + expect(dismissMobileNotification).toHaveBeenCalledWith('agent:missing') + }) + + it('closes the previous native notification when replacing the same id', () => { + registerNotificationHandlers({ + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: true, + terminalBell: true, + suppressWhenFocused: false + } + }) + } as never) + + const dispatchHandler = getDispatchHandler() + expect( + dispatchHandler({}, { source: 'agent-task-complete', notificationId: 'agent:replace' }) + ).toEqual({ delivered: true }) + vi.advanceTimersByTime(5001) + expect( + dispatchHandler({}, { source: 'agent-task-complete', notificationId: 'agent:replace' }) + ).toEqual({ delivered: true }) + + expect(notificationCloseMock).toHaveBeenCalledTimes(1) + expect(notificationShowMock).toHaveBeenCalledTimes(2) + }) + it('silences the native notification when a custom sound is configured', () => { registerNotificationHandlers({ getSettings: () => ({ diff --git a/src/main/ipc/notifications.ts b/src/main/ipc/notifications.ts index f35be06f7..b9490da86 100644 --- a/src/main/ipc/notifications.ts +++ b/src/main/ipc/notifications.ts @@ -15,6 +15,7 @@ import type { Store } from '../persistence' import type { NotificationDispatchRequest, NotificationDispatchResult, + NotificationDismissResult, NotificationPermissionStatusResult, NotificationSettings, NotificationSoundDataResult @@ -59,6 +60,10 @@ type NotificationSoundId = NotificationSettings['customSoundId'] // the notification in macOS Notification Center. Prevent this by keeping a // strong reference until the notification is clicked or closed. const activeNotifications = new Set() +const activeNotificationsById = new Map< + string, + { notification: Notification; release: () => void } +>() function retainNotificationUntilRelease( notification: Notification, @@ -225,6 +230,24 @@ export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntime return getPermissionStatus() }) + ipcMain.removeHandler('notifications:dismiss') + ipcMain.handle('notifications:dismiss', (_event, ids: string[]): NotificationDismissResult => { + const uniqueIds = Array.from( + new Set(ids.filter((id): id is string => typeof id === 'string' && id.length > 0)) + ) + let dismissed = 0 + for (const id of uniqueIds) { + const entry = activeNotificationsById.get(id) + if (entry) { + entry.notification.close() + entry.release() + dismissed += 1 + } + runtime?.dismissMobileNotification(id) + } + return { dismissed } + }) + ipcMain.removeHandler('notifications:dispatch') ipcMain.handle( 'notifications:dispatch', @@ -281,10 +304,12 @@ export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntime // where Electron native notifications are unavailable. if (runtime && args.source !== 'test') { runtime.dispatchMobileNotification({ + type: 'notification', source: args.source, title: notificationOptions.title, body: notificationOptions.body, - worktreeId: args.worktreeId + worktreeId: args.worktreeId, + ...(args.notificationId ? { notificationId: args.notificationId } : {}) }) } @@ -300,11 +325,20 @@ export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntime notificationOptions.sound = 'default' } const notification = new Notification(notificationOptions) + if (args.notificationId) { + const previous = activeNotificationsById.get(args.notificationId) + if (previous) { + previous.notification.close() + previous.release() + } + } // Why: prevent GC from collecting the notification (and its click // handler) while it's still visible in macOS Notification Center. let clickHandler: (() => void) | null = null let failedHandler: ((_event: unknown, error?: string) => void) | null = null + const entryForId: { notification: Notification; release: () => void } | null = + args.notificationId ? { notification, release: () => {} } : null const release = retainNotificationUntilRelease(notification, () => { if (clickHandler) { notification.removeListener('click', clickHandler) @@ -314,7 +348,17 @@ export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntime notification.removeListener('failed', failedHandler) failedHandler = null } + if ( + args.notificationId && + activeNotificationsById.get(args.notificationId) === entryForId + ) { + activeNotificationsById.delete(args.notificationId) + } }) + if (entryForId && args.notificationId) { + entryForId.release = release + activeNotificationsById.set(args.notificationId, entryForId) + } failedHandler = (_event, error) => { // Why: Electron 42's macOS UNNotification backend reports unsigned diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index dc9747d70..6d6e0bbfc 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -1134,13 +1134,24 @@ type ResolvedWorktreeInFlight = { promise: Promise } -export type MobileNotificationEvent = { +export type MobileNotificationDispatchEvent = { + type: 'notification' source: 'agent-task-complete' | 'terminal-bell' | 'test' title: string body: string worktreeId?: string + notificationId?: string } +export type MobileNotificationDismissEvent = { + type: 'dismiss' + notificationId: string +} + +export type MobileNotificationEvent = + | MobileNotificationDispatchEvent + | MobileNotificationDismissEvent + // Why: presence-based driver state for the mobile-presence lock. Exactly one // driver per PTY at any moment. See docs/mobile-presence-lock.md. // - `idle`: no mobile subscribers; desktop input flows freely @@ -2990,6 +3001,10 @@ export class OrcaRuntimeService { } } + dismissMobileNotification(notificationId: string): void { + this.dispatchMobileNotification({ type: 'dismiss', notificationId }) + } + // ─── Account Services (mobile RPC bridge) ───────────────────── setAccountServices(services: RuntimeAccountServices): void { diff --git a/src/main/runtime/rpc/methods/notifications.ts b/src/main/runtime/rpc/methods/notifications.ts index 1d63f26d7..45fe73604 100644 --- a/src/main/runtime/rpc/methods/notifications.ts +++ b/src/main/runtime/rpc/methods/notifications.ts @@ -24,7 +24,7 @@ export const NOTIFICATION_METHODS: readonly RpcAnyMethod[] = [ handler: async (_params, { runtime, connectionId }, emit) => { await new Promise((resolve) => { const unsubscribe = runtime.onNotificationDispatched((event) => { - emit({ type: 'notification', ...event }) + emit(event) }) // Why: scope by per-ws connectionId + per-process counter so diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 5f8ce2749..d1002a143 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -108,6 +108,7 @@ import type { GetRateLimitResult, NotificationDispatchRequest, NotificationDispatchResult, + NotificationDismissResult, NotificationPermissionStatusResult, NotificationSoundResult, OnboardingState, @@ -1593,6 +1594,7 @@ export type PreloadApi = { preflight: PreflightApi notifications: { dispatch: (args: NotificationDispatchRequest) => Promise + dismiss: (ids: string[]) => Promise openSystemSettings: () => Promise getPermissionStatus: () => Promise requestPermission: () => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index fd214ce20..1fb74b97a 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -27,6 +27,7 @@ import type { GhosttyImportPreview, ListWorkItemsResult, MemorySnapshot, + NotificationDismissResult, NotificationDispatchResult, NotificationPermissionStatusResult, NotificationSoundDataResult, @@ -1580,6 +1581,8 @@ const api = { notifications: { dispatch: (args: Record): Promise => ipcRenderer.invoke('notifications:dispatch', args), + dismiss: (ids: string[]): Promise => + ipcRenderer.invoke('notifications:dismiss', ids), openSystemSettings: (): Promise => ipcRenderer.invoke('notifications:openSystemSettings'), getPermissionStatus: (): Promise => ipcRenderer.invoke('notifications:getPermissionStatus'), 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 45cf1402c..a2c83e228 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 @@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { dispatchTerminalNotification } from './use-notification-dispatch' import type { AgentStatusEntry } from '../../../../shared/agent-status-types' import type { TerminalLayoutSnapshot } from '../../../../shared/types' +import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' type MockState = { activeWorktreeId: string | null @@ -151,6 +152,11 @@ describe('dispatchTerminalNotification', () => { expect(window.api.notifications.dispatch).toHaveBeenCalledWith( expect.objectContaining({ source: 'agent-task-complete', + notificationId: buildAgentNotificationId({ + worktreeId: 'wt-primary', + paneKey, + stateStartedAt: mockState.agentStatusByPaneKey[paneKey].stateStartedAt + }), worktreeId: 'wt-primary', paneKey, repoLabel: 'orca', @@ -343,6 +349,9 @@ describe('dispatchTerminalNotification', () => { agentLastAssistantMessage: 'Done.' }) ) + expect(window.api.notifications.dispatch).toHaveBeenCalledWith( + expect.not.objectContaining({ notificationId: expect.any(String) }) + ) expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary') expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1') expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey) 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 184ed7ddb..2cee34d9d 100644 --- a/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts +++ b/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts @@ -5,6 +5,7 @@ import { playDesktopNotificationSound } from '@/lib/desktop-notification-sound' import { isExplicitAgentStatusFresh } from '@/lib/agent-status' import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-types' import type { ParsedAgentStatusPayload } from '../../../../shared/agent-status-types' +import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' import { parsePaneKey } from '../../../../shared/stable-pane-id' import type { TerminalPaneLayoutNode } from '../../../../shared/types' @@ -311,10 +312,19 @@ export function dispatchTerminalNotification( agentInterrupted: agentStatus.interrupted } : {} + const notificationId = + event.source === 'agent-task-complete' + ? buildAgentNotificationId({ + worktreeId, + paneKey: event.paneKey, + stateStartedAt: freshStoredAgentStatus?.stateStartedAt + }) + : null void window.api.notifications .dispatch({ source: event.source, + ...(notificationId ? { notificationId } : {}), worktreeId, paneKey: event.paneKey, repoLabel: repo?.displayName, diff --git a/src/renderer/src/store/slices/ui.test.ts b/src/renderer/src/store/slices/ui.test.ts index 479858aeb..e1d2eedfb 100644 --- a/src/renderer/src/store/slices/ui.test.ts +++ b/src/renderer/src/store/slices/ui.test.ts @@ -5,6 +5,7 @@ import { getDefaultUIState } from '../../../../shared/constants' import type { GitHubWorkItem, PersistedUIState, + TerminalTab, Worktree, WorktreeCardProperty } from '../../../../shared/types' @@ -15,6 +16,8 @@ import type { AppState } from '../types' import type { ContextualTourId } from '../../../../shared/contextual-tours' import type { FeatureInteractionState } from '../../../../shared/feature-interactions' import { makePaneKey } from '../../../../shared/stable-pane-id' +import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' const mocks = vi.hoisted(() => ({ sendBracketedPasteToRunningAgent: vi.fn(), @@ -73,6 +76,31 @@ function makeWorktree(id: string): Worktree { return { id } as unknown as Worktree } +function makeAgentEntry(paneKey: string, stateStartedAt: number): AgentStatusEntry { + return { + state: 'done', + prompt: 'Review complete', + updatedAt: stateStartedAt, + stateStartedAt, + agentType: 'codex', + paneKey, + stateHistory: [] + } +} + +function makeTerminalTab(id: string, worktreeId: string): TerminalTab { + return { + id, + worktreeId, + ptyId: null, + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: Date.now() + } +} + function makeGitHubWorkItem(overrides: Partial = {}): GitHubWorkItem { return { id: 'pr-95', @@ -395,6 +423,131 @@ describe('createUISlice agent send target mode', () => { }) }) +describe('createUISlice acknowledgeAgents notification dismissal', () => { + const tabId = 'tab-ack' + const livePaneKey = makePaneKey(tabId, '11111111-1111-4111-8111-111111111111') + const retainedPaneKey = makePaneKey('tab-retained', '22222222-2222-4222-8222-222222222222') + const skippedPaneKey = makePaneKey('tab-skipped', '33333333-3333-4333-8333-333333333333') + + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-06-02T12:00:00Z')) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('dismisses live and retained agent notifications only when the event is unvisited', () => { + const dismiss = vi.fn().mockResolvedValue({ dismissed: 0 }) + vi.stubGlobal('window', { api: { notifications: { dismiss } } }) + const store = createUIStore() + store.setState({ + tabsByWorktree: { + 'wt-live': [makeTerminalTab(tabId, 'wt-live')] + }, + agentStatusByPaneKey: { + [livePaneKey]: makeAgentEntry(livePaneKey, 1_000), + [skippedPaneKey]: makeAgentEntry(skippedPaneKey, 3_000) + }, + retainedAgentsByPaneKey: { + [retainedPaneKey]: { + entry: makeAgentEntry(retainedPaneKey, 2_000), + worktreeId: 'wt-retained', + tab: makeTerminalTab('tab-retained', 'wt-retained'), + agentType: 'codex', + startedAt: 2_000 + } + }, + acknowledgedAgentsByPaneKey: { + [skippedPaneKey]: 4_000 + } + } as Partial) + + store.getState().acknowledgeAgents([livePaneKey, retainedPaneKey, skippedPaneKey]) + + expect(dismiss).toHaveBeenCalledWith([ + buildAgentNotificationId({ + worktreeId: 'wt-live', + paneKey: livePaneKey, + stateStartedAt: 1_000 + }), + buildAgentNotificationId({ + worktreeId: 'wt-retained', + paneKey: retainedPaneKey, + stateStartedAt: 2_000 + }) + ]) + + dismiss.mockClear() + vi.setSystemTime(new Date('2026-06-02T12:00:01Z')) + store.getState().acknowledgeAgents([livePaneKey, retainedPaneKey]) + + expect(dismiss).not.toHaveBeenCalled() + }) + + it('falls back to live entry worktree attribution and skips unresolved live entries', () => { + const dismiss = vi.fn().mockResolvedValue({ dismissed: 0 }) + vi.stubGlobal('window', { api: { notifications: { dismiss } } }) + const store = createUIStore() + const fallbackPaneKey = makePaneKey('tab-fallback', '44444444-4444-4444-8444-444444444444') + store.setState({ + tabsByWorktree: {}, + agentStatusByPaneKey: { + [fallbackPaneKey]: { + ...makeAgentEntry(fallbackPaneKey, 1_000), + worktreeId: 'wt-from-entry' + }, + [livePaneKey]: makeAgentEntry(livePaneKey, 2_000) + }, + retainedAgentsByPaneKey: {} + } as Partial) + + store.getState().acknowledgeAgents([fallbackPaneKey, livePaneKey]) + + expect(dismiss).toHaveBeenCalledWith([ + buildAgentNotificationId({ + worktreeId: 'wt-from-entry', + paneKey: fallbackPaneKey, + stateStartedAt: 1_000 + }) + ]) + }) + + it('dedupes identical live and retained notification ids for the same pane', () => { + const dismiss = vi.fn().mockResolvedValue({ dismissed: 0 }) + vi.stubGlobal('window', { api: { notifications: { dismiss } } }) + const store = createUIStore() + store.setState({ + tabsByWorktree: { + 'wt-live': [makeTerminalTab(tabId, 'wt-live')] + }, + agentStatusByPaneKey: { + [livePaneKey]: makeAgentEntry(livePaneKey, 1_000) + }, + retainedAgentsByPaneKey: { + [livePaneKey]: { + entry: makeAgentEntry(livePaneKey, 1_000), + worktreeId: 'wt-live', + tab: makeTerminalTab(tabId, 'wt-live'), + agentType: 'codex', + startedAt: 1_000 + } + } + } as Partial) + + store.getState().acknowledgeAgents([livePaneKey]) + + expect(dismiss).toHaveBeenCalledWith([ + buildAgentNotificationId({ + worktreeId: 'wt-live', + paneKey: livePaneKey, + stateStartedAt: 1_000 + }) + ]) + }) +}) + describe('createUISlice hydratePersistedUI', () => { it('defaults persisted right sidebar visibility to open', () => { expect(getDefaultUIState().rightSidebarOpen).toBe(true) diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index 6d70a70fa..fc1b41ac7 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -85,6 +85,8 @@ import { deriveRunningAgentSendTargets, resolveRunningAgentSendTarget } from '../../lib/running-agent-targets' +import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' +import { parsePaneKey } from '../../../../shared/stable-pane-id' export type PendingSidebarWorktreeReveal = { worktreeId: string @@ -285,6 +287,41 @@ const VALID_JIRA_PRESETS = new Set>([ 'done' ]) +function resolvePaneKeyWorktreeIdFromTabs(state: AppState, paneKey: string): string | null { + const parsed = parsePaneKey(paneKey) + if (!parsed) { + return null + } + for (const [worktreeId, tabs] of Object.entries(state.tabsByWorktree ?? {})) { + if (tabs.some((tab) => tab.id === parsed.tabId)) { + return worktreeId + } + } + return null +} + +function collectAcknowledgedAgentNotificationId({ + ids, + worktreeId, + paneKey, + stateStartedAt, + previousAckAt +}: { + ids: Set + worktreeId: string | null | undefined + paneKey: string + stateStartedAt: number | null | undefined + previousAckAt: number +}): void { + if (typeof stateStartedAt !== 'number' || previousAckAt >= stateStartedAt) { + return + } + const id = buildAgentNotificationId({ worktreeId, paneKey, stateStartedAt }) + if (id) { + ids.add(id) + } +} + function filterTrustedOrcaHooksToValidRepos( trust: PersistedTrustedOrcaHooks, validRepoIds: Set @@ -899,7 +936,8 @@ export const createUISlice: StateCreator = (set, get) }, acknowledgedAgentsByPaneKey: {}, - acknowledgeAgents: (paneKeys) => + acknowledgeAgents: (paneKeys) => { + const notificationIdsToDismiss = new Set() set((s) => { if (paneKeys.length === 0) { return s @@ -915,6 +953,26 @@ export const createUISlice: StateCreator = (set, get) let next: Record | null = null for (const key of paneKeys) { const prev = s.acknowledgedAgentsByPaneKey[key] ?? 0 + const liveEntry = s.agentStatusByPaneKey?.[key] + if (liveEntry) { + collectAcknowledgedAgentNotificationId({ + ids: notificationIdsToDismiss, + worktreeId: resolvePaneKeyWorktreeIdFromTabs(s, key) ?? liveEntry.worktreeId, + paneKey: key, + stateStartedAt: liveEntry.stateStartedAt, + previousAckAt: prev + }) + } + const retained = s.retainedAgentsByPaneKey?.[key] + if (retained) { + collectAcknowledgedAgentNotificationId({ + ids: notificationIdsToDismiss, + worktreeId: retained.worktreeId, + paneKey: key, + stateStartedAt: retained.entry.stateStartedAt, + previousAckAt: prev + }) + } if (prev < now) { if (next === null) { next = { ...s.acknowledgedAgentsByPaneKey } @@ -923,7 +981,12 @@ export const createUISlice: StateCreator = (set, get) } } return next ? { acknowledgedAgentsByPaneKey: next } : s - }), + }) + const notificationIds = [...notificationIdsToDismiss] + if (notificationIds.length > 0 && typeof window !== 'undefined') { + void window.api?.notifications?.dismiss?.(notificationIds) + } + }, unacknowledgeAgents: (paneKeys) => set((s) => { if (paneKeys.length === 0) { diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 1616ff3f2..221dd198d 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1968,6 +1968,7 @@ function createSkillsApi(): NonNullable['skills']> { function createNotificationsApi(): NonNullable['notifications']> { return { dispatch: () => Promise.resolve({ delivered: false, reason: 'not-supported' }), + dismiss: () => Promise.resolve({ dismissed: 0 }), openSystemSettings: () => Promise.resolve(), getPermissionStatus: () => Promise.resolve({ supported: false, platform: getBrowserPlatform(), requested: false }), diff --git a/src/shared/agent-notification-id.test.ts b/src/shared/agent-notification-id.test.ts new file mode 100644 index 000000000..c16775009 --- /dev/null +++ b/src/shared/agent-notification-id.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import { buildAgentNotificationId } from './agent-notification-id' + +describe('buildAgentNotificationId', () => { + it('builds a stable id for the same agent event metadata', () => { + const args = { + worktreeId: 'repo::/Users/me/orca/workspaces/feature', + paneKey: 'tab-1:11111111-1111-4111-8111-111111111111', + stateStartedAt: 1780000000123 + } + + expect(buildAgentNotificationId(args)).toBe(buildAgentNotificationId(args)) + }) + + it('changes when the agent state start time changes', () => { + const base = { + worktreeId: 'repo::/Users/me/orca/workspaces/feature', + paneKey: 'tab-1:11111111-1111-4111-8111-111111111111' + } + + expect(buildAgentNotificationId({ ...base, stateStartedAt: 1780000000123 })).not.toBe( + buildAgentNotificationId({ ...base, stateStartedAt: 1780000000456 }) + ) + }) + + it('returns null when required fields are missing', () => { + expect( + buildAgentNotificationId({ + paneKey: 'tab-1:11111111-1111-4111-8111-111111111111', + stateStartedAt: 1780000000123 + }) + ).toBeNull() + expect( + buildAgentNotificationId({ + worktreeId: 'repo::/Users/me/orca/workspaces/feature', + stateStartedAt: 1780000000123 + }) + ).toBeNull() + expect( + buildAgentNotificationId({ + worktreeId: 'repo::/Users/me/orca/workspaces/feature', + paneKey: 'tab-1:11111111-1111-4111-8111-111111111111' + }) + ).toBeNull() + }) +}) diff --git a/src/shared/agent-notification-id.ts b/src/shared/agent-notification-id.ts new file mode 100644 index 000000000..059f86354 --- /dev/null +++ b/src/shared/agent-notification-id.ts @@ -0,0 +1,25 @@ +export type BuildAgentNotificationIdArgs = { + worktreeId?: string | null + paneKey?: string | null + stateStartedAt?: number | null +} + +export function buildAgentNotificationId({ + worktreeId, + paneKey, + stateStartedAt +}: BuildAgentNotificationIdArgs): string | null { + if (!worktreeId || !paneKey || typeof stateStartedAt !== 'number') { + return null + } + if (!Number.isFinite(stateStartedAt)) { + return null + } + + return [ + 'agent', + encodeURIComponent(worktreeId), + encodeURIComponent(paneKey), + String(Math.trunc(stateStartedAt)) + ].join(':') +} diff --git a/src/shared/types.ts b/src/shared/types.ts index 70f46cbac..4a8fd02b8 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -2339,6 +2339,7 @@ export type NotificationEventSource = 'agent-task-complete' | 'terminal-bell' | export type NotificationDispatchRequest = { source: NotificationEventSource + notificationId?: string /** Why: useful for fast native failures, but macOS can still drop notifications after 'show'. */ requireDisplayConfirmation?: boolean worktreeId?: string @@ -2370,6 +2371,10 @@ export type NotificationDispatchResult = { | 'not-displayed' } +export type NotificationDismissResult = { + dismissed: number +} + export type NotificationSoundResult = { played: boolean reason?: