Skip to content

The agent that grows with you

fix(desktop): route native notifications back to their source window

brooklyn!7107458d96aa
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 546dc1387d0..e68c47879a6 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -19,7 +19,6 @@ import {
ipcMain,
Menu,
nativeTheme,
- Notification,
powerMonitor,
powerSaveBlocker,
protocol,
@@ -270,6 +269,7 @@ import {
} from './native-oauth'
import { runNativeLogin } from './native-oauth-login'
import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } from './native-token-store'
+import { registerNativeNotifications } from './notification-ipc'
import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'
import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'
@@ -16773,92 +16773,11 @@ ipcMain.handle('hermes:api', async (_event, request) => {
return handleHermesApiRequest(request).finally(releaseProfileDeletion)
})
-// One deduper per cross-window cue — the choke point every window shares. Main
-// handles IPC serially, so the first window to claim a key wins with no race.
-const isDuplicateNotification = createEventDeduper()
+// Main serializes cross-window ambient claims.
const claimedAmbientCue = createEventDeduper()
-
-// A window asks "do I own this ambient cue (turn-end sound / spoken reply)?".
-// The first caller within the window gets true; peers get false and stay quiet.
ipcMain.handle('hermes:ambient:claim', (_event, key) => !claimedAmbientCue(String(key ?? '')))
-ipcMain.handle('hermes:notify', (_event, payload) => {
- if (!Notification.isSupported()) {
- return false
- }
-
- // Multiple full windows each run their own renderer throttle, so the same
- // kind+session can arrive here twice. Collapse it at this single choke point.
- // Return true (not false): a notification for the event IS being shown by the
- // first caller, so the settings "send test" success probe stays honest.
- if (isDuplicateNotification(`${payload?.kind ?? ''}:${payload?.sessionId ?? payload?.tag ?? ''}`)) {
- return true
- }
-
- // Action buttons render only on signed macOS builds; elsewhere they're dropped
- // and the body click still works.
- const actions = Array.isArray(payload?.actions) ? payload.actions : []
- const icon = typeof payload?.icon === 'string' && payload.icon.trim() ? payload.icon.trim() : undefined
-
- const notification = new Notification({
- title: payload?.title || 'Hermes',
- body: payload?.body || '',
- silent: Boolean(payload?.silent),
- ...(icon ? { icon } : {}),
- actions: actions.map(action => ({ type: 'button', text: String(action?.text || '') }))
- })
-
- notification.on('click', () => {
- if (!mainWindow || mainWindow.isDestroyed()) {
- return
- }
-
- focusWindow(mainWindow)
-
- if (payload?.sessionId) {
- mainWindow.webContents.send('hermes:focus-session', payload.sessionId)
- }
-
- // Plugin / session-less activation — serializable path (+ optional notifyId
- // for renderer callbacks). Same vocabulary as hermes://index-network/….
- if (payload?.activate || payload?.notifyId) {
- mainWindow.webContents.send('hermes:notification-activate', {
- activate: payload?.activate,
- notifyId: payload?.notifyId,
- tag: payload?.tag
- })
- }
- })
- notification.on('action', (_actionEvent, index) => {
- if (!mainWindow || mainWindow.isDestroyed()) {
- return
- }
-
- const action = actions[index]
-
- if (!action?.id) {
- return
- }
-
- // Approvals keep the existing session-scoped channel.
- if (payload?.sessionId && !payload?.notifyId && !payload?.activate) {
- mainWindow.webContents.send('hermes:notification-action', { sessionId: payload.sessionId, actionId: action.id })
-
- return
- }
-
- focusWindow(mainWindow)
- mainWindow.webContents.send('hermes:notification-activate', {
- actionId: action.id,
- activate: action.activate || payload?.activate,
- notifyId: payload?.notifyId,
- tag: payload?.tag
- })
- })
- notification.show()
-
- return true
-})
+registerNativeNotifications({ getMainWindow: () => mainWindow, focusWindow })
// Data-URL file load cap (composer attach + local previews). Main owns the
// persisted MB value so every IPC read honours Settings → Chat without the
diff --git a/apps/desktop/electron/notification-ipc.test.ts b/apps/desktop/electron/notification-ipc.test.ts
new file mode 100644
index 00000000000..9cdd110d7c4
--- /dev/null
+++ b/apps/desktop/electron/notification-ipc.test.ts
@@ -0,0 +1,104 @@
+import { EventEmitter } from 'node:events'
+
+import type { BrowserWindow, IpcMainInvokeEvent } from 'electron'
+import { beforeEach, expect, it, vi } from 'vitest'
+
+import type { HermesNotification } from '../src/global'
+
+const host = vi.hoisted(() => ({
+ handle: vi.fn(),
+ fromWebContents: vi.fn(),
+ shown: [] as EventEmitter[]
+}))
+
+vi.mock('electron', () => ({
+ BrowserWindow: { fromWebContents: host.fromWebContents },
+ ipcMain: { handle: host.handle },
+ Notification: class extends EventEmitter {
+ static isSupported() {
+ return true
+ }
+
+ show() {
+ host.shown.push(this)
+ }
+ }
+}))
+
+import { registerNativeNotifications } from './notification-ipc'
+
+function windowStub() {
+ return {
+ isDestroyed: vi.fn(() => false),
+ webContents: { isDestroyed: vi.fn(() => false), send: vi.fn() }
+ }
+}
+
+beforeEach(() => {
+ host.handle.mockReset()
+ host.fromWebContents.mockReset()
+ host.shown.length = 0
+})
+
+it('returns native clicks and approval actions to the emitting window, not the primary', () => {
+ const primary = windowStub()
+ const source = windowStub()
+ host.fromWebContents.mockReturnValue(source)
+ const focusWindow = vi.fn()
+ registerNativeNotifications({ getMainWindow: () => primary as unknown as BrowserWindow, focusWindow })
+ const notify = host.handle.mock.calls[0][1] as (event: IpcMainInvokeEvent, payload: HermesNotification) => boolean
+ const payload = {
+ kind: 'approval',
+ sessionId: 'runtime-source',
+ focusSessionId: 'stored-source',
+ title: 'Approval',
+ actions: [{ id: 'approve', text: 'Approve' }, { id: 'reject', text: 'Reject' }]
+ }
+ expect(notify({ sender: source.webContents } as unknown as IpcMainInvokeEvent, payload)).toBe(true)
+ expect(focusWindow).not.toHaveBeenCalled()
+ expect(primary.webContents.send).not.toHaveBeenCalled()
+ host.shown[0].emit('click')
+ expect(focusWindow).toHaveBeenCalledWith(source)
+ expect(source.webContents.send).toHaveBeenCalledWith('hermes:focus-session', payload.focusSessionId)
+ host.shown[0].emit('action', { actionIndex: 1 }, undefined)
+ expect(source.webContents.send).toHaveBeenCalledWith('hermes:notification-action', {
+ sessionId: payload.sessionId,
+ actionId: 'reject'
+ })
+ expect(primary.webContents.send).not.toHaveBeenCalled()
+
+ // A response must never jump to another window's gateway after its owner closes.
+ source.isDestroyed.mockReturnValue(true)
+ host.shown[0].emit('action', { actionIndex: 0 }, undefined)
+ expect(primary.webContents.send).not.toHaveBeenCalled()
+ host.shown[0].emit('click')
+ expect(primary.webContents.send).toHaveBeenCalledWith('hermes:focus-session', payload.focusSessionId)
+})
+
+it('delivers plugin callbacks to their source and falls back only for navigation after it closes', () => {
+ const primary = windowStub()
+ const source = windowStub()
+ host.fromWebContents.mockReturnValue(source)
+ const focusWindow = vi.fn()
+ registerNativeNotifications({ getMainWindow: () => primary as unknown as BrowserWindow, focusWindow })
+ const notify = host.handle.mock.calls[0][1] as (event: IpcMainInvokeEvent, payload: HermesNotification) => boolean
+ notify({ sender: source.webContents } as unknown as IpcMainInvokeEvent, {
+ kind: 'plugin',
+ notifyId: 'source-callback',
+ activate: '/plugin',
+ actions: [{ id: 'open', text: 'Open', activate: '/plugin/detail' }]
+ })
+ host.shown[0].emit('action', { actionIndex: 0 }, undefined)
+ expect(source.webContents.send).toHaveBeenCalledWith('hermes:notification-activate', expect.objectContaining({
+ actionId: 'open',
+ notifyId: 'source-callback',
+ activate: '/plugin/detail'
+ }))
+ expect(primary.webContents.send).not.toHaveBeenCalled()
+ source.isDestroyed.mockReturnValue(true)
+ host.shown[0].emit('click')
+ expect(primary.webContents.send).toHaveBeenCalledWith('hermes:notification-activate', expect.objectContaining({
+ activate: '/plugin',
+ notifyId: undefined
+ }))
+})
diff --git a/apps/desktop/electron/notification-ipc.ts b/apps/desktop/electron/notification-ipc.ts
new file mode 100644
index 00000000000..cafdd884529
--- /dev/null
+++ b/apps/desktop/electron/notification-ipc.ts
@@ -0,0 +1,102 @@
+import { BrowserWindow, ipcMain, Notification } from 'electron'
+
+import type { HermesNotification } from '../src/global'
+
+import { createEventDeduper } from './event-dedupe'
+import { resolveNotificationAction } from './notification-actions'
+import { createNotificationRegistry } from './notification-registry'
+
+interface NotificationHost {
+ getMainWindow: () => BrowserWindow | null
+ focusWindow: (window: BrowserWindow) => void
+}
+
+export function registerNativeNotifications({ getMainWindow, focusWindow }: NotificationHost): void {
+ const isDuplicateNotification = createEventDeduper()
+ const notifications = createNotificationRegistry()
+
+ ipcMain.handle('hermes:notify', (event, payload: HermesNotification) => {
+ // The source renderer owns runtime bindings and plugin callbacks.
+ const sourceWindow = BrowserWindow.fromWebContents(event.sender)
+ const targetWindow = () => (sourceWindow && !sourceWindow.isDestroyed() ? sourceWindow : getMainWindow())
+
+ if (!Notification.isSupported()) {
+ return false
+ }
+
+ // Peer renderers share one OS notification for the same event.
+ if (isDuplicateNotification(`${payload?.kind ?? ''}:${payload?.sessionId ?? payload?.tag ?? ''}`)) {
+ return true
+ }
+
+ const actions = Array.isArray(payload?.actions) ? payload.actions : []
+ const icon = typeof payload?.icon === 'string' && payload.icon.trim() ? payload.icon.trim() : undefined
+ const notification = new Notification({
+ title: payload?.title || 'Hermes',
+ body: payload?.body || '',
+ silent: Boolean(payload?.silent),
+ ...(icon ? { icon } : {}),
+ actions: actions.map(action => ({ type: 'button', text: String(action?.text || '') }))
+ })
+
+ notification.on('click', () => {
+ const window = targetWindow()
+
+ if (!window || window.isDestroyed()) {
+ return
+ }
+
+ focusWindow(window)
+
+ const focusSessionId = payload?.focusSessionId || payload?.sessionId
+
+ if (focusSessionId) {
+ window.webContents.send('hermes:focus-session', focusSessionId)
+ }
+
+ if (payload?.activate || payload?.notifyId) {
+ window.webContents.send('hermes:notification-activate', {
+ activate: payload?.activate,
+ notifyId: window === sourceWindow ? payload?.notifyId : undefined,
+ tag: payload?.tag
+ })
+ }
+ })
+ notification.on('action', (actionEvent, index) => {
+ const window = targetWindow()
+
+ if (!window || window.isDestroyed()) {
+ return
+ }
+
+ const action = resolveNotificationAction(actions, actionEvent, index)
+
+ if (!action?.id) {
+ return
+ }
+
+ if (payload?.sessionId && !payload?.notifyId && !payload?.activate) {
+ // Runtime actions belong to the source renderer, never the fallback.
+ if (window !== sourceWindow) {
+ return
+ }
+
+ window.webContents.send('hermes:notification-action', { sessionId: payload.sessionId, actionId: action.id })
+
+ return
+ }
+
+ focusWindow(window)
+ window.webContents.send('hermes:notification-activate', {
+ actionId: action.id,
+ activate: action.activate || payload?.activate,
+ notifyId: window === sourceWindow ? payload?.notifyId : undefined,
+ tag: payload?.tag
+ })
+ })
+ notifications.retain(notification)
+ notification.show()
+
+ return true
+ })
+}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 641d7bfb6e9..d7705d6edeb 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -1244,6 +1244,8 @@ export interface HermesNotification {
silent?: boolean
kind?: string
sessionId?: string
+ /** Durable click target captured before runtime bindings can be recycled. */
+ focusSessionId?: string
/** Dedupe discriminator for session-less notifications (e.g. plugin id). */
tag?: string
/** Absolute icon path for Electron `Notification`. */
diff --git a/apps/desktop/src/store/native-notifications.test.ts b/apps/desktop/src/store/native-notifications.test.ts
index 69adfb0df07..3902fceb74b 100644
--- a/apps/desktop/src/store/native-notifications.test.ts
+++ b/apps/desktop/src/store/native-notifications.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createClientSessionState } from '@/lib/chat-runtime'
+
import { $gateway } from './gateway'
import {
clearPluginNotifyHandlers,
@@ -17,6 +19,7 @@ import { __resetNativeNotifyBaselineForTests, markNativeNotifyBaseline } from '.
import { $approvalRequest, setApprovalRequest } from './prompts'
import { markSessionGone, resetBackgroundPollingGuard } from './runtime-gone'
import { $activeSessionId, setActiveSessionId } from './session'
+import { dropSessionState, publishSessionState } from './session-states'
const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }
const initialHermesDesktop = desktopWindow.hermesDesktop
@@ -65,6 +68,18 @@ afterEach(() => {
resetBackgroundPollingGuard()
})
+it('captures durable navigation identity while keeping the runtime id for approval actions', () => {
+ const runtimeId = freshSession()
+ publishSessionState(runtimeId, createClientSessionState('durable-chat'))
+
+ try {
+ dispatchNativeNotification({ kind: 'approval', sessionId: runtimeId, title: 'Approval' })
+ expect(notify).toHaveBeenCalledWith(expect.objectContaining({ sessionId: runtimeId, focusSessionId: 'durable-chat' }))
+ } finally {
+ dropSessionState(runtimeId)
+ }
+})
+
describe('dispatchNativeNotification focus gating', () => {
it('fires a completion notification for the active session when the window is hidden', () => {
const sessionId = freshSession()
diff --git a/apps/desktop/src/store/native-notifications.ts b/apps/desktop/src/store/native-notifications.ts
index 4a76acb8a09..b9bce407895 100644
--- a/apps/desktop/src/store/native-notifications.ts
+++ b/apps/desktop/src/store/native-notifications.ts
@@ -8,7 +8,7 @@ import { withinNativeNotifyBaseline } from './notify-baseline'
import { clearApprovalRequest } from './prompts'
import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone } from './runtime-gone'
import { $activeSessionId } from './session'
-import { requestForOwnedSession } from './session-states'
+import { requestForOwnedSession, storedSessionIdForRuntimeId } from './session-states'
export type { HermesOpenTarget }
@@ -212,6 +212,7 @@ export function dispatchNativeNotification(input: NativeNotificationInput): bool
actions: input.actions,
activate: input.activate,
body: input.body,
+ focusSessionId: input.sessionId ? storedSessionIdForRuntimeId(input.sessionId) ?? undefined : undefined,
icon: input.icon,
kind: input.kind,
notifyId: input.notifyId,