Skip to content

The agent that grows with you

fix(desktop): prevent Linux native notification freezes

BearHuddleston326ce363a36c
diff --git a/apps/desktop/electron/notification-ipc.test.ts b/apps/desktop/electron/notification-ipc.test.ts
index bd68dba03e8..b69437089a5 100644
--- a/apps/desktop/electron/notification-ipc.test.ts
+++ b/apps/desktop/electron/notification-ipc.test.ts
@@ -27,6 +27,23 @@ vi.mock('electron', () => ({
import { registerNativeNotifications } from './notification-ipc'
+vi.mock('./notification-linux', () => ({
+ createLinuxNotifications: () => ({
+ create: () => {
+ const notification = Object.assign(new EventEmitter(), {
+ show() {
+ host.shown.push(notification)
+
+ return Promise.resolve(true)
+ },
+ close() {}
+ })
+
+ return notification
+ }
+ })
+}))
+
function windowStub() {
return {
isDestroyed: vi.fn(() => false),
@@ -40,7 +57,7 @@ beforeEach(() => {
host.shown.length = 0
})
-it('returns native clicks and approval actions to the emitting window, not the primary', () => {
+it('returns native clicks and approval actions to the emitting window, not the primary', async () => {
const primary = windowStub()
const source = windowStub()
host.fromWebContents.mockReturnValue(source)
@@ -59,7 +76,7 @@ it('returns native clicks and approval actions to the emitting window, not the p
]
}
- expect(notify({ sender: source.webContents } as unknown as IpcMainInvokeEvent, payload)).toBe(true)
+ expect(await 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')
@@ -80,14 +97,14 @@ it('returns native clicks and approval actions to the emitting window, not the p
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', () => {
+it('delivers plugin callbacks to their source and falls back only for navigation after it closes', async () => {
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, {
+ await notify({ sender: source.webContents } as unknown as IpcMainInvokeEvent, {
kind: 'plugin',
notifyId: 'source-callback',
activate: '/plugin',
diff --git a/apps/desktop/electron/notification-ipc.ts b/apps/desktop/electron/notification-ipc.ts
index 1567989acd6..8619e8ff8ba 100644
--- a/apps/desktop/electron/notification-ipc.ts
+++ b/apps/desktop/electron/notification-ipc.ts
@@ -2,6 +2,7 @@ import { BrowserWindow, ipcMain, Notification } from 'electron'
import { createEventDeduper } from './event-dedupe'
import { resolveNotificationAction } from './notification-actions'
+import { createLinuxNotifications } from './notification-linux'
import { createNotificationRegistry } from './notification-registry'
import type { HermesNotification } from './notification-types'
@@ -11,33 +12,39 @@ interface NotificationHost {
}
export function registerNativeNotifications({ getMainWindow, focusWindow }: NotificationHost): void {
- const isDuplicateNotification = createEventDeduper()
+ const dedupeIntervalMs = 1000
+ const isDuplicateNotification = createEventDeduper(dedupeIntervalMs)
+ const deliveries = new Map<string, Promise<boolean>>()
const notifications = createNotificationRegistry()
+ const linux = process.platform === 'linux' ? createLinuxNotifications() : undefined
- ipcMain.handle('hermes:notify', (event, payload: HermesNotification) => {
+ ipcMain.handle('hermes:notify', async (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()) {
+ if (!linux && !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 key = `${payload?.kind ?? ''}:${payload?.sessionId ?? payload?.tag ?? ''}`
+ if (isDuplicateNotification(key)) {
+ return deliveries.get(key) ?? false
}
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({
+ const options = {
title: payload?.title || 'Hermes',
body: payload?.body || '',
silent: Boolean(payload?.silent),
...(icon ? { icon } : {}),
- actions: actions.map(action => ({ type: 'button', text: String(action?.text || '') }))
- })
+ actions: actions.map(action => ({ type: 'button' as const, text: String(action?.text || '') }))
+ }
+
+ const notification = linux ? linux.create(options) : new Notification(options)
notification.on('click', () => {
const window = targetWindow()
@@ -95,8 +102,16 @@ export function registerNativeNotifications({ getMainWindow, focusWindow }: Noti
})
})
notifications.retain(notification)
- notification.show()
- return true
+ // Peers share the actual outcome, including pending/failed Linux delivery.
+ const delivery = Promise.resolve(notification.show()).then(result => result !== false)
+ deliveries.set(key, delivery)
+ setTimeout(() => {
+ if (deliveries.get(key) === delivery) {
+ deliveries.delete(key)
+ }
+ }, dedupeIntervalMs).unref()
+
+ return delivery
})
}
diff --git a/apps/desktop/electron/notification-linux.test.ts b/apps/desktop/electron/notification-linux.test.ts
new file mode 100644
index 00000000000..162f4b65e29
--- /dev/null
+++ b/apps/desktop/electron/notification-linux.test.ts
@@ -0,0 +1,301 @@
+import { EventEmitter } from 'node:events'
+
+import type { Message } from 'dbus-native'
+import type { BrowserWindow, IpcMainInvokeEvent } from 'electron'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import type { HermesNotification } from './notification-types'
+
+const host = vi.hoisted(() => ({ handle: vi.fn(), fromWebContents: vi.fn(), createClient: vi.fn() }))
+vi.mock('electron', () => ({
+ BrowserWindow: { fromWebContents: host.fromWebContents },
+ ipcMain: { handle: host.handle },
+ Notification: class extends EventEmitter {
+ static isSupported() {
+ return true
+ }
+ show() {}
+ close() {}
+ }
+}))
+vi.mock('dbus-native', () => ({
+ createClient: host.createClient,
+ Variant: class {
+ constructor(
+ public signature: string,
+ public value: unknown
+ ) {}
+ }
+}))
+
+import { registerNativeNotifications } from './notification-ipc'
+
+function setup(alreadyRunning = false) {
+ host.handle.mockClear()
+ const connection = Object.assign(new EventEmitter(), {
+ stream: { destroy: vi.fn(() => connection.emit('close')), unref: vi.fn() }
+ })
+
+ let stalled = '',
+ owner = ':1.20',
+ id = 0,
+ activated = alreadyRunning,
+ raceOwnerReply = false
+
+ const calls: Message[] = []
+ const failures = new Map<string, string>()
+ const replaceOwner = () => {
+ const old = owner
+ owner = ':1.21'
+ id = 0
+ connection.emit('message', {
+ type: 4,
+ sender: 'org.freedesktop.DBus',
+ path: '/org/freedesktop/DBus',
+ interface: 'org.freedesktop.DBus',
+ member: 'NameOwnerChanged',
+ body: ['org.freedesktop.Notifications', old, owner]
+ })
+ }
+
+ const invoke = (
+ message: Message,
+ options: { signal?: AbortSignal; timeout?: number },
+ callback?: (error: Error | null, value?: unknown) => void
+ ) => {
+ calls.push(message)
+
+ const promise = new Promise((resolve, reject) => {
+ if (failures.has(message.member ?? '')) {
+ reject(Object.assign(new Error('fixture failure'), { dbusName: failures.get(message.member ?? '') }))
+ return
+ }
+ if (message.member === stalled) {
+ const fail = () => reject(new Error('service unavailable'))
+
+ if (options.signal) {
+ options.signal.addEventListener('abort', fail, { once: true })
+ } else {
+ setTimeout(fail, options.timeout ?? 5000)
+ }
+
+ return
+ }
+
+ if (message.member === 'GetNameOwner' && !activated) {
+ reject(Object.assign(new Error('no owner'), { dbusName: 'org.freedesktop.DBus.Error.NameHasNoOwner' }))
+ return
+ }
+ if (message.member === 'StartServiceByName') {
+ if (alreadyRunning) {
+ reject(
+ Object.assign(new Error('no activation file'), { dbusName: 'org.freedesktop.DBus.Error.ServiceUnknown' })
+ )
+ return
+ }
+ activated = true
+ }
+
+ const values: Record<string, unknown> = {
+ Hello: ':1.10',
+ StartServiceByName: 1,
+ GetNameOwner: owner,
+ GetCapabilities: ['actions', 'body'],
+ Notify: message.member === 'Notify' ? ++id : id
+ }
+
+ const value = values[message.member ?? '']
+
+ // Delivery can be followed by a signal in the same read turn.
+ if (callback) {
+ callback(null, value)
+ }
+ resolve(value)
+ if (message.member === 'GetNameOwner' && raceOwnerReply) {
+ raceOwnerReply = false
+ replaceOwner() // Reply followed by owner replacement in the same read batch.
+ }
+ })
+
+ if (callback) {
+ void promise.catch(error => callback(error))
+ }
+
+ return promise
+ }
+
+ host.createClient.mockReturnValue({ connection, invoke, invokeDbus: invoke })
+ const primary = { isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } }
+ const source = { isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } }
+ host.fromWebContents.mockReturnValue(source)
+ const focusWindow = vi.fn()
+ registerNativeNotifications({ getMainWindow: () => primary as unknown as BrowserWindow, focusWindow })
+
+ const notify = (payload: HermesNotification) =>
+ Promise.resolve(
+ host.handle.mock.calls[0][1]({ sender: source.webContents } as unknown as IpcMainInvokeEvent, payload)
+ )
+
+ const signal = (member: string, body: unknown[], sender = owner) =>
+ connection.emit('message', {
+ type: 4,
+ path: '/org/freedesktop/Notifications',
+ interface: 'org.freedesktop.Notifications',
+ member,
+ sender,
+ body
+ })
+
+ return {
+ connection,
+ calls,
+ primary,
+ source,
+ focusWindow,
+ notify,
+ signal,
+ stall: (method: string) => {
+ stalled = method
+ },
+ replaceOwner,
+ raceOwnerReply: () => {
+ raceOwnerReply = true
+ },
+ fail: (member: string, name: string) => {
+ failures.set(member, name)
+ },
+ lastId: () => id
+ }
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.stubEnv('DBUS_SESSION_BUS_ADDRESS', 'unix:path=/test-notifications')
+ vi.stubEnv('ELECTRON_USE_UBUNTU_NOTIFIER', undefined)
+ host.handle.mockReset()
+ host.fromWebContents.mockReset()
+ host.createClient.mockReset()
+})
+afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllEnvs()
+})
+
+it.skipIf(process.platform !== 'linux')(
+ 'bounds failed delivery without dropping older callbacks, and retries only on a later request',
+ async () => {
+ const unavailable = setup()
+ unavailable.fail('StartServiceByName', 'org.freedesktop.DBus.Error.ServiceUnknown')
+ expect(await unavailable.notify({ tag: 'test' })).toBe(false)
+ expect(await unavailable.notify({ tag: 'test' })).toBe(false)
+ expect(unavailable.calls.filter(call => call.member === 'StartServiceByName')).toHaveLength(1)
+ unavailable.connection.emit('close')
+
+ // libnotify's getenv guard disables actions even for an empty value.
+ vi.stubEnv('ELECTRON_USE_UBUNTU_NOTIFIER', '')
+ const unity = setup(true)
+ expect(await unity.notify({ tag: 'unity', actions: [{ id: 'ok', text: 'OK' }] })).toBe(true)
+ expect(unity.calls.find(call => call.member === 'Notify')?.body?.[5]).toEqual([])
+ unity.connection.emit('close')
+ vi.stubEnv('ELECTRON_USE_UBUNTU_NOTIFIER', undefined)
+
+ for (const method of ['Hello', 'AddMatch', 'StartServiceByName', 'GetNameOwner', 'GetCapabilities']) {
+ const startup = setup()
+ startup.stall(method)
+ const attempt = startup.notify({ tag: method })
+ await vi.advanceTimersByTimeAsync(6000)
+ expect(await attempt).toBe(false)
+ await vi.advanceTimersByTimeAsync(11000)
+ startup.stall('')
+ expect(await startup.notify({ tag: 'startup-recovered' })).toBe(true)
+ startup.connection.emit('close')
+ }
+
+ const h = setup()
+ expect(await h.notify({ tag: 'old', focusSessionId: 'old-session' })).toBe(true)
+ expect(h.calls.some(call => call.member === 'StartServiceByName')).toBe(true)
+ const oldId = h.lastId()
+ h.stall('Notify')
+ const pending = h.notify({ tag: 'stalled' })
+ const duplicate = h.notify({ tag: 'stalled' })
+ await vi.advanceTimersByTimeAsync(6000)
+ expect(await pending).toBe(false)
+ expect(await duplicate).toBe(false)
+ const attempts = h.calls.length
+ expect(await h.notify({ tag: 'cooldown' })).toBe(false)
+ expect(h.calls).toHaveLength(attempts)
+ h.signal('ActionInvoked', [oldId, 'default'])
+ expect(h.source.webContents.send).toHaveBeenCalledWith('hermes:focus-session', 'old-session')
+ const afterConsumption = h.calls.length
+ await vi.advanceTimersByTimeAsync(11000)
+ expect(h.calls).toHaveLength(afterConsumption) // No automatic replay of an ambiguous Notify.
+ h.stall('')
+ expect(await h.notify({ tag: 'recovered' })).toBe(true)
+ h.stall('CloseNotification')
+ const closesBeforeExpiry = h.calls.filter(call => call.member === 'CloseNotification').length
+ await vi.advanceTimersByTimeAsync(10 * 60_000 + 6000)
+ expect(h.calls.filter(call => call.member === 'CloseNotification')).toHaveLength(closesBeforeExpiry + 1)
+ h.connection.emit('close')
+ }
+)
+
+it.skipIf(process.platform !== 'linux')(
+ 'preserves activation, dedupe and source ownership while fencing daemon ID reuse',
+ async () => {
+ const race = setup(true)
+ race.raceOwnerReply()
+ expect(await race.notify({ tag: 'obsolete-owner', focusSessionId: 'must-not-open' })).toBe(false)
+ expect(race.calls.filter(call => call.member === 'Notify')).toHaveLength(0)
+ race.connection.emit('close')
+
+ const h = setup(true)
+
+ const payload = {
+ kind: 'approval',
+ sessionId: 'runtime',
+ focusSessionId: 'stored',
+ silent: true,
+ actions: [
+ { id: 'approve', text: 'Approve' },
+ { id: 'reject', text: 'Reject' }
+ ]
+ }
+
+ expect(await h.notify(payload)).toBe(true)
+ const firstId = h.lastId()
+ expect(await h.notify(payload)).toBe(true)
+ expect(h.calls.filter(call => call.member === 'Notify')).toHaveLength(1)
+ h.signal('ActionInvoked', [firstId, '1'], ':1.666')
+ expect(h.source.webContents.send).not.toHaveBeenCalled()
+ h.fail('CloseNotification', 'org.freedesktop.DBus.Error.InvalidArgs')
+ h.signal('ActionInvoked', [firstId, '1'])
+ expect(h.source.webContents.send).toHaveBeenCalledWith('hermes:notification-action', {
+ sessionId: 'runtime',
+ actionId: 'reject'
+ })
+ expect(h.primary.webContents.send).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(await h.notify({ tag: 'plugin', notifyId: 'source-callback', activate: '/plugin' })).toBe(true)
+ const pluginId = h.lastId()
+ h.source.isDestroyed.mockReturnValue(true)
+ h.signal('ActionInvoked', [pluginId, 'default'])
+ expect(h.primary.webContents.send).toHaveBeenCalledWith('hermes:notification-activate', {
+ activate: '/plugin',
+ notifyId: undefined,
+ tag: 'plugin'
+ })
+ h.connection.emit('close')
+
+ const reused = setup(true)
+ expect(await reused.notify({ tag: 'old-owner', focusSessionId: 'must-not-open' })).toBe(true)
+ const retainedId = reused.lastId()
+ reused.replaceOwner()
+ expect(await reused.notify({ tag: 'new-owner', focusSessionId: 'new-session' })).toBe(true)
+ expect(reused.lastId()).toBe(retainedId)
+ reused.signal('ActionInvoked', [retainedId, 'default'], ':1.20')
+ expect(reused.source.webContents.send).not.toHaveBeenCalled()
+ reused.signal('ActionInvoked', [retainedId, 'default'])
+ expect(reused.source.webContents.send).toHaveBeenCalledWith('hermes:focus-session', 'new-session')
+ reused.connection.emit('close')
+ }
+)
diff --git a/apps/desktop/electron/notification-linux.ts b/apps/desktop/electron/notification-linux.ts
new file mode 100644
index 00000000000..b836edf7153
--- /dev/null
+++ b/apps/desktop/electron/notification-linux.ts
@@ -0,0 +1,320 @@
+import { EventEmitter } from 'node:events'
+
+import { createClient, type Message, Variant } from 'dbus-native'
+
+const SERVICE = 'org.freedesktop.Notifications'
+const PATH = '/org/freedesktop/Notifications'
+const DBUS = 'org.freedesktop.DBus'
+const DELIVERY_TIMEOUT_MS = 5000
+const RETRY_COOLDOWN_MS = 10_000
+const MAX_PENDING = 32
+
+interface NotificationOptions {
+ title: string
+ body: string
+ silent: boolean
+ icon?: string
+ actions: { text: string }[]
+}
+
+interface Connection {
+ bus: ReturnType<typeof createClient>
+ ready: Promise<void>
+ generation: number
+ live: Map<string, { owner: string; receive: (member: string, value: unknown) => void }>
+}
+
+// Electron's Linux presenter uses synchronous libnotify calls for capabilities,
+// show AND close. Keep all of those off the main thread by using async D-Bus,
+// rather than timing a native call that prevents its own watchdog from running.
+export function createLinuxNotifications() {
+ let connection: Connection | undefined
+ let retryAfter = 0
+ let pending = 0
+
+ function connect(): Connection {
+ if (connection) {
+ return connection
+ }
+
+ // Own Hello so a rejected/timed-out handshake is a delivery failure, not
+ // dbus-native's automatic Hello callback throwing out of the event loop.
+ const bus = createClient({
+ busAddress:
+ process.env.DBUS_SESSION_BUS_ADDRESS ||
+ `unix:path=${process.env.XDG_RUNTIME_DIR || `/run/user/${process.getuid!()}`}/bus`,
+ authMethods: ['EXTERNAL'],
+ direct: true,
+ timeout: DELIVERY_TIMEOUT_MS
+ })
+
+ const state: Connection = { bus, ready: Promise.resolve(), generation: 0, live: new Map() }
+ connection = state
+
+ const disconnect = () => {
+ if (connection !== state) {
+ return
+ }
+ connection = undefined
+ state.generation++
+
+ for (const item of state.live.values()) {
+ item.receive('failed', undefined)
+ }
+ state.live.clear()
+ bus.connection.stream.destroy()
+ }
+
+ bus.connection.on('error', disconnect)
+ bus.connection.on('close', disconnect)
+ bus.connection.on('message', (message: Message) => {
+ if (message.type !== 4) {
+ return
+ }
+
+ if (
+ message.sender === DBUS &&
+ message.interface === DBUS &&
+ message.member === 'NameOwnerChanged' &&
+ message.body?.[0] === SERVICE
+ ) {
+ state.generation++
+
+ for (const item of state.live.values()) {
+ if (item.owner === message.body[1]) {
+ item.receive('failed', undefined)
+ }
+ }
+
+ return
+ }
+
+ if (message.path !== PATH || message.interface !== SERVICE || !message.member) {
+ return
+ }
+ const [id, value] = message.body ?? []
+ state.live.get(`${message.sender}:${id}`)?.receive(message.member, value)
+ })
+ state.ready = (async () => {
+ const startup = new AbortController()
+ const timer = setTimeout(() => startup.abort(), DELIVERY_TIMEOUT_MS)
+ const options = { signal: startup.signal, timeout: DELIVERY_TIMEOUT_MS }
+ try {
+ bus.name = await bus.invokeDbus<string>({ member: 'Hello' }, options)
+
+ for (const rule of [
+ `type='signal',interface='${SERVICE}',path='${PATH}'`,
+ `type='signal',sender='${DBUS}',interface='${DBUS}',member='NameOwnerChanged',arg0='${SERVICE}'`
+ ]) {
+ await bus.invokeDbus({ member: 'AddMatch', signature: 's', body: [rule] }, options)
+ }
+ } catch (error) {
+ disconnect()
+ throw error
+ } finally {
+ clearTimeout(timer)
+ }
+ })()
+
+ return state
+ }
+
+ function create(options: NotificationOptions) {
+ const notification = new EventEmitter()
+ let delivered: { state: Connection; owner: string; id: number } | undefined
+ let finished = false
+ const abort = new AbortController()
+
+ const release = () => {
+ finished = true
+
+ if (delivered) {
+ delivered.state.live.delete(`${delivered.owner}:${delivered.id}`)
+ }
+ delivered = undefined
+ }
+
+ const close = () => {
+ const target = delivered
+ abort.abort()
+ release()
+
+ if (!target || connection !== target.state) {
+ return
+ }
+ const { state, owner, id } = target
+ // The retention timer must never re-enter synchronous libnotify either.
+ void state.bus
+ .invoke(
+ {
+ destination: owner,
+ path: PATH,
+ interface: SERVICE,
+ member: 'CloseNotification',
+ signature: 'u',
+ body: [id]
+ },
+ { timeout: DELIVERY_TIMEOUT_MS }
+ )
+ .catch(() => {
+ // Already dismissed is an error in the protocol. Closing is best-effort,
+ // never retried, and must not suppress unrelated healthy deliveries.
+ })
+ }
+
+ const show = async (): Promise<boolean> => {
+ if (finished || Date.now() < retryAfter || pending >= MAX_PENDING) {
+ release()
+ notification.emit('failed')
+
+ return false
+ }
+
+ pending++
+ const timer = setTimeout(() => abort.abort(), DELIVERY_TIMEOUT_MS)
+ const callOptions = { signal: abort.signal, timeout: DELIVERY_TIMEOUT_MS }
+
+ try {
+ const state = connect()
+ await state.ready
+ const { bus } = state
+ const getOwner = () =>
+ new Promise<{ owner: string; generation: number }>((resolve, reject) => {
+ bus.invokeDbus(
+ { member: 'GetNameOwner', signature: 's', body: [SERVICE] },
+ callOptions,
+ (error, owner: string) => {
+ if (error) {
+ return reject(error)
+ }
+ // Snapshot before another message in this read batch can replace the
+ // owner. An await followed by reading generation pairs stale/new data.
+ resolve({ owner, generation: state.generation })
+ }
+ )
+ })
+ let destination: { owner: string; generation: number }
+ try {
+ destination = await getOwner()
+ } catch (error) {
+ if ((error as { dbusName?: string })?.dbusName !== 'org.freedesktop.DBus.Error.NameHasNoOwner') {
+ throw error
+ }
+ // A running daemon need not have an activation file, but an unowned
+ // activatable service is healthy too. Never make this an owner-only guard.
+ await bus.invokeDbus({ member: 'StartServiceByName', signature: 'su', body: [SERVICE, 0] }, callOptions)
+ destination = await getOwner()
+ }
+
+ const { owner, generation } = destination
+ if (state.generation !== generation) {
+ throw new Error('Notification owner changed during lookup')
+ }
+
+ const caps = await bus.invoke<string[]>(
+ { destination: owner, path: PATH, interface: SERVICE, member: 'GetCapabilities' },
+ callOptions
+ )
+
+ if (finished || connection !== state || state.generation !== generation) {
+ throw new Error('Notification owner changed before delivery')
+ }
+
+ const actions =
+ caps.includes('actions') && process.env.ELECTRON_USE_UBUNTU_NOTIFIER === undefined
+ ? ['default', 'View', ...options.actions.flatMap((action, index) => [String(index), action.text])]
+ : []
+
+ return await new Promise<boolean>((resolve, reject) => {
+ bus.invoke(
+ {
+ destination: owner,
+ path: PATH,
+ interface: SERVICE,
+ member: 'Notify',
+ signature: 'susssasa{sv}i',
+ body: [
+ 'Hermes',
+ 0,
+ options.icon || '',
+ options.title,
+ options.body,
+ actions,
+ {
+ urgency: new Variant('y', 1),
+ 'desktop-entry': new Variant('s', 'hermes'),
+ 'suppress-sound': new Variant('b', options.silent)
+ },
+ -1
+ ]
+ },
+ callOptions,
+ (error, id: number) => {
+ if (error) {
+ return reject(error)
+ }
+
+ if (
+ finished ||
+ connection !== state ||
+ state.generation !== generation ||
+ !Number.isInteger(id) ||
+ id <= 0
+ ) {
+ return reject(new Error('Notification owner changed during delivery'))
+ }
+
+ delivered = { state, owner, id }
+ // Register in the reply callback, before a signal in the same D-Bus
+ // read batch can arrive; awaiting the reply first loses that race.
+ state.live.set(`${owner}:${id}`, {
+ owner,
+ receive: (member, value) => {
+ if (finished) {
+ return
+ }
+
+ if (
+ member === 'ActionInvoked' &&
+ typeof value === 'string' &&
+ actions.some((key, index) => index % 2 === 0 && key === value)
+ ) {
+ if (value === 'default') {
+ notification.emit('click')
+ } else if (/^\d+$/.test(value) && Number(value) < options.actions.length) {
+ notification.emit('action', { actionIndex: Number(value) })
+ } else {
+ return
+ }
+
+ close()
+ } else if (member === 'NotificationClosed' || member === 'failed') {
+ release()
+ notification.emit(member === 'failed' ? 'failed' : 'close')
+ }
+ }
+ })
+ notification.emit('show')
+ resolve(true)
+ }
+ )
+ })
+ } catch {
+ // A timeout may still have delivered remotely. Never replay it, and do
+ // not discard older healthy notifications' callbacks on this connection.
+ retryAfter = Date.now() + RETRY_COOLDOWN_MS
+ release()
+ notification.emit('failed')
+
+ return false
+ } finally {
+ clearTimeout(timer)
+ pending--
+ }
+ }
+
+ return Object.assign(notification, { show, close })
+ }
+
+ return { create }
+}
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 4aa2b391bb0..34f0acba1b9 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -116,6 +116,7 @@
"clsx": "2.1.1",
"cmdk": "1.1.1",
"d3-force": "3.0.0",
+ "dbus-native": "0.15.2",
"dnd-core": "14.0.1",
"dompurify": "3.4.13",
"driver.js": "1.8.0",
diff --git a/package-lock.json b/package-lock.json
index be7de895da7..f99c70ab806 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -104,6 +104,7 @@
"clsx": "2.1.1",
"cmdk": "1.1.1",
"d3-force": "3.0.0",
+ "dbus-native": "0.15.2",
"dnd-core": "14.0.1",
"dompurify": "3.4.13",
"driver.js": "1.8.0",
@@ -9517,6 +9518,21 @@
"integrity": "sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA==",
"license": "MIT"
},
+ "node_modules/dbus-native": {
+ "version": "0.15.2",
+ "resolved": "https://registry.npmjs.org/dbus-native/-/dbus-native-0.15.2.tgz",
+ "integrity": "sha512-J1IBi4LmbqrFhroN66Dj1tCCTP6TVbZgUKhWQZf3uS6t93yRWEcRRDjOZV9N6boGRhOp/BOjLliFm9vWu1QZOA==",
+ "license": "MIT",
+ "dependencies": {
+ "xml2js": "^0.6.2"
+ },
+ "bin": {
+ "dbus-native": "bin/dbus-native.js"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -16960,7 +16976,6 @@
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz",
"integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==",
- "dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
@@ -19289,6 +19304,28 @@
"node": ">=18"
}
},
+ "node_modules/xml2js": {
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
+ "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==",
+ "license": "MIT",
+ "dependencies": {
+ "sax": ">=0.6.0",
+ "xmlbuilder": "~11.0.0"
+ },
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/xml2js/node_modules/xmlbuilder": {
+ "version": "11.0.1",
+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
+ "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
"node_modules/xmlbuilder": {
"version": "15.1.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",