Auto-dismiss agent notifications on acknowledgement (#4518)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -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<void> {
|
||||
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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<string, string>()
|
||||
|
||||
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<void> {
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -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'
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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: () => ({
|
||||
|
||||
@@ -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<Notification>()
|
||||
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
|
||||
|
||||
@@ -1134,13 +1134,24 @@ type ResolvedWorktreeInFlight = {
|
||||
promise: Promise<ResolvedWorktree[]>
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -24,7 +24,7 @@ export const NOTIFICATION_METHODS: readonly RpcAnyMethod[] = [
|
||||
handler: async (_params, { runtime, connectionId }, emit) => {
|
||||
await new Promise<void>((resolve) => {
|
||||
const unsubscribe = runtime.onNotificationDispatched((event) => {
|
||||
emit({ type: 'notification', ...event })
|
||||
emit(event)
|
||||
})
|
||||
|
||||
// Why: scope by per-ws connectionId + per-process counter so
|
||||
|
||||
@@ -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<NotificationDispatchResult>
|
||||
dismiss: (ids: string[]) => Promise<NotificationDismissResult>
|
||||
openSystemSettings: () => Promise<void>
|
||||
getPermissionStatus: () => Promise<NotificationPermissionStatusResult>
|
||||
requestPermission: () => Promise<NotificationPermissionStatusResult>
|
||||
|
||||
@@ -27,6 +27,7 @@ import type {
|
||||
GhosttyImportPreview,
|
||||
ListWorkItemsResult,
|
||||
MemorySnapshot,
|
||||
NotificationDismissResult,
|
||||
NotificationDispatchResult,
|
||||
NotificationPermissionStatusResult,
|
||||
NotificationSoundDataResult,
|
||||
@@ -1580,6 +1581,8 @@ const api = {
|
||||
notifications: {
|
||||
dispatch: (args: Record<string, unknown>): Promise<NotificationDispatchResult> =>
|
||||
ipcRenderer.invoke('notifications:dispatch', args),
|
||||
dismiss: (ids: string[]): Promise<NotificationDismissResult> =>
|
||||
ipcRenderer.invoke('notifications:dismiss', ids),
|
||||
openSystemSettings: (): Promise<void> => ipcRenderer.invoke('notifications:openSystemSettings'),
|
||||
getPermissionStatus: (): Promise<NotificationPermissionStatusResult> =>
|
||||
ipcRenderer.invoke('notifications:getPermissionStatus'),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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> = {}): 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<AppState>)
|
||||
|
||||
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<AppState>)
|
||||
|
||||
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<AppState>)
|
||||
|
||||
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)
|
||||
|
||||
@@ -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<NonNullable<TaskResumeState['jiraPreset']>>([
|
||||
'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<string>
|
||||
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<string>
|
||||
@@ -899,7 +936,8 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
|
||||
},
|
||||
|
||||
acknowledgedAgentsByPaneKey: {},
|
||||
acknowledgeAgents: (paneKeys) =>
|
||||
acknowledgeAgents: (paneKeys) => {
|
||||
const notificationIdsToDismiss = new Set<string>()
|
||||
set((s) => {
|
||||
if (paneKeys.length === 0) {
|
||||
return s
|
||||
@@ -915,6 +953,26 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
|
||||
let next: Record<string, number> | 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<AppState, [], [], UISlice> = (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) {
|
||||
|
||||
@@ -1968,6 +1968,7 @@ function createSkillsApi(): NonNullable<Partial<PreloadApi>['skills']> {
|
||||
function createNotificationsApi(): NonNullable<Partial<PreloadApi>['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 }),
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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(':')
|
||||
}
|
||||
@@ -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?:
|
||||
|
||||
Reference in New Issue
Block a user