Skip to content

A full-featured download manager.

fix(notifications): honor desktop download notification modes (#2254)

Dr_rOotad40b16bfaf9
diff --git a/.github/pr-assets/download-complete-toast.png b/.github/pr-assets/download-complete-toast.png
new file mode 100644
index 00000000..7b3c55ee
Binary files /dev/null and b/.github/pr-assets/download-complete-toast.png differ
diff --git a/src/main/notifications/desktop-delivery.test.ts b/src/main/notifications/desktop-delivery.test.ts
new file mode 100644
index 00000000..6fcea5a9
--- /dev/null
+++ b/src/main/notifications/desktop-delivery.test.ts
@@ -0,0 +1,97 @@
+import { EventEmitter } from 'node:events'
+import { EventBus } from '@core/events/event-bus'
+import { Events } from '@shared/protocol/events'
+import { DEFAULT_APP_SETTINGS } from '@shared/schemas/app-settings'
+import {
+ type AppNotification,
+ getHiddenNotificationKinds,
+ NotificationKinds,
+} from '@shared/types/notification'
+import { describe, expect, it, vi } from 'vitest'
+import { setupEventForwarding } from '../ipc/events'
+import type { WindowManager } from '../window/window-manager'
+import { createOsNotificationBridge } from './os-bridge'
+
+vi.mock('electron', () => ({ Notification: {} }))
+
+describe.each([NotificationKinds.TaskComplete, NotificationKinds.TaskError])(
+ 'desktop delivery of %s',
+ (kind) => {
+ it.each([true, false])(
+ 'applies all four channel choices without restarting (foreground=%s)',
+ (foreground) => {
+ const eventBus = new EventBus()
+ const settings = { ...DEFAULT_APP_SETTINGS }
+ const broadcast = vi.fn()
+ const nativeShow = vi.fn()
+ const warn = vi.fn()
+ setupEventForwarding(
+ eventBus,
+ { broadcast } as unknown as WindowManager,
+ () => getHiddenNotificationKinds(settings)
+ )
+ const bridge = createOsNotificationBridge({
+ subscribe: (channel, listener) => {
+ eventBus.on(channel, (payload) =>
+ listener(payload as AppNotification)
+ )
+ },
+ getAppSettings: () => settings,
+ getMainWindow: () => ({
+ isVisible: () => foreground,
+ isFocused: () => foreground,
+ }),
+ showMainWindow: vi.fn(),
+ translate: (key) => key,
+ getTaskStatus: () => null,
+ navigateToTask: vi.fn(),
+ navigateToDownloads: vi.fn(),
+ revealTaskInFolder: vi.fn(async () => {}),
+ isSupported: () => true,
+ createNotification: () =>
+ Object.assign(new EventEmitter(), { show: nativeShow }),
+ log: { warn },
+ })
+
+ for (const [system, inside] of [
+ [false, false],
+ [true, false],
+ [false, true],
+ [true, true],
+ ]) {
+ const completed = kind === NotificationKinds.TaskComplete
+ settings[completed ? 'notifyOnComplete' : 'notifyOnError'] = system
+ settings[completed ? 'notifyInAppOnComplete' : 'notifyInAppOnError'] =
+ inside
+ const payload: AppNotification = {
+ id: `${kind}-${system}-${inside}`,
+ sourceKey: null,
+ kind,
+ severity: completed ? 'info' : 'error',
+ titleKey: completed
+ ? 'notification.taskComplete.title'
+ : 'notification.taskError.title',
+ titleParams: { name: 'file.zip' },
+ bodyKey: null,
+ bodyParams: null,
+ taskId: 't-1',
+ createdAt: 1000,
+ readAt: null,
+ }
+ nativeShow.mockClear()
+ broadcast.mockClear()
+ eventBus.emit(Events.NotificationAdded, payload)
+ expect(nativeShow).toHaveBeenCalledTimes(system ? 1 : 0)
+ expect(broadcast).toHaveBeenCalledTimes(inside ? 1 : 0)
+ if (inside)
+ expect(broadcast).toHaveBeenCalledWith(
+ Events.NotificationAdded,
+ payload
+ )
+ }
+ expect(warn).not.toHaveBeenCalled()
+ bridge.dispose()
+ }
+ )
+ }
+)
diff --git a/src/main/notifications/os-bridge.test.ts b/src/main/notifications/os-bridge.test.ts
index 735f356c..9991ef89 100644
--- a/src/main/notifications/os-bridge.test.ts
+++ b/src/main/notifications/os-bridge.test.ts
@@ -6,6 +6,7 @@
// import for the module under test because vitest.config.ts does not alias
// @main (see CLAUDE.md gotchas); @shared/@core aliases still work in tests.
+import { EventEmitter } from 'node:events'
import type { EventChannel } from '@shared/protocol/events'
import { Events } from '@shared/protocol/events'
import { DEFAULT_APP_SETTINGS } from '@shared/schemas/app-settings'
@@ -86,23 +87,24 @@ function makeWindow(
interface FakeHandle extends OsNotificationHandle {
opts: { title: string; body?: string }
click(): Promise<void>
+ fail(error: string): void
}
function makeNotificationFactory() {
const instances: FakeHandle[] = []
const createNotification = vi.fn(
(opts: { title: string; body?: string }): OsNotificationHandle => {
- const clickListeners: Array<() => void | Promise<void>> = []
- const handle: FakeHandle = {
+ const emitter = new EventEmitter()
+ const handle: FakeHandle = Object.assign(emitter, {
opts,
show: vi.fn(),
- on: vi.fn((event: 'click', listener: () => void) => {
- if (event === 'click') clickListeners.push(listener)
- }),
click: async () => {
- for (const listener of clickListeners) await listener()
+ for (const listener of emitter.listeners('click')) await listener()
},
- }
+ fail: (error: string) => {
+ emitter.emit('failed', {}, error)
+ },
+ })
instances.push(handle)
return handle
}
@@ -288,7 +290,11 @@ describe('createOsNotificationBridge — gating matrix', () => {
createOsNotificationBridge(deps)
deliver(makeNotification({ kind: kindCase.kind }))
- const expectSend = !windowState.foreground && toggleOn
+ const isTaskOutcome =
+ kindCase.kind === NotificationKinds.TaskComplete ||
+ kindCase.kind === NotificationKinds.TaskError
+ const expectSend =
+ toggleOn && (isTaskOutcome || !windowState.foreground)
if (expectSend) {
expect(createNotification).toHaveBeenCalledOnce()
} else {
@@ -361,10 +367,10 @@ describe('createOsNotificationBridge — subscription', () => {
// ---------------------------------------------------------------------------
describe('createOsNotificationBridge — isSupported gate', () => {
- it('isSupported() === false skips silently even when everything else says send', () => {
+ it('logs unavailable native notifications without attempting delivery', () => {
const { createNotification } = makeNotificationFactory()
const translate = vi.fn((key: string) => key)
- const { deps, deliver } = baseDeps({
+ const { deps, deliver, log } = baseDeps({
window: null,
settings: makeSettings({ notifyOnComplete: true }),
createNotification,
@@ -378,6 +384,14 @@ describe('createOsNotificationBridge — isSupported gate', () => {
expect(createNotification).not.toHaveBeenCalled()
// Short-circuits before doing any translation work.
expect(translate).not.toHaveBeenCalled()
+ expect(log.warn).toHaveBeenCalledWith(
+ {
+ notificationId: 'n-1',
+ kind: NotificationKinds.TaskComplete,
+ taskId: null,
+ },
+ 'os-notification-bridge: native notifications unavailable'
+ )
})
})
@@ -792,6 +806,36 @@ describe('createOsNotificationBridge — click behavior', () => {
// ---------------------------------------------------------------------------
describe('createOsNotificationBridge — throw isolation', () => {
+ it('logs asynchronous native failures and continues delivering later notifications', () => {
+ const { createNotification, instances } = makeNotificationFactory()
+ const { deps, deliver, log } = baseDeps({ createNotification })
+ createOsNotificationBridge(deps)
+ deliver(makeNotification({ taskId: 't-1' }))
+
+ instances[0].fail('WinAPI: Show failed, ERROR 0x80070490')
+ expect(log.warn).toHaveBeenCalledWith(
+ {
+ notificationId: 'n-1',
+ kind: NotificationKinds.TaskComplete,
+ taskId: 't-1',
+ error: 'WinAPI: Show failed, ERROR 0x80070490',
+ },
+ 'os-notification-bridge: native notification failed'
+ )
+ deliver(makeNotification({ id: 'n-2' }))
+ expect(instances[1].show).toHaveBeenCalledOnce()
+ })
+
+ it('ignores late native failures after disposal', () => {
+ const { createNotification, instances } = makeNotificationFactory()
+ const { deps, deliver, log } = baseDeps({ createNotification })
+ const bridge = createOsNotificationBridge(deps)
+ deliver(makeNotification())
+ bridge.dispose()
+ instances[0].fail('late failure')
+ expect(log.warn).not.toHaveBeenCalled()
+ })
+
it('createNotification throwing is caught, logged via log.warn, and not re-thrown', () => {
const err = new Error('boom')
const createNotification = vi.fn(() => {
diff --git a/src/main/notifications/os-bridge.ts b/src/main/notifications/os-bridge.ts
index 1a35dc93..23deae8d 100644
--- a/src/main/notifications/os-bridge.ts
+++ b/src/main/notifications/os-bridge.ts
@@ -18,6 +18,7 @@ export interface OsNotificationMainWindow {
export interface OsNotificationHandle {
show(): void
on(event: 'click', listener: () => void): void
+ on(event: 'failed', listener: (event: unknown, error: string) => void): void
}
export interface OsNotificationBridgeDeps {
@@ -54,14 +55,14 @@ function isEnabledForKind(kind: string, settings: MotrixAppSettings): boolean {
}
/**
- * Best-effort OS notification bridge (Electron only) — Phase C of the
- * notification-center plan (spec §6). Mirrors `AppNotification` rows onto
- * native OS toasts when the main window is not in the foreground, gated
- * per-kind by the `notifyOnComplete` / `notifyOnError` toggles. `task-error`,
- * `engine-failure`, and any unknown kind all fall back to `notifyOnError`.
+ * Best-effort OS notification bridge (Electron only). Download outcomes
+ * follow the selected system notification preference regardless of focus.
+ * Other alerts stay background-only, with their existing in-app presentation
+ * owning the foreground. `task-error`, `engine-failure`, and unknown kinds
+ * all fall back to `notifyOnError`.
*
- * OS toasts carry no delivery tracking — a dropped/dismissed/unsupported
- * toast never blocks or retries anything; the notification center's stored
+ * Unsupported delivery and native failures are logged but never retried;
+ * a dropped or dismissed toast never blocks anything. The center's stored
* row (already written before `NotificationAdded` fires) is the durable
* record. This bridge is a pure side effect on top of it.
*
@@ -120,13 +121,28 @@ export function createOsNotificationBridge(deps: OsNotificationBridgeDeps): {
}
function handle(payload: AppNotification): void {
- const win = deps.getMainWindow()
- const foreground = win == null ? false : win.isVisible() && win.isFocused()
- if (foreground) return
-
if (!isEnabledForKind(payload.kind, deps.getAppSettings())) return
- if (!isSupported()) return
+ const isTaskOutcome =
+ payload.kind === NotificationKinds.TaskComplete ||
+ payload.kind === NotificationKinds.TaskError
+ if (!isTaskOutcome) {
+ const win = deps.getMainWindow()
+ if (win?.isVisible() && win.isFocused()) return
+ }
+
+ const context = {
+ notificationId: payload.id,
+ kind: payload.kind,
+ taskId: payload.taskId,
+ }
+ if (!isSupported()) {
+ deps.log.warn(
+ context,
+ 'os-notification-bridge: native notifications unavailable'
+ )
+ return
+ }
const title = deps.translate(
payload.titleKey,
@@ -141,6 +157,13 @@ export function createOsNotificationBridge(deps: OsNotificationBridgeDeps): {
body === undefined ? { title } : { title, body }
)
notification.on('click', () => handleClick(payload))
+ notification.on('failed', (_event, error) => {
+ if (disposed) return
+ deps.log.warn(
+ { ...context, error },
+ 'os-notification-bridge: native notification failed'
+ )
+ })
notification.show()
}
diff --git a/src/renderer/hooks/use-notification-toasts.limited.test.tsx b/src/renderer/hooks/use-notification-toasts.limited.test.tsx
index d48fefbb..efa964a5 100644
--- a/src/renderer/hooks/use-notification-toasts.limited.test.tsx
+++ b/src/renderer/hooks/use-notification-toasts.limited.test.tsx
@@ -26,6 +26,7 @@ const listeners: Record<string, Array<(...args: unknown[]) => void>> = {}
vi.mock('@renderer/lib/transport', () => ({
transport: {
+ platform: 'win32',
on: vi.fn((ch: string, cb: (...args: unknown[]) => void) => {
listeners[ch] = listeners[ch] ?? []
listeners[ch].push(cb)
@@ -133,4 +134,42 @@ describe('useNotificationToasts (F9, real toast manager + store)', () => {
const buriedFiller = result.current.toasts.find((t) => t.id === 'filler-0')
expect(buriedFiller).toMatchObject({ limited: true })
})
+
+ it('coalesces a completion burst without hiding a task error, engine failure, or pairing prompt', () => {
+ const { result } = renderProbe()
+ act(() => {
+ toast.add({ id: 'pair-request', title: 'Pair browser', timeout: 0 })
+ fire(Events.NotificationAdded, notification())
+ fire(Events.NotificationAdded, notification({ kind: 'engine-failure' }))
+ for (let i = 0; i < 20; i++) {
+ fire(
+ Events.NotificationAdded,
+ notification({
+ id: `complete-${i}`,
+ kind: 'task-complete',
+ severity: 'info',
+ titleKey: 'notification.taskComplete.title',
+ titleParams: { name: `file-${i}.zip` },
+ })
+ )
+ }
+ })
+ expect(result.current.toasts).toHaveLength(4)
+ expect(
+ result.current.toasts.find((item) => item.id === 'notification-complete')
+ ).toMatchObject({
+ title: 'file-19.zip finished downloading',
+ type: 'success',
+ limited: false,
+ })
+ for (const id of [
+ 'pair-request',
+ 'notification-error',
+ 'engine-start-failed',
+ ]) {
+ expect(
+ result.current.toasts.find((item) => item.id === id)
+ ).toMatchObject({ limited: false })
+ }
+ })
})
diff --git a/src/renderer/hooks/use-notification-toasts.test.tsx b/src/renderer/hooks/use-notification-toasts.test.tsx
index f73f1ef0..c3816ebc 100644
--- a/src/renderer/hooks/use-notification-toasts.test.tsx
+++ b/src/renderer/hooks/use-notification-toasts.test.tsx
@@ -1,4 +1,5 @@
import '@renderer/lib/i18n'
+import { transport } from '@renderer/lib/transport'
import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
import { EngineFailureReason, EngineState } from '@shared/types/engine'
@@ -16,6 +17,7 @@ const { transportInvokeMock } = vi.hoisted(() => ({
vi.mock('@renderer/lib/transport', () => ({
transport: {
+ platform: 'win32',
on: vi.fn((ch: string, cb: (...args: unknown[]) => void) => {
listeners[ch] = listeners[ch] ?? []
listeners[ch].push(cb)
@@ -68,6 +70,7 @@ function notification(
describe('useNotificationToasts', () => {
beforeEach(() => {
+ transport.platform = 'win32'
for (const k of Object.keys(listeners)) delete listeners[k]
toastAddMock.mockReset()
toastCloseMock.mockReset()
@@ -187,7 +190,57 @@ describe('useNotificationToasts', () => {
expect(toastAddMock).not.toHaveBeenCalled()
})
- it('non-error severity never toasts, even when focused', () => {
+ it.each(['win32', 'darwin', 'linux'] as const)(
+ 'shows a translated completion toast in the foreground on %s',
+ (platform) => {
+ transport.platform = platform
+ renderHook(() => useNotificationToasts())
+ act(() => {
+ fire(
+ Events.NotificationAdded,
+ notification({
+ severity: 'info',
+ kind: NotificationKinds.TaskComplete,
+ titleKey: 'notification.taskComplete.title',
+ })
+ )
+ })
+ expect(toastAddMock).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ id: 'notification-complete',
+ title: 'file.zip finished downloading',
+ type: 'success',
+ })
+ )
+ }
+ )
+
+ it.each([
+ ['web', 'visible', true],
+ ['win32', 'hidden', false],
+ ['win32', 'visible', false],
+ ] as const)(
+ 'keeps completion toasts silent on %s / %s / focused=%s',
+ (platform, visibility, focused) => {
+ transport.platform = platform
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue(visibility)
+ vi.spyOn(document, 'hasFocus').mockReturnValue(focused)
+ renderHook(() => useNotificationToasts())
+ act(() => {
+ fire(
+ Events.NotificationAdded,
+ notification({
+ severity: 'info',
+ kind: NotificationKinds.TaskComplete,
+ titleKey: 'notification.taskComplete.title',
+ })
+ )
+ })
+ expect(toastAddMock).not.toHaveBeenCalled()
+ }
+ )
+
+ it('other non-error notifications stay silent, even when focused', () => {
renderHook(() => useNotificationToasts())
act(() => {
@@ -195,8 +248,7 @@ describe('useNotificationToasts', () => {
Events.NotificationAdded,
notification({
severity: 'info',
- kind: 'task-complete',
- titleKey: 'notification.taskComplete.title',
+ kind: 'unknown-info',
})
)
fire(
diff --git a/src/renderer/hooks/use-notification-toasts.ts b/src/renderer/hooks/use-notification-toasts.ts
index 9579b751..3ef7f879 100644
--- a/src/renderer/hooks/use-notification-toasts.ts
+++ b/src/renderer/hooks/use-notification-toasts.ts
@@ -28,29 +28,24 @@ import { useTranslation } from 'react-i18next'
* un-coalesced per-row history always remains available on `/notifications`.
*/
const FOCUSED_ERROR_TOAST_ID = 'notification-error'
+const FOCUSED_COMPLETE_TOAST_ID = 'notification-complete'
/**
- * Focused-error toast subscriber (spec §7 boundary) that also owns the
+ * Foreground notification subscriber that also owns the
* sticky engine-failure diagnostic toast — formerly a separate sticky-toast
* hook that coordinated with this one through parallel
* `Events.EngineStateChanged` tracking. Absorbing it here removes that
* coordination: there is now exactly one place that decides when the sticky
* toast shows and when it closes.
*
- * Two distinct toast surfaces share this one hook:
+ * Three distinct toast surfaces share this one hook:
*
* 1. Generic error rows (`n.severity === 'error'`, any kind other than
* `engine-failure`) toast through `FOCUSED_ERROR_TOAST_ID`, gated on
* document foreground (see below) and coalesced via close-then-add
- * (F9). This is the renderer half of an "exactly one track fires" split
- * with the OS notification bridge (`src/main/notifications/os-bridge.ts`,
- * Task 16): that bridge toasts natively only when the main window is NOT
- * foreground (`!(win.isVisible() && win.isFocused())`); this hook toasts
- * in-app only when the document IS foreground
- * (`visibilityState === 'visible' && document.hasFocus()`) — the exact
- * complement when both notification channels are enabled. Desktop event
- * forwarding filters muted task outcomes before they reach this hook;
- * native notification settings remain independent.
+ * (F9). Desktop event forwarding filters muted task outcomes before they
+ * reach this hook. Native download notifications independently follow the
+ * system preference, including while this document is in the foreground.
*
* 2. `kind === NotificationKinds.EngineFailure` rows toast through the
* STICKY `ENGINE_FAILURE_TOAST_ID` instead (`timeout: 0`, with an action
@@ -76,9 +71,11 @@ const FOCUSED_ERROR_TOAST_ID = 'notification-error'
* failed query (transport not ready yet, etc.) is swallowed — a later
* engine event or app reload will retry it.
*
- * Only `severity === 'error'` rows and the engine-compatibility warning toast
- * at all — `task-complete`/info rows stay silent (they still land in the bell
- * badge / `/notifications` page via `useNotifications()` when enabled).
+ * 3. Desktop `task-complete` rows show a success toast when the document is
+ * foreground. A separate stable id coalesces completion bursts without
+ * replacing an error toast or adding one visible toast per finished task.
+ * Server/Web completion rows keep their notification-center-only behavior.
+ * Other non-error rows stay silent except for engine compatibility warnings.
*
* Mount exactly once at the top of the app tree (AppLayout), mirroring
* `useToastEvents`/`usePairRequestPrompts`: `t` and `i18n` are threaded
@@ -87,12 +84,8 @@ const FOCUSED_ERROR_TOAST_ID = 'notification-error'
* `usePairRequestPrompts`'s docstring) never tears down and re-subscribes
* the transport listener.
*
- * The generic-error track (vs. the OS bridge) gates on document/window
- * focus read at different instants — this hook at emit time, the OS bridge
- * at delivery time (post store-write) — so a focus change landing between
- * those two reads can make both fire or neither. That's an accepted
- * best-effort gap, not a bug to chase; see the OS bridge's own docstring for
- * its half of the same tradeoff.
+ * Non-task alerts retain the foreground/background split with the OS bridge.
+ * Their separate focus reads can race a focus change; delivery is best-effort.
*/
export function useNotificationToasts(): void {
const { t, i18n } = useTranslation()
@@ -177,7 +170,11 @@ export function useNotificationToasts(): void {
const n = args[0] as AppNotification
const isCompatibilityWarning =
n.kind === NotificationKinds.EngineCompatibility
- if (n.severity !== 'error' && !isCompatibilityWarning) return
+ const isTaskComplete =
+ transport.platform !== 'web' &&
+ n.kind === NotificationKinds.TaskComplete
+ if (n.severity !== 'error' && !isCompatibilityWarning && !isTaskComplete)
+ return
// Bullet 1: engine-failure rows get the sticky action-bearing toast —
// no foreground gate, no FOCUSED_ERROR_TOAST_ID coalescing.
@@ -202,13 +199,20 @@ export function useNotificationToasts(): void {
// puts this toast back at the front (mirrors the sticky
// engine-failure toast above). This toast has no `onClose` handler,
// so close() firing one here is a no-op.
- toast.close(FOCUSED_ERROR_TOAST_ID)
+ const toastId = isTaskComplete
+ ? FOCUSED_COMPLETE_TOAST_ID
+ : FOCUSED_ERROR_TOAST_ID
+ toast.close(toastId)
toast.add({
- id: FOCUSED_ERROR_TOAST_ID,
+ id: toastId,
title: resolve(n.titleKey, n.titleParams),
description:
n.bodyKey != null ? resolve(n.bodyKey, n.bodyParams) : undefined,
- type: isCompatibilityWarning ? 'warning' : 'error',
+ type: isTaskComplete
+ ? 'success'
+ : isCompatibilityWarning
+ ? 'warning'
+ : 'error',
})
}