diff --git a/src/main/index.ts b/src/main/index.ts index a9481faa1..f1d760e54 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -4,6 +4,7 @@ import devIcon from '../../resources/icon-dev.png?asset' import { Store, initDataPath } from './persistence' import { killAllPty } from './ipc/pty' import { registerCoreHandlers } from './ipc/register-core-handlers' +import { triggerStartupNotificationRegistration } from './ipc/notifications' import { OrcaRuntimeService } from './runtime/orca-runtime' import { OrcaRuntimeRpcServer } from './runtime/runtime-rpc' import { registerAppMenu } from './menu/register-app-menu' @@ -83,6 +84,7 @@ app.whenReady().then(async () => { } }) registerCoreHandlers(store, runtime) + triggerStartupNotificationRegistration(store) runtimeRpc = new OrcaRuntimeRpcServer({ runtime, userDataPath: app.getPath('userData') diff --git a/src/main/ipc/notifications.test.ts b/src/main/ipc/notifications.test.ts index 8527a5a2f..56580c4b8 100644 --- a/src/main/ipc/notifications.test.ts +++ b/src/main/ipc/notifications.test.ts @@ -1,31 +1,42 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +/* eslint-disable max-lines */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { removeHandlerMock, handleMock, notificationShowMock, + notificationCloseMock, + notificationOnMock, notificationCtorMock, notificationIsSupportedMock, - getAllWindowsMock + getAllWindowsMock, + getNotificationSettingsMock } = vi.hoisted(() => { const removeHandlerMock = vi.fn() const handleMock = vi.fn() const notificationShowMock = vi.fn() + const notificationCloseMock = vi.fn() + const notificationOnMock = vi.fn() const notificationCtorMock = vi.fn(function () { return { show: notificationShowMock, - on: vi.fn() + close: notificationCloseMock, + on: notificationOnMock } }) const notificationIsSupportedMock = vi.fn(() => true) const getAllWindowsMock = vi.fn(() => []) + const getNotificationSettingsMock = vi.fn(() => ({ authorizationStatus: 'authorized' })) return { removeHandlerMock, handleMock, notificationShowMock, + notificationCloseMock, + notificationOnMock, notificationCtorMock, notificationIsSupportedMock, - getAllWindowsMock + getAllWindowsMock, + getNotificationSettingsMock } }) @@ -44,14 +55,18 @@ vi.mock('electron', () => ({ focus: vi.fn() }, systemPreferences: { - getNotificationSettings: vi.fn(() => ({ authorizationStatus: 'authorized' })) + getNotificationSettings: getNotificationSettingsMock }, shell: { openExternal: vi.fn() } })) -import { registerNotificationHandlers } from './notifications' +import { + registerNotificationHandlers, + triggerStartupNotificationRegistration, + getPermissionStatus +} from './notifications' describe('registerNotificationHandlers', () => { beforeEach(() => { @@ -61,10 +76,14 @@ describe('registerNotificationHandlers', () => { handleMock.mockReset() notificationCtorMock.mockClear() notificationShowMock.mockClear() + notificationCloseMock.mockClear() + notificationOnMock.mockClear() notificationIsSupportedMock.mockReset() notificationIsSupportedMock.mockReturnValue(true) getAllWindowsMock.mockReset() getAllWindowsMock.mockReturnValue([]) + getNotificationSettingsMock.mockReset() + getNotificationSettingsMock.mockReturnValue({ authorizationStatus: 'authorized' }) }) function getDispatchHandler(): (event: unknown, args: unknown) => unknown { @@ -104,10 +123,43 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete' })).toEqual({ delivered: false }) + expect(handler({}, { source: 'agent-task-complete' })).toEqual({ + delivered: false, + reason: 'disabled' + }) expect(notificationCtorMock).not.toHaveBeenCalled() }) + it('returns system-denied when macOS permission is denied', () => { + // Why: getPermissionStatus only consults systemPreferences.getNotificationSettings + // on macOS. On Linux CI the non-darwin branch would check Notification.isSupported() + // instead, so we must force the darwin path to exercise the 'denied' gate. + const originalPlatform = process.platform + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + + getNotificationSettingsMock.mockReturnValue({ authorizationStatus: 'denied' }) + + registerNotificationHandlers({ + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: true, + terminalBell: true, + suppressWhenFocused: true + } + }) + } as never) + + const handler = getDispatchHandler() + expect(handler({}, { source: 'test' })).toEqual({ + delivered: false, + reason: 'system-denied' + }) + expect(notificationCtorMock).not.toHaveBeenCalled() + + Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) + }) + it('suppresses active-worktree notifications while Orca is focused', () => { getAllWindowsMock.mockReturnValue([ { @@ -129,7 +181,8 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() expect(handler({}, { source: 'agent-task-complete', isActiveWorktree: true })).toEqual({ - delivered: false + delivered: false, + reason: 'suppressed-focus' }) expect(notificationCtorMock).not.toHaveBeenCalled() }) @@ -157,6 +210,25 @@ describe('registerNotificationHandlers', () => { expect(notificationShowMock).toHaveBeenCalledTimes(1) }) + it('returns source-disabled when the specific source toggle is off', () => { + registerNotificationHandlers({ + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: false, + terminalBell: true, + suppressWhenFocused: true + } + }) + } as never) + + const handler = getDispatchHandler() + expect(handler({}, { source: 'agent-task-complete' })).toEqual({ + delivered: false, + reason: 'source-disabled' + }) + }) + it('deduplicates repeated notifications for the same worktree', () => { registerNotificationHandlers({ getSettings: () => ({ @@ -174,7 +246,8 @@ describe('registerNotificationHandlers', () => { delivered: true }) expect(handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ - delivered: false + delivered: false, + reason: 'cooldown' }) vi.advanceTimersByTime(5001) @@ -205,8 +278,128 @@ describe('registerNotificationHandlers', () => { }) // Bell fires immediately after for the same worktree — should be suppressed expect(handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ - delivered: false + delivered: false, + reason: 'cooldown' }) expect(notificationShowMock).toHaveBeenCalledTimes(1) }) }) + +describe('triggerStartupNotificationRegistration', () => { + const originalPlatform = process.platform + + beforeEach(() => { + notificationCtorMock.mockClear() + notificationShowMock.mockClear() + notificationCloseMock.mockClear() + notificationOnMock.mockClear() + notificationIsSupportedMock.mockReset() + notificationIsSupportedMock.mockReturnValue(true) + getNotificationSettingsMock.mockReset() + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + }) + + afterEach(() => { + Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) + }) + + it('shows welcome notification when permission is not-determined and not yet requested', () => { + getNotificationSettingsMock.mockReturnValue({ authorizationStatus: 'not determined' }) + + const store = { + getUI: () => ({ notificationPermissionRequested: undefined }), + updateUI: vi.fn() + } + + triggerStartupNotificationRegistration(store as never) + + expect(store.updateUI).toHaveBeenCalledWith({ notificationPermissionRequested: true }) + expect(notificationCtorMock).toHaveBeenCalledWith({ + title: 'Orca is ready to notify you', + body: 'Allow notifications so Orca can alert you when agents finish or terminals need attention.' + }) + expect(notificationShowMock).toHaveBeenCalledTimes(1) + }) + + it('does not fire when permission is already authorized', () => { + getNotificationSettingsMock.mockReturnValue({ authorizationStatus: 'authorized' }) + + const store = { + getUI: () => ({ notificationPermissionRequested: undefined }), + updateUI: vi.fn() + } + + triggerStartupNotificationRegistration(store as never) + + expect(notificationCtorMock).not.toHaveBeenCalled() + expect(store.updateUI).not.toHaveBeenCalled() + }) + + it('does not fire when notificationPermissionRequested flag is set', () => { + getNotificationSettingsMock.mockReturnValue({ authorizationStatus: 'not determined' }) + + const store = { + getUI: () => ({ notificationPermissionRequested: true }), + updateUI: vi.fn() + } + + triggerStartupNotificationRegistration(store as never) + + expect(notificationCtorMock).not.toHaveBeenCalled() + }) + + it('does nothing on non-darwin platforms', () => { + Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }) + getNotificationSettingsMock.mockReturnValue({ authorizationStatus: 'not determined' }) + + const store = { + getUI: () => ({ notificationPermissionRequested: undefined }), + updateUI: vi.fn() + } + + triggerStartupNotificationRegistration(store as never) + + expect(notificationCtorMock).not.toHaveBeenCalled() + }) +}) + +describe('getPermissionStatus', () => { + const originalPlatform = process.platform + + beforeEach(() => { + getNotificationSettingsMock.mockReset() + notificationIsSupportedMock.mockReset() + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + }) + + afterEach(() => { + Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) + }) + + it('returns authorized when macOS reports authorized', () => { + getNotificationSettingsMock.mockReturnValue({ authorizationStatus: 'authorized' }) + expect(getPermissionStatus()).toBe('authorized') + }) + + it('returns denied when macOS reports denied', () => { + getNotificationSettingsMock.mockReturnValue({ authorizationStatus: 'denied' }) + expect(getPermissionStatus()).toBe('denied') + }) + + it('returns not-determined when macOS reports not determined', () => { + getNotificationSettingsMock.mockReturnValue({ authorizationStatus: 'not determined' }) + expect(getPermissionStatus()).toBe('not-determined') + }) + + it('returns authorized on non-darwin when Notification is supported', () => { + Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) + notificationIsSupportedMock.mockReturnValue(true) + expect(getPermissionStatus()).toBe('authorized') + }) + + it('returns denied on non-darwin when Notification is not supported', () => { + Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }) + notificationIsSupportedMock.mockReturnValue(false) + expect(getPermissionStatus()).toBe('denied') + }) +}) diff --git a/src/main/ipc/notifications.ts b/src/main/ipc/notifications.ts index a3cd67573..5df29a3fc 100644 --- a/src/main/ipc/notifications.ts +++ b/src/main/ipc/notifications.ts @@ -1,12 +1,12 @@ import { app, BrowserWindow, Notification, ipcMain, systemPreferences, shell } from 'electron' import type { Store } from '../persistence' -import type { NotificationDispatchRequest } from '../../shared/types' +import type { NotificationDispatchRequest, NotificationDispatchResult } from '../../shared/types' const NOTIFICATION_COOLDOWN_MS = 5000 export type NotificationPermissionStatus = 'authorized' | 'denied' | 'not-determined' | 'unknown' -function getPermissionStatus(): NotificationPermissionStatus { +export function getPermissionStatus(): NotificationPermissionStatus { if (process.platform !== 'darwin') { // Windows/Linux don't have a per-app notification permission gate. return Notification.isSupported() ? 'authorized' : 'denied' @@ -53,17 +53,31 @@ export function registerNotificationHandlers(store: Store): void { ipcMain.removeHandler('notifications:dispatch') ipcMain.handle( 'notifications:dispatch', - (_event, args: NotificationDispatchRequest): { delivered: boolean } => { + (_event, args: NotificationDispatchRequest): NotificationDispatchResult => { + if (!Notification.isSupported()) { + return { delivered: false, reason: 'not-supported' } + } + const settings = store.getSettings().notifications - if (!settings.enabled || !Notification.isSupported()) { - return { delivered: false } + if (!settings.enabled) { + return { delivered: false, reason: 'disabled' } + } + + // Why: even when in-app notifications are enabled, macOS can independently + // block them at the system level. Checking here prevents a silent no-op + // and lets the renderer show actionable feedback. We only block on 'denied' + // — 'not-determined' is allowed through because posting the notification is + // what triggers the macOS permission dialog for the first time. + const permissionStatus = getPermissionStatus() + if (permissionStatus === 'denied') { + return { delivered: false, reason: 'system-denied' } } if ( (args.source === 'agent-task-complete' && !settings.agentTaskComplete) || (args.source === 'terminal-bell' && !settings.terminalBell) ) { - return { delivered: false } + return { delivered: false, reason: 'source-disabled' } } const browserWindow = @@ -74,7 +88,7 @@ export function registerNotificationHandlers(store: Store): void { browserWindow && browserWindow.isFocused() ) { - return { delivered: false } + return { delivered: false, reason: 'suppressed-focus' } } // Dedupe by worktree, not by source — an agent finishing and a terminal bell @@ -83,7 +97,7 @@ export function registerNotificationHandlers(store: Store): void { const now = Date.now() const lastSentAt = recentNotifications.get(dedupeKey) ?? 0 if (now - lastSentAt < NOTIFICATION_COOLDOWN_MS) { - return { delivered: false } + return { delivered: false, reason: 'cooldown' } } recentNotifications.set(dedupeKey, now) @@ -131,6 +145,58 @@ export function registerNotificationHandlers(store: Store): void { ) } +/** + * On first launch, when macOS notification permission is 'not-determined', + * show a welcome notification to trigger the system permission dialog. + * + * Why: macOS requires at least one notification attempt before the system + * will prompt the user to allow/deny. Doing this at startup with meaningful + * content avoids a confusing blank notification later. The notification is + * closed shortly after to avoid lingering in Notification Center. + */ +export function triggerStartupNotificationRegistration(store: Store): void { + if (process.platform !== 'darwin' || !Notification.isSupported()) { + return + } + const status = getPermissionStatus() + if (status !== 'not-determined') { + return + } + // Why: only fire once per install — not on every launch where status stays + // not-determined (e.g. if the user dismisses the macOS dialog without choosing). + const ui = store.getUI() + if (ui.notificationPermissionRequested) { + return + } + store.updateUI({ notificationPermissionRequested: true }) + + const notification = new Notification({ + title: 'Orca is ready to notify you', + body: 'Allow notifications so Orca can alert you when agents finish or terminals need attention.' + }) + + let handled = false + const cleanup = (): void => { + if (handled) { + return + } + handled = true + notification.close() + } + + notification.on('show', () => { + // Why: close after a short delay so the notification doesn't linger in + // Notification Center. The macOS permission dialog is a system-level sheet + // that appears independently and is not dismissed by closing this notification. + setTimeout(cleanup, 8000) + }) + + // Fallback in case macOS doesn't fire the 'show' event (e.g. user denies). + setTimeout(cleanup, 10_000) + + notification.show() +} + function buildNotificationOptions(args: NotificationDispatchRequest): { title: string body: string diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index bf534658f..1497dcaa5 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -12,6 +12,7 @@ import type { IssueInfo, GlobalSettings, NotificationDispatchRequest, + NotificationDispatchResult, OrcaHooks, PersistedUIState, WorkspaceSessionState, @@ -118,7 +119,7 @@ type CliApi = { type NotificationPermissionStatus = 'authorized' | 'denied' | 'not-determined' | 'unknown' type NotificationsApi = { - dispatch: (args: NotificationDispatchRequest) => Promise<{ delivered: boolean }> + dispatch: (args: NotificationDispatchRequest) => Promise getPermissionStatus: () => Promise openSystemSettings: () => Promise } diff --git a/src/preload/index.ts b/src/preload/index.ts index 79da31bd8..03fd88919 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -4,6 +4,7 @@ review and type drift checks easier than scattering these bindings across module import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron' import { electronAPI } from '@electron-toolkit/preload' import type { CliInstallStatus } from '../shared/cli-install-types' +import type { NotificationDispatchResult } from '../shared/types' import type { RuntimeStatus, RuntimeSyncWindowGraph } from '../shared/runtime-types' import { ORCA_EDITOR_SAVE_DIRTY_FILES_EVENT, @@ -280,7 +281,7 @@ const api = { }, notifications: { - dispatch: (args: Record): Promise<{ delivered: boolean }> => + dispatch: (args: Record): Promise => ipcRenderer.invoke('notifications:dispatch', args), getPermissionStatus: (): Promise => ipcRenderer.invoke('notifications:getPermissionStatus'), diff --git a/src/renderer/src/components/settings/NotificationsPane.tsx b/src/renderer/src/components/settings/NotificationsPane.tsx index df35f7278..e6d8ec9b2 100644 --- a/src/renderer/src/components/settings/NotificationsPane.tsx +++ b/src/renderer/src/components/settings/NotificationsPane.tsx @@ -1,4 +1,5 @@ -import { type ReactNode, useEffect, useState } from 'react' +import { type ReactNode, useCallback, useEffect, useState } from 'react' +import { toast } from 'sonner' import type { GlobalSettings } from '../../../../shared/types' import { Button } from '../ui/button' import { Label } from '../ui/label' @@ -44,16 +45,25 @@ export function NotificationsPane({ updateSettings }: NotificationsPaneProps): React.JSX.Element { const notificationSettings = settings.notifications - const [permissionDenied, setPermissionDenied] = useState(false) + const [permissionBlocked, setPermissionBlocked] = useState(false) + + const recheckPermission = useCallback(() => { + void window.api.notifications.getPermissionStatus().then((status) => { + // Why: only flag 'denied', not 'not-determined'. 'not-determined' means + // macOS hasn't prompted the user yet — the startup registration or the + // next notification dispatch will trigger that dialog. Showing "blocked" + // for a permission that was never asked would be misleading. + setPermissionBlocked(status === 'denied') + }) + }, []) useEffect(() => { if (!notificationSettings.enabled) { + setPermissionBlocked(false) return } - void window.api.notifications.getPermissionStatus().then((status) => { - setPermissionDenied(status === 'denied') - }) - }, [notificationSettings.enabled]) + recheckPermission() + }, [notificationSettings.enabled, recheckPermission]) const updateNotificationSettings = (updates: Partial): void => { updateSettings({ @@ -64,9 +74,24 @@ export function NotificationsPane({ }) } + const handleSendTestNotification = async (): Promise => { + const result = await window.api.notifications.dispatch({ source: 'test' }) + if (!result.delivered && result.reason === 'system-denied') { + // Why: don't auto-open System Settings — the yellow banner above already + // provides the "Open Notification Settings" button. Just tell the user + // what happened so the silent failure isn't confusing. + toast.error('Notification blocked by macOS', { + description: 'Allow notifications for Orca in System Settings → Notifications.' + }) + } + // Why: the macOS permission dialog may have appeared (for 'not-determined' + // status), so re-check to update the banner accordingly. + recheckPermission() + } + return (
- {notificationSettings.enabled && permissionDenied && ( + {notificationSettings.enabled && permissionBlocked && (
@@ -139,7 +164,7 @@ export function NotificationsPane({ variant="outline" size="sm" disabled={!notificationSettings.enabled} - onClick={() => void window.api.notifications.dispatch({ source: 'test' })} + onClick={() => void handleSendTestNotification()} className="gap-2" > diff --git a/src/shared/types.ts b/src/shared/types.ts index c7f24f518..7213a08bf 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -353,6 +353,18 @@ export type NotificationDispatchRequest = { isActiveWorktree?: boolean } +export type NotificationDispatchResult = { + delivered: boolean + /** Present when delivered is false. Tells the caller why delivery was skipped. */ + reason?: + | 'disabled' + | 'source-disabled' + | 'suppressed-focus' + | 'cooldown' + | 'not-supported' + | 'system-denied' +} + export type WorktreeCardProperty = 'status' | 'unread' | 'ci' | 'issue' | 'pr' | 'comment' export type PersistedUIState = { @@ -369,6 +381,10 @@ export type PersistedUIState = { worktreeCardProperties: WorktreeCardProperty[] dismissedUpdateVersion: string | null lastUpdateCheckAt: number | null + /** Whether Orca has already attempted to trigger the macOS notification + * permission dialog via a startup notification. Prevents re-firing on + * every launch. */ + notificationPermissionRequested?: boolean } // ─── Persistence shape ──────────────────────────────────────────────