Skip to content

The agent that grows with you

feat(desktop): minimize windows to tray without changing Close or Quit

brooklyn!92be0f8ed1fd
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index c80a0388290..aa6b20e2470 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -301,6 +301,7 @@ import {
import { registerMcpOauthCallbackIpc } from './mcp-oauth-callback-ipc'
import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'
import { fetchLocalMedia } from './media-range'
+import { createMinimizeToTray } from './minimize-to-tray'
import { createNativeAccessTokenCoordinator, NativeAuthChangedError } from './native-access-token'
import { oauthSessionIsLive, resolveJsonBody, resolveReadinessProbeAuth } from './native-auth-decisions'
import {
@@ -13848,6 +13849,14 @@ function wireWindowReveal(win, { show, onRevealed }: { show?: () => void; onReve
// builder live in session-windows.ts so they stay unit-testable.
const sessionWindows = createSessionWindowRegistry()
+const minimizeToTray = createMinimizeToTray({
+ preferencesPath: path.join(app.getPath('userData'), 'minimize-to-tray.json'),
+ getIconPath: getAppIconPath,
+ restoreMainWindow: () => ensureMainWindow(mainWindow, { isReady: app.isReady(), createWindow, focusWindow }),
+ isQuittingForHandoff: () => isQuittingForHandoff,
+ log: rememberLog
+})
+
function focusWindow(win) {
if (!win || win.isDestroyed()) {
return
@@ -13894,6 +13903,7 @@ function spawnSecondaryWindow({
// Chat-surface registration: applyWindowTranslucency swaps this window's
// backing between opaque-themed and alpha-0 when glass toggles.
+ minimizeToTray.registerWindow(win)
translucencyBackedWindows.add(win)
if (IS_MAC) {
@@ -14006,6 +14016,7 @@ function spawnBrowserWindow(tabId) {
recentReloadTimesRef: rendererReloadTimesRef
})
+ minimizeToTray.registerWindow(win)
win.on('closed', () => notifyBrowserPopoutClosed(tabId))
loadWindowUrl(
@@ -14080,6 +14091,7 @@ function createInstanceWindow(
})
instanceWindows.add(win)
+ minimizeToTray.registerWindow(win)
recordWindowConnectionRoute(win.webContents, { ...route, registryScoped: route.connectionId !== null })
// Chat-surface registration: see applyWindowTranslucency.
@@ -15077,6 +15089,7 @@ function createWindow() {
})
const createdMainWindow = mainWindow
+ minimizeToTray.registerWindow(createdMainWindow)
const defaultRoute = desktopProfilePreferences.getDefault()
if (defaultRoute) {
@@ -18655,6 +18668,7 @@ app.whenReady().then(() => {
configureSpellChecker()
registerPowerResumeListeners()
keepAwake.set(readPersistedKeepAwake())
+ void minimizeToTray.start()
f12Blocked = readPersistedDisableF12()
// Seed this before the first window exists: a picker can open before
// startHermes() finishes resolving the configured backend.
@@ -18736,12 +18750,22 @@ function configureSpellChecker() {
// and the confirmation is on screen; "Quit Anyway" re-enters before-quit with
// the latch set and falls straight through to the teardown below.
function heldQuitForActiveWork(event: Electron.Event): boolean {
- if (SKIP_QUIT_CONFIRM || quitConfirmedWithActiveWork || quitPromptOpen) {
+ if (SKIP_QUIT_CONFIRM || quitConfirmedWithActiveWork || isQuittingForHandoff) {
return false
}
+ if (quitPromptOpen) {
+ event.preventDefault()
+ return true
+ }
+
const prompt = quitPromptFor(mergeActiveWork(activeWorkByWebContents.values()), isQuittingForHandoff)
+ // A tray quit with live work still needs the ordinary visible confirmation.
+ if (prompt && minimizeToTray.status().available) {
+ minimizeToTray.restore()
+ }
+
// A hidden aux window must never parent the quit prompt: the dialog would
// be invisible and the held quit unanswerable (#116376 §E).
const parent = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows().find(window => window.isVisible())
@@ -18787,6 +18811,8 @@ app.on('before-quit', event => {
return
}
+ minimizeToTray.beginQuit()
+
// A detached remote updater can outlive this Electron process. Do not tear
// down its SSH observer/restore transaction at the generic SSH shutdown
// deadline: join it first (BEFORE sealing the bootstrap coordinator, whose
diff --git a/apps/desktop/electron/minimize-to-tray-native-fixture/main.ts b/apps/desktop/electron/minimize-to-tray-native-fixture/main.ts
new file mode 100644
index 00000000000..13919123905
--- /dev/null
+++ b/apps/desktop/electron/minimize-to-tray-native-fixture/main.ts
@@ -0,0 +1,117 @@
+// Targeted native lifecycle probe: compile this fixture with esbuild (external:
+// electron, dbus-native), then run Electron <fixture.cjs> <fresh userData> <icon>.
+// No backend, renderer dev server, CDP listener, or real user state is touched.
+import assert from 'node:assert/strict'
+import { once } from 'node:events'
+import path from 'node:path'
+import { setTimeout as delay } from 'node:timers/promises'
+
+import { app, BrowserWindow } from 'electron'
+
+import { createMinimizeToTray } from '../minimize-to-tray'
+
+app.setPath('userData', process.argv[2])
+app.on('window-all-closed', () => {})
+const watchdog = setTimeout(() => {
+ console.error('Native tray probe timed out')
+ app.exit(1)
+}, 20_000)
+
+async function run() {
+ await app.whenReady()
+ const primary = new BrowserWindow({ width: 440, height: 320, show: false })
+ const peer = new BrowserWindow({ width: 440, height: 320, show: false })
+
+ const controller = createMinimizeToTray({
+ preferencesPath: path.join(app.getPath('userData'), 'minimize-to-tray.json'),
+ getIconPath: () => process.argv[3],
+ restoreMainWindow: () => {
+ primary.show()
+ primary.focus()
+ },
+ isQuittingForHandoff: () => false,
+ log: console.log
+ })
+
+ controller.registerWindow(primary)
+ controller.registerWindow(peer)
+ const html =
+ 'data:text/html,<title>Hermes tray lifecycle probe</title><p>Isolated tray lifecycle probe</p><script>window.draft="preserved"</script>'
+ await Promise.all([primary.loadURL(html), peer.loadURL(html)])
+ primary.show()
+ peer.show()
+ assert.deepEqual(await controller.start(), { enabled: false, available: false })
+ assert.deepEqual(await controller.setEnabled(true), { enabled: true, available: true })
+ const primaryMinimized = once(primary, 'minimize')
+ primary.minimize()
+ await primaryMinimized
+ await delay(250)
+ assert.equal(primary.isDestroyed(), false)
+ assert.equal(primary.isVisible(), false)
+ assert.equal(peer.isVisible(), true)
+
+ if (process.platform === 'darwin') {
+ assert.equal(app.dock!.isVisible(), true)
+ }
+ const minimized = once(peer, 'minimize')
+ peer.minimize()
+ await minimized
+ await delay(250)
+ assert.equal(peer.isVisible(), false)
+
+ if (process.platform === 'darwin') {
+ assert.equal(app.dock!.isVisible(), false)
+ }
+ assert.equal(await primary.webContents.executeJavaScript('window.draft'), 'preserved')
+ controller.restore()
+ await delay(250)
+ assert.equal(primary.isVisible(), true)
+ assert.equal(peer.isVisible(), true)
+ assert.equal(peer.isMinimized(), false)
+
+ if (process.platform === 'darwin') {
+ assert.equal(app.dock!.isVisible(), true)
+ }
+ primary.minimize()
+ await delay(250)
+ peer.close()
+ assert.equal(peer.isDestroyed(), true)
+ assert.equal(primary.isDestroyed(), false)
+ await controller.setEnabled(false)
+ assert.equal(primary.isVisible(), true)
+ assert.equal(controller.status().available, false)
+ await controller.setEnabled(true)
+ primary.minimize()
+ await delay(250)
+ app.on('before-quit', () => controller.beginQuit())
+ app.on('will-quit', () => {
+ assert.equal(primary.isDestroyed(), true)
+ clearTimeout(watchdog)
+ console.log(
+ JSON.stringify({
+ ok: true,
+ platform: process.platform,
+ checks: [
+ 'default off',
+ 'native tray creation',
+ 'primary minimize preserves renderer',
+ 'visible peer retains Dock',
+ 'native minimize hides peer',
+ 'last hidden window removes Dock',
+ 'renderer draft survives',
+ 'restore reveals all tray-hidden windows and Dock',
+ 'peer close remains close',
+ 'disable restores before destroying tray',
+ 'explicit quit exits'
+ ]
+ })
+ )
+ })
+ app.quit()
+}
+
+void run().catch(error => {
+ clearTimeout(watchdog)
+ console.error(error)
+ app.exit(1)
+})
diff --git a/apps/desktop/electron/minimize-to-tray.test.ts b/apps/desktop/electron/minimize-to-tray.test.ts
new file mode 100644
index 00000000000..a976b606c9d
--- /dev/null
+++ b/apps/desktop/electron/minimize-to-tray.test.ts
@@ -0,0 +1,209 @@
+import { EventEmitter } from 'node:events'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import type { BrowserWindow } from 'electron'
+import { afterEach, beforeEach, expect, test, vi } from 'vitest'
+
+const native = vi.hoisted(() => ({
+ app: { on: vi.fn(), quit: vi.fn(), dock: { show: vi.fn(), hide: vi.fn() } },
+ ipc: new Map<string, (...args: any[]) => any>(),
+ windows: [] as any[],
+ trays: [] as any[],
+ fail: false
+}))
+
+vi.mock('electron', () => ({
+ app: native.app,
+ ipcMain: { handle: (name: string, fn: (...args: any[]) => any) => native.ipc.set(name, fn) },
+ BrowserWindow: { getAllWindows: () => native.windows },
+ Menu: { buildFromTemplate: (items: unknown[]) => items },
+ nativeImage: { createFromPath: () => ({ isEmpty: () => false, resize: () => ({}) }) },
+ Tray: class extends EventEmitter {
+ destroyed = false
+ menu: any[] = []
+ constructor() {
+ super()
+
+ if (native.fail) {
+ throw new Error('Unavailable tray')
+ }
+ native.trays.push(this)
+ }
+ setToolTip() {}
+ setContextMenu(menu: any[]) {
+ this.menu = menu
+ }
+ destroy() {
+ this.destroyed = true
+ }
+ isDestroyed() {
+ return this.destroyed
+ }
+ }
+}))
+vi.mock('./tray-host', () => ({ watchLinuxTrayHost: async () => () => {} }))
+
+import { createMinimizeToTray } from './minimize-to-tray'
+
+class Window extends EventEmitter {
+ visible = true
+ minimized = false
+ destroyed = false
+ skipped = false
+ webContents = { send: vi.fn() }
+ isDestroyed() {
+ return this.destroyed
+ }
+ isVisible() {
+ return this.visible
+ }
+ isMinimized() {
+ return this.minimized
+ }
+ setSkipTaskbar(on: boolean) {
+ this.skipped = on
+ }
+ hide() {
+ this.visible = false
+ this.emit('hide')
+ }
+ showInactive() {
+ this.visible = true
+ this.emit('show')
+ }
+ restore() {
+ this.minimized = false
+ this.visible = true
+ this.emit('restore')
+ }
+ minimize() {
+ this.minimized = true
+ this.emit('minimize')
+ }
+ close() {
+ const event = { preventDefault: vi.fn() }
+ this.emit('close', event)
+
+ if (!event.preventDefault.mock.calls.length) {
+ this.destroyed = true
+ this.emit('closed')
+ }
+
+ return event
+ }
+}
+
+let home: string
+beforeEach(() => {
+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-tray-'))
+ native.windows = []
+ native.trays = []
+ native.fail = false
+ vi.clearAllMocks()
+})
+afterEach(() => fs.rmSync(home, { recursive: true, force: true }))
+
+function setup() {
+ const main = new Window()
+ const peer = new Window()
+ native.windows.push(main, peer)
+ let handoff = false
+
+ const controller = createMinimizeToTray({
+ preferencesPath: path.join(home, 'minimize-to-tray.json'),
+ getIconPath: () => 'icon.png',
+ restoreMainWindow: () => main.showInactive(),
+ isQuittingForHandoff: () => handoff,
+ log: vi.fn()
+ })
+
+ controller.registerWindow(main as unknown as BrowserWindow)
+ controller.registerWindow(peer as unknown as BrowserWindow)
+
+ return {
+ controller,
+ main,
+ peer,
+ handoff: () => {
+ handoff = true
+ }
+ }
+}
+
+test('opt-in minimize preserves windows and restoration, without intercepting Close or Quit', async () => {
+ const { controller, main, peer } = setup()
+ expect(await controller.start()).toEqual({ enabled: false, available: false })
+ main.minimize()
+ expect(main.visible).toBe(true)
+ main.restore()
+ await native.ipc.get('hermes:minimize-to-tray:set')!(null, true)
+ expect(native.ipc.get('hermes:minimize-to-tray:get')!()).toEqual({ enabled: true, available: true })
+ main.minimize()
+ expect(main.destroyed).toBe(false)
+ expect(main.visible).toBe(false)
+ expect(peer.visible).toBe(true)
+
+ if (process.platform === 'darwin') {
+ expect(native.app.dock.hide).not.toHaveBeenCalled()
+ }
+ peer.minimize()
+ expect(peer.visible).toBe(false)
+
+ if (process.platform === 'darwin') {
+ expect(native.app.dock.hide).toHaveBeenCalled()
+ }
+
+ if (process.platform === 'win32') {
+ expect(main.skipped && peer.skipped).toBe(true)
+ }
+ native.trays[0].menu[0].click()
+ expect(main.visible && peer.visible).toBe(true)
+ expect(main.minimized || peer.minimized).toBe(false)
+ expect(main.skipped || peer.skipped).toBe(false)
+ peer.close()
+ expect(peer.destroyed).toBe(true)
+ main.minimize()
+ native.trays[0].menu[2].click()
+ expect(native.app.quit).toHaveBeenCalledOnce()
+ // A cancelled guard doesn't call beginQuit; hide remains enabled.
+ controller.restore()
+ main.minimize()
+ expect(main.destroyed).toBe(false)
+ expect(main.visible).toBe(false)
+ // Native Close and Alt+F4 are never cancelled, even with the tray enabled.
+ expect(main.close().preventDefault).not.toHaveBeenCalled()
+ expect(main.destroyed).toBe(true)
+ controller.beginQuit()
+ native.app.on.mock.calls.find(([event]) => event === 'will-quit')![1]()
+ expect(native.trays[0].destroyed).toBe(true)
+})
+
+test('persistence, disabling, failed tray creation, and handoff never strand hidden windows', async () => {
+ const first = setup()
+ await first.controller.start()
+ await first.controller.setEnabled(true)
+ first.main.minimize()
+ await first.controller.setEnabled(false)
+ expect(first.main.visible).toBe(true)
+ expect(native.trays[0].destroyed).toBe(true)
+ await first.controller.setEnabled(true)
+ const restarted = setup()
+ expect(await restarted.controller.start()).toEqual({ enabled: true, available: true })
+ restarted.handoff()
+ restarted.main.close()
+ expect(restarted.main.destroyed).toBe(true)
+ const failed = setup()
+ native.fail = true
+ expect(await failed.controller.start()).toEqual({ enabled: true, available: false })
+ failed.main.minimize()
+ expect(failed.main.visible).toBe(true)
+ failed.main.close()
+ expect(failed.main.destroyed).toBe(true)
+ fs.writeFileSync(path.join(home, 'minimize-to-tray.json'), 'bad json')
+ const disabled = setup()
+ expect(await disabled.controller.start()).toEqual({ enabled: false, available: false })
+ disabled.main.close()
+ expect(disabled.main.destroyed).toBe(true)
+})
diff --git a/apps/desktop/electron/minimize-to-tray.ts b/apps/desktop/electron/minimize-to-tray.ts
new file mode 100644
index 00000000000..54a4f8571d5
--- /dev/null
+++ b/apps/desktop/electron/minimize-to-tray.ts
@@ -0,0 +1,265 @@
+import fs from 'node:fs'
+import path from 'node:path'
+
+import { app, BrowserWindow, ipcMain, Menu, nativeImage, Tray } from 'electron'
+
+export interface MinimizeToTrayStatus {
+ enabled: boolean
+ available: boolean
+}
+
+interface Options {
+ preferencesPath: string
+ getIconPath: () => string | undefined
+ restoreMainWindow: () => void
+ isQuittingForHandoff: () => boolean
+ log: (message: string) => void
+}
+
+/** Device-local native preference; renderer windows only cache its status. */
+export function createMinimizeToTray(options: Options) {
+ let enabled = false
+ let quitting = false
+ let tray: Tray | null = null
+ let stopWatchingHost: (() => void) | undefined
+ let dockHidden = false
+ let hostGeneration = 0
+ let pending = Promise.resolve()
+ const windows = new Set<BrowserWindow>()
+ const hidden = new Set<BrowserWindow>()
+
+ const status = (): MinimizeToTrayStatus => ({ enabled, available: !!tray && !tray.isDestroyed() })
+
+ const broadcast = () => {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) {
+ win.webContents.send('hermes:minimize-to-tray:changed', status())
+ }
+ }
+ }
+
+ const showDock = () => {
+ if (dockHidden) {
+ dockHidden = false
+ void app.dock?.show()
+ }
+ }
+
+ const syncDock = () => {
+ if (process.platform !== 'darwin') {
+ return
+ }
+ // A hidden primary must not remove a visible peer from Cmd-Tab/the Dock.
+ const foreground = [...windows].some(win => !win.isDestroyed() && win.isVisible() && !win.isMinimized())
+
+ if (status().available && hidden.size > 0 && !foreground && !quitting) {
+ dockHidden = true
+ app.dock?.hide()
+ } else {
+ showDock()
+ }
+ }
+
+ const released = (win: BrowserWindow) => {
+ if (!hidden.delete(win)) {
+ return
+ }
+
+ if (process.platform === 'win32') {
+ win.setSkipTaskbar(false)
+ }
+ showDock()
+ }
+
+ const restoreHidden = () => {
+ showDock()
+
+ for (const win of [...hidden]) {
+ if (win.isDestroyed()) {
+ hidden.delete(win)
+
+ continue
+ }
+
+ released(win)
+
+ if (win.isMinimized()) {
+ win.restore()
+ }
+ win.showInactive()
+ }
+ }
+
+ const restore = () => {
+ restoreHidden()
+ options.restoreMainWindow()
+ }
+
+ const destroyTray = () => {
+ stopWatchingHost?.()
+ stopWatchingHost = undefined
+ tray?.destroy()
+ tray = null
+ }
+
+ const hostLost = () => {
+ // Losing the shell/tray must never strand an invisible app.
+ hostGeneration += 1
+ restoreHidden()
+ destroyTray()
+ broadcast()
+ }
+
+ const apply = async (on: boolean) => {
+ enabled = on
+
+ if (!on) {
+ restoreHidden()
+ destroyTray()
+ } else if (!status().available && !quitting) {
+ try {
+ if (process.platform === 'linux') {
+ const { watchLinuxTrayHost } = await import('./tray-host')
+ const generation = hostGeneration
+ stopWatchingHost = await watchLinuxTrayHost(hostLost)
+
+ if (generation !== hostGeneration) {
+ throw new Error('System tray host disappeared')
+ }
+ }
+
+ if (quitting) {
+ destroyTray()
+
+ return status()
+ }
+
+ const iconPath = options.getIconPath()
+ const icon = iconPath ? nativeImage.createFromPath(iconPath) : nativeImage.createEmpty()
+
+ if (icon.isEmpty()) {
+ throw new Error('No usable tray icon')
+ }
+ tray = new Tray(
+ icon.resize({
+ width: process.platform === 'darwin' ? 18 : 24,
+ height: process.platform === 'darwin' ? 18 : 24
+ })
+ )
+ tray.setToolTip('Hermes')
+ tray.setContextMenu(
+ Menu.buildFromTemplate([
+ { label: 'Show Hermes', click: restore },
+ { type: 'separator' },
+ // Do not bypass the ordinary active-work confirmation or teardown.
+ { label: 'Quit Hermes', click: () => app.quit() }
+ ])
+ )
+
+ // macOS single-click opens the native menu, not the window behind it.
+ if (process.platform !== 'darwin') {
+ tray.on('click', restore)
+ }
+ tray.on('double-click', restore)
+ } catch (error) {
+ restoreHidden()
+ destroyTray()
+ options.log(`[tray] unavailable; ordinary window behavior retained: ${error}`)
+ }
+ }
+
+ broadcast()
+
+ return status()
+ }
+
+ function registerWindow(win: BrowserWindow) {
+ windows.add(win)
+
+ const hide = () => {
+ if (!enabled || !status().available || quitting || options.isQuittingForHandoff()) {
+ return
+ }
+ hidden.add(win)
+
+ if (process.platform === 'win32') {
+ win.setSkipTaskbar(true)
+ }
+ win.hide()
+ syncDock()
+ }
+
+ win.on('minimize', hide)
+ // Close (including Alt+F4) and explicit Quit keep their ordinary meaning.
+ // Windows session ending need not emit app.before-quit. Never hold it open.
+ win.on('query-session-end', () => {
+ quitting = true
+ })
+ win.on('show', () => {
+ released(win)
+ syncDock()
+ })
+ win.on('restore', () => {
+ released(win)
+ syncDock()
+ })
+ win.on('closed', () => {
+ windows.delete(win)
+ hidden.delete(win)
+ syncDock()
+ })
+ }
+
+ async function start() {
+ let on = false
+
+ try {
+ on = JSON.parse(fs.readFileSync(options.preferencesPath, 'utf8')).enabled === true
+ } catch {
+ // Missing or malformed preference preserves ordinary minimize/close.
+ }
+
+ const operation = apply(on)
+ pending = operation.then(
+ () => undefined,
+ () => undefined
+ )
+
+ return operation
+ }
+
+ function setEnabled(on: boolean): Promise<MinimizeToTrayStatus> {
+ // Serialize writes from peer windows so an older native apply cannot win.
+ const operation = pending.then(async () => {
+ fs.mkdirSync(path.dirname(options.preferencesPath), { recursive: true })
+ fs.writeFileSync(`${options.preferencesPath}.tmp`, JSON.stringify({ enabled: on === true }), 'utf8')
+ fs.renameSync(`${options.preferencesPath}.tmp`, options.preferencesPath)
+
+ return apply(on === true)
+ })
+
+ pending = operation.then(
+ () => undefined,
+ () => undefined
+ )
+
+ return operation
+ }
+
+ ipcMain.handle('hermes:minimize-to-tray:get', status)
+ ipcMain.handle('hermes:minimize-to-tray:set', (_event, on) => setEnabled(on === true))
+ app.on('will-quit', destroyTray)
+
+ return {
+ start,
+ status,
+ setEnabled,
+ registerWindow,
+ restore,
+ // Call only AFTER the active-work guard accepts the quit. Cancelling the
+ // prompt must leave hiding and its recovery affordance intact.
+ beginQuit: () => {
+ quitting = true
+ }
+ }
+}
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 844f20a1d41..083fd0ad86b 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -357,6 +357,15 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
setNativeTheme: mode => ipcRenderer.send('hermes:native-theme', mode),
setTranslucency: payload => ipcRenderer.send('hermes:translucency', payload),
setKeepAwake: on => ipcRenderer.send('hermes:keep-awake', on),
+ minimizeToTray: {
+ get: () => ipcRenderer.invoke('hermes:minimize-to-tray:get'),
+ set: on => ipcRenderer.invoke('hermes:minimize-to-tray:set', on),
+ onChanged: callback => {
+ const listener = (_event, status) => callback(status)
+ ipcRenderer.on('hermes:minimize-to-tray:changed', listener)
+ return () => ipcRenderer.removeListener('hermes:minimize-to-tray:changed', listener)
+ }
+ },
setDisableF12: blocked => ipcRenderer.send('hermes:devtools:disable-f12', blocked),
setPreviewShortcutActive: active => ipcRenderer.send('hermes:previewShortcutActive', Boolean(active)),
openExternal: url => ipcRenderer.invoke('hermes:openExternal', url),
diff --git a/apps/desktop/electron/tray-host.test.ts b/apps/desktop/electron/tray-host.test.ts
new file mode 100644
index 00000000000..2f704df62c2
--- /dev/null
+++ b/apps/desktop/electron/tray-host.test.ts
@@ -0,0 +1,53 @@
+import { EventEmitter } from 'node:events'
+
+import { expect, test, vi } from 'vitest'
+
+const createClient = vi.hoisted(() => vi.fn())
+vi.mock('dbus-native', () => ({ createClient }))
+
+import { watchLinuxTrayHost } from './tray-host'
+
+function bus(hostRegistered: boolean) {
+ const connection = Object.assign(new EventEmitter(), { stream: { destroy: vi.fn() } })
+ const invoke = vi.fn(async () => ({ signature: 'b', value: hostRegistered }))
+
+ const instance = {
+ connection,
+ invoke,
+ invokeDbus: vi.fn(async ({ member }: { member: string }) => (member === 'GetNameOwner' ? ':1.42' : ':1.99'))
+ }
+
+ createClient.mockReturnValue(instance)
+
+ return instance
+}
+
+test('a registered host is required, and losing its owner reports loss exactly once', async () => {
+ const instance = bus(true)
+ const lost = vi.fn()
+ const dispose = await watchLinuxTrayHost(lost)
+ expect(lost).not.toHaveBeenCalled()
+ instance.connection.emit('message', {
+ type: 4,
+ sender: 'org.freedesktop.DBus',
+ interface: 'org.freedesktop.DBus',
+ member: 'NameOwnerChanged',
+ body: ['org.kde.StatusNotifierWatcher', ':1.42', '']
+ })
+ instance.connection.emit('close')
+ expect(lost).toHaveBeenCalledOnce()
+ expect(instance.connection.stream.destroy).toHaveBeenCalledOnce()
+ dispose()
+})
+
+test('a missing host and a failed query reject without leaving an open bus connection', async () => {
+ const lost = vi.fn()
+ const absent = bus(false)
+ await expect(watchLinuxTrayHost(lost)).rejects.toThrow('No system tray host')
+ expect(absent.connection.stream.destroy).toHaveBeenCalledOnce()
+ expect(lost).not.toHaveBeenCalled()
+ const failed = bus(true)
+ failed.invoke.mockRejectedValue(new Error('D-Bus unavailable'))
+ await expect(watchLinuxTrayHost(lost)).rejects.toThrow('D-Bus unavailable')
+ expect(failed.connection.stream.destroy).toHaveBeenCalledOnce()
+})
diff --git a/apps/desktop/electron/tray-host.ts b/apps/desktop/electron/tray-host.ts
new file mode 100644
index 00000000000..e57ce8eee61
--- /dev/null
+++ b/apps/desktop/electron/tray-host.ts
@@ -0,0 +1,106 @@
+import { createClient, type Message, type Variant } from 'dbus-native'
+
+// Electron can construct a Linux Tray even when the desktop has no tray host
+// (notably stock GNOME). Never use that object alone as proof of a restore path.
+export async function watchLinuxTrayHost(onLost: () => void): Promise<() => void> {
+ const service = 'org.kde.StatusNotifierWatcher'
+
+ 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: 2000
+ })
+
+ let disposed = false
+ let ready = false
+ let owner = ''
+
+ const dispose = () => {
+ if (disposed) {
+ return
+ }
+ disposed = true
+ bus.connection.stream.destroy()
+ }
+
+ const lost = () => {
+ if (disposed) {
+ return
+ }
+ dispose()
+
+ if (ready) {
+ onLost()
+ }
+ }
+
+ bus.connection.on('error', lost)
+ bus.connection.on('close', lost)
+ bus.connection.on('message', (message: Message) => {
+ if (message.type !== 4) {
+ return
+ }
+
+ if (
+ message.sender === 'org.freedesktop.DBus' &&
+ message.interface === 'org.freedesktop.DBus' &&
+ message.member === 'NameOwnerChanged' &&
+ message.body?.[0] === service &&
+ message.body[1] === owner
+ ) {
+ lost()
+ }
+
+ if (
+ message.sender === owner &&
+ message.path === '/StatusNotifierWatcher' &&
+ message.interface === service &&
+ message.member === 'StatusNotifierHostUnregistered'
+ ) {
+ lost()
+ }
+ })
+ const abort = new AbortController()
+ const timer = setTimeout(() => abort.abort(), 2000)
+ const options = { signal: abort.signal, timeout: 2000 }
+
+ try {
+ bus.name = await bus.invokeDbus<string>({ member: 'Hello' }, options)
+
+ for (const rule of [
+ `type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='${service}'`,
+ `type='signal',interface='${service}',member='StatusNotifierHostUnregistered'`
+ ]) {
+ await bus.invokeDbus({ member: 'AddMatch', signature: 's', body: [rule] }, options)
+ }
+
+ owner = await bus.invokeDbus<string>({ member: 'GetNameOwner', signature: 's', body: [service] }, options)
+
+ const value = await bus.invoke<Variant>(
+ {
+ destination: owner,
+ path: '/StatusNotifierWatcher',
+ interface: 'org.freedesktop.DBus.Properties',
+ member: 'Get',
+ signature: 'ss',
+ body: [service, 'IsStatusNotifierHostRegistered']
+ },
+ options
+ )
+
+ if (disposed || value.value !== true) {
+ throw new Error('No system tray host is available')
+ }
+ ready = true
+
+ return dispose
+ } catch (error) {
+ dispose()
+ throw error
+ } finally {
+ clearTimeout(timer)
+ }
+}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 53716ba2cb6..6467d2d8938 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -378,6 +378,11 @@ declare global {
skipIntro?: boolean
setTranslucency?: (payload: TranslucencyState) => void
setKeepAwake?: (on: boolean) => void
+ minimizeToTray?: {
+ get: () => Promise<{ enabled: boolean; available: boolean }>
+ set: (on: boolean) => Promise<{ enabled: boolean; available: boolean }>
+ onChanged: (callback: (status: { enabled: boolean; available: boolean }) => void) => () => void
+ }
setDisableF12?: (blocked: boolean) => void
setPreviewShortcutActive?: (active: boolean) => void
openExternal: (url: string) => Promise<void>