The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): leaving HUD mode always gives the app window back (macOS)
Teknium8092f0e8eeb6
diff --git a/apps/desktop/electron/hud-close.test.ts b/apps/desktop/electron/hud-close.test.tsnew file mode 100644index 00000000000..7cd3e8adf6b--- /dev/null+++ b/apps/desktop/electron/hud-close.test.ts@@ -0,0 +1,69 @@+import assert from 'node:assert/strict'++import { test, vi } from 'vitest'++import { HUD_CLOSE_GRACE_MS, type HudCloseWindowLike, requestHudClose } from './hud-close'++function fakeWindow() {+ let destroyed = false+ let closedListener: (() => void) | null = null++ const win: HudCloseWindowLike & { closeCalls: number; destroyCalls: number; emitClosed(): void } = {+ closeCalls: 0,+ destroyCalls: 0,+ close() {+ this.closeCalls += 1+ },+ destroy() {+ this.destroyCalls += 1+ destroyed = true+ closedListener?.()+ },+ isDestroyed: () => destroyed,+ once(_event, listener) {+ closedListener = listener+ },+ emitClosed() {+ destroyed = true+ closedListener?.()+ }+ }++ return win+}++test('a renderer that answers the close is never destroyed', () => {+ vi.useFakeTimers()++ try {+ const win = fakeWindow()++ requestHudClose(win)+ assert.equal(win.closeCalls, 1)++ win.emitClosed()+ vi.advanceTimersByTime(HUD_CLOSE_GRACE_MS * 2)++ assert.equal(win.destroyCalls, 0)+ } finally {+ vi.useRealTimers()+ }+})++test('a renderer that never answers is destroyed at the grace deadline', () => {+ vi.useFakeTimers()++ try {+ const win = fakeWindow()++ requestHudClose(win)+ vi.advanceTimersByTime(HUD_CLOSE_GRACE_MS - 1)+ assert.equal(win.destroyCalls, 0)++ vi.advanceTimersByTime(1)+ assert.equal(win.destroyCalls, 1)+ assert.equal(win.isDestroyed(), true)+ } finally {+ vi.useRealTimers()+ }+})diff --git a/apps/desktop/electron/hud-close.ts b/apps/desktop/electron/hud-close.tsnew file mode 100644index 00000000000..c66b58330d3--- /dev/null+++ b/apps/desktop/electron/hud-close.ts@@ -0,0 +1,53 @@+/**+ * Bounded graceful close for the HUD window.+ *+ * `win.close()` is a request, not an action: Electron asks the renderer to run+ * its beforeunload/unload handlers and only destroys the window once it+ * answers. That round-trip is what lets the HUD flush a half-typed draft into+ * the shared stash the app window re-reads on handoff — but a renderer that is+ * hung never answers, and an always-on-top window that never closes is exactly+ * the "HUD won't go away" report. Electron's own escalation is a 5 s+ * `unresponsive` event nobody acts on.+ *+ * So: ask nicely, then take the window away if the renderer has not let go by+ * the grace deadline. Pure and timer-injected so the deadline is testable.+ */++export interface HudCloseWindowLike {+ close(): void+ destroy(): void+ isDestroyed(): boolean+ once(event: 'closed', listener: () => void): unknown+}++interface HudCloseTimers {+ setTimer?: (fn: () => void, ms: number) => unknown+ clearTimer?: (handle: unknown) => void+}++/** How long a HUD renderer gets to answer the close before it is destroyed.+ * A healthy beforeunload round-trip is tens of milliseconds; a transcript+ * flush on a slow machine still fits comfortably. */+export const HUD_CLOSE_GRACE_MS = 1500++export function requestHudClose(+ win: HudCloseWindowLike,+ {+ setTimer = (fn, ms) => setTimeout(fn, ms),+ clearTimer = handle => clearTimeout(handle as ReturnType<typeof setTimeout>)+ }: HudCloseTimers = {},+ graceMs: number = HUD_CLOSE_GRACE_MS+): void {+ if (win.isDestroyed()) {+ return+ }++ const deadline = setTimer(() => {+ if (!win.isDestroyed()) {+ win.destroy()+ }+ }, graceMs)++ win.once('closed', () => clearTimer(deadline))+ win.close()+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex e68c47879a6..4fb88c2d4d2 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -221,6 +221,7 @@ import {tightenSecretFileMode,writeSecretFileAtomic} from './hardening'+import { requestHudClose } from './hud-close'import { cursorPointInWindow } from './hud-cursor'import { startHudGameOverlayWatch } from './hud-game-overlay'import { applyHudResetBounds, defaultHudBounds } from './hud-geometry'@@ -7085,6 +7086,17 @@ function installPreviewShortcut(window) {// — no `previewShortcutActive` gate, so it works for every closeable tab.if (isCloseTabShortcut) {event.preventDefault()++ // ⌘W in the HUD is "leave HUD mode", not "close a tab in the app+ // window". Routing it to the main renderer closed the app's tab out+ // from under the user while the HUD stayed put; routing it through the+ // HUD's own close path hands the session back like the exit button.+ if (hudWindow && !hudWindow.isDestroyed() && window === hudWindow) {+ closeHudWindow()++ return+ }+sendClosePreviewRequested()return@@ -13879,11 +13891,13 @@ function closePetOverlay() {// app's composer (slash commands, attachments, queue, voice) instead of a// lookalike that drifts. Entering HUD mode hides the main window; leaving// restores it.-let hudWindow = null+let hudWindow: BrowserWindow | null = null-// Whether the main window was visible when HUD mode was entered, so exiting-// puts the desktop back as it was rather than raising a window the user had-// already minimized.+// Whether closing the HUD should bring the main window back. Armed whenever a+// live main window exists at HUD-open time, visible or not: the HUD hides the+// app window itself, so a main window minimized or behind another app when+// the HUD opened still needs a surface back — arming only on `isVisible()`+// left the user with NO Hermes window after the second toggle (#88513).let hudRestoreMainWindow = false// The session the HUD is currently on, reported by its renderer whenever the@@ -14274,16 +14288,17 @@ function spawnHudWindow(sessionId, profile) {win.on('closed', () => {if (hudWindow === win) {hudWindow = null+ } else if (hudWindow && !hudWindow.isDestroyed()) {+ // Superseded by a profile respawn: the replacement owns the shortcut,+ // the main-window restore and the toggles. Nothing to hand back.+ return}- // Closed from its own side (⌘W) — closeHudWindow()'s dispose() never ran,- // so the global snap shortcut would otherwise stay registered (and stuck- // taken) with no HUD left to apply it to. dispose() is idempotent, so- // this is safe even if closeHudWindow() already released it.+ // Whether the close came from closeHudWindow() or from the window's own+ // side (a crashed renderer, a native close), this is the one teardown:+ // release the global snap shortcut, put the app back so the user is never+ // left with no surface, and correct every window's toggle.hudSnapShortcut.dispose()-- // Put the app back so the user is never left with no surface, and- // correct every window's toggle.restoreMainWindowFromHud()broadcastHudState(false)})@@ -14297,17 +14312,31 @@ function spawnHudWindow(sessionId, profile) {return win}-// Put the app window back the way HUD mode found it.+// Put the app window back, and give it the keyboard. `focusWindow`, not a bare+// `show()`: show() alone leaves a minimized window minimized, and on macOS a+// shown-but-not-key window means the user is looking at the app with the+// caret still belonging to whatever the HUD was floating over.function restoreMainWindowFromHud() {if (!hudRestoreMainWindow) {return}hudRestoreMainWindow = false+ focusWindow(mainWindow)+}- if (mainWindow && !mainWindow.isDestroyed()) {- mainWindow.show()+// Take the HUD window down. The 'closed' handler stays attached so ONE path+// owns the teardown (snap shortcut, main-window restore, close broadcast)+// whether the window went via the exit button, ⌘W, a profile respawn, or the+// grace deadline — detaching it before close() was how a renderer that never+// answered the close left an always-on-top HUD nobody could dismiss and no+// broadcast to correct the toggles.+function destroyHudWindow(win: BrowserWindow) {+ if (hudWindow === win) {+ hudWindow = null}++ requestHudClose(win)}function openHudWindow(sessionId, profile) {@@ -14317,16 +14346,16 @@ function openHudWindow(sessionId, profile) {// Pointed at another PROFILE: the live renderer is bound to the old// profile's backend, and a renderer adopts its backend exactly once at// boot — an in-place goto would resolve the id against the wrong backend- // (the #82285 fallback). Respawn against the right one.+ // (the #82285 fallback). Respawn against the right one. The old window's+ // 'closed' handler sees `hudWindow` already pointing at the replacement,+ // so it neither restores main nor broadcasts a false "closed".if (profileKey && hudProfile !== profileKey) {- const win = hudWindow- hudWindow = null- win.removeAllListeners('closed')- win.destroy()+ const previous = hudWindowhudSessionId = sessionId || nullhudProfile = profileKeyhudWindow = spawnHudWindow(sessionId, profileKey)+ previous.destroy()broadcastHudState(true)registerHudSnapShortcut()@@ -14349,7 +14378,7 @@ function openHudWindow(sessionId, profile) {return hudWindow}- hudRestoreMainWindow = Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible())+ hudRestoreMainWindow = Boolean(mainWindow && !mainWindow.isDestroyed())hudSessionId = sessionId || nullhudProfile = profileKeyhudWindow = spawnHudWindow(sessionId, profileKey)@@ -14360,23 +14389,20 @@ function openHudWindow(sessionId, profile) {}function closeHudWindow() {- hudSnapShortcut.dispose()-const win = hudWindow- hudWindow = nullif (win && !win.isDestroyed()) {- // Null'd first so the 'closed' handler doesn't broadcast a second time.- win.removeAllListeners('closed')- win.close()+ destroyHudWindow(win)++ return}+ // No live HUD (a renderer that died, a toggle racing the close): still+ // release what an open HUD holds, so the toggles read right.+ hudWindow = null+ hudSnapShortcut.dispose()restoreMainWindowFromHud()broadcastHudState(false)-- if (mainWindow && !mainWindow.isDestroyed()) {- focusWindow(mainWindow)- }}// ── Quick Entry ─────────────────────────────────────────────────────────────diff --git a/apps/desktop/src/app/hud/handoff.test.tsx b/apps/desktop/src/app/hud/handoff.test.tsxnew file mode 100644index 00000000000..4a1665a402a--- /dev/null+++ b/apps/desktop/src/app/hud/handoff.test.tsx@@ -0,0 +1,61 @@+// @vitest-environment jsdom+import { renderHook } from '@testing-library/react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++const requestComposerFocus = vi.fn()++vi.mock('../chat/composer/focus', () => ({+ getActiveComposer: () => 'main',+ requestComposerFocus: (...args: unknown[]) => requestComposerFocus(...args)+}))++vi.mock('../open-session', () => ({ openSession: vi.fn() }))+vi.mock('@/store/composer', () => ({ reloadPersistedDrafts: vi.fn(), requestComposerDraftSync: vi.fn() }))+vi.mock('@/store/session-states', () => ({ focusOpenSession: () => 'main', sessionTileDelegate: () => null }))++import { useHudHandoff } from './handoff'++type HudChanged = (state: { open: boolean; sessionId: null | string }) => void++const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }+const initialHermesDesktop = desktopWindow.hermesDesktop+let emitHudChanged: HudChanged | null = null++beforeEach(() => {+ requestComposerFocus.mockClear()+ emitHudChanged = null+ desktopWindow.hermesDesktop = {+ hud: {+ onChanged: (listener: HudChanged) => {+ emitHudChanged = listener++ return () => undefined+ }+ }+ } as unknown as Window['hermesDesktop']+})++afterEach(() => {+ if (initialHermesDesktop) {+ desktopWindow.hermesDesktop = initialHermesDesktop+ } else {+ delete desktopWindow.hermesDesktop+ }+})++// Leaving HUD mode hands the app window the session AND the keyboard: the+// user was typing in the HUD a moment ago, and a re-shown app window whose+// composer has no caret swallows the first keystrokes.+it('puts the caret back in the app composer when the HUD closes', () => {+ const resumeSession = vi.fn()++ renderHook(() => useHudHandoff({ navigate: vi.fn(), resumeSession }))++ expect(emitHudChanged).not.toBeNull()++ emitHudChanged?.({ open: true, sessionId: 's1' })+ expect(requestComposerFocus).not.toHaveBeenCalled()++ emitHudChanged?.({ open: false, sessionId: 's1' })+ expect(requestComposerFocus).toHaveBeenCalledOnce()+})diff --git a/apps/desktop/src/app/hud/handoff.ts b/apps/desktop/src/app/hud/handoff.tsindex dfd41a57f9a..e79f86ef553 100644--- a/apps/desktop/src/app/hud/handoff.ts+++ b/apps/desktop/src/app/hud/handoff.ts@@ -23,7 +23,7 @@ import { $selectedStoredSessionId } from '@/store/session'import { focusOpenSession, sessionTileDelegate } from '@/store/session-states'import { isHudWindow } from '@/store/windows'-import { getActiveComposer } from '../chat/composer/focus'+import { getActiveComposer, requestComposerFocus } from '../chat/composer/focus'import { openSession, type OpenSessionNavigate } from '../open-session'import { sessionRoute } from '../routes'@@ -70,6 +70,11 @@ export function useHudHandoff({ navigate, resumeSession }: HudHandoffParams): vo// The HUD may have typed or sent since this window last read the stash.reloadPersistedDrafts()+ // The user was typing in the HUD; they are now looking at the app. Put+ // the caret where they left it. Main re-keys the OS window, but a key+ // window with no focused element still eats the first keystrokes.+ requestComposerFocus()+const selected = $selectedStoredSessionId.get()const target = hudSessionId ?? selecteddiff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex bd4cfa52f21..f160ba6a59e 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -152,7 +152,7 @@ Talk to Hermes and hear it back, the same [voice mode](./features/voice-mode.md)- **Resizing** — drag any edge or corner of the bar; the opposite edge stays anchored. Native Wayland exposes the right and bottom edges because the compositor does not allow apps to position top-level windows themselves.- **Reset layout** — the discard control on the bar restores the default size and (on X11 / macOS / Windows) position. Use this if a persisted size leaves the HUD unusable.- **Snap to pointer** — **⌘/Ctrl+Shift+G** (a global hotkey, works from any app) jumps the HUD to wherever your cursor is. On native Wayland this is a no-op — the compositor owns placement.-- **Exiting** — click the exit button on the bar, or press **⌘/Ctrl+Shift+H** again. The app window comes back with your session intact.+- **Exiting** — click the exit button on the bar, press **⌘/Ctrl+Shift+H** again, or press **⌘/Ctrl+W** while the HUD has focus. The app window comes back in front with your session and the caret in its composer.#### Linux / Wayland