Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 20 additions & 87 deletions src/main/ipc/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<string, number>()
const recentMobileNotifications = new Map<string, number>()
resetNotificationPermissionEvidence()

ipcMain.removeHandler('notifications:openSystemSettings')
Expand Down Expand Up @@ -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<NotificationDispatchResult> => {
// 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<NotificationDispatchResult> =>
deliveryService.dispatch(args)
)

registerNotificationSoundHandlers(store)
Expand Down
163 changes: 163 additions & 0 deletions src/main/notifications/notification-delivery-service.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): NotificationSettings {
return {
enabled: true,
agentTaskComplete: true,
terminalBell: true,
suppressWhenFocused: false,
customSoundId: 'system',
customSoundPath: null,
customSoundVolume: 1,
...overrides
}
}

function makeRequest(
overrides: Partial<NotificationDispatchRequest> = {}
): NotificationDispatchRequest {
return {
source: 'agent-task-complete',
worktreeId: 'wt-1',
worktreeLabel: 'wt-1',
...overrides
}
}

type Harness = {
deps: NotificationDeliveryDependencies
order: string[]
setTrayAttention: ReturnType<typeof vi.fn>
dispatchMobileNotification: ReturnType<typeof vi.fn>
deliverNative: ReturnType<typeof vi.fn>
}

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()
})
})
Loading
Loading