Skip to content

The agent that grows with you

fix(desktop): exit on window close and restore window on second instance (#130810)

JerryLiu36938413a36a8fc
diff --git a/apps/desktop/electron/main-window-lifecycle.test.ts b/apps/desktop/electron/main-window-lifecycle.test.ts
index 4ca6f8cd3d8..42cf69baa75 100644
--- a/apps/desktop/electron/main-window-lifecycle.test.ts
+++ b/apps/desktop/electron/main-window-lifecycle.test.ts
@@ -2,7 +2,12 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
-import { ensureMainWindow } from './main-window-lifecycle'
+import {
+ activateWindow,
+ decideSecondInstanceAction,
+ ensureMainWindow,
+ shouldQuitOnAllClosed
+} from './main-window-lifecycle'
test('recreates a destroyed primary window without focusing it', () => {
const destroyedWindow = {
@@ -70,3 +75,80 @@ test('leaves live-window focus to deep-link delivery', () => {
focusExisting: false
})
})
+
+// Regression for #130810: closing the last window must quit on
+// Windows/Linux (never strand a windowless single-instance lock holder),
+// while macOS stays in the Dock unless handing off to a detached script.
+test('window-all-closed quits off macOS and only on handoff for darwin', () => {
+ assert.equal(shouldQuitOnAllClosed('win32', false), true)
+ assert.equal(shouldQuitOnAllClosed('linux', false), true)
+ assert.equal(shouldQuitOnAllClosed('darwin', false), false)
+ assert.equal(shouldQuitOnAllClosed('darwin', true), true)
+})
+
+// Regression for #130810: a second launch re-creates a destroyed primary,
+// defers pre-ready (whenReady boot owns the first window), and activates a
+// live one instead of silently exiting.
+test('second-instance routes destroyed/missing/live primaries', () => {
+ assert.equal(decideSecondInstanceAction({ isDestroyed: () => true }, true), 'create')
+ assert.equal(decideSecondInstanceAction(null, true), 'create')
+ assert.equal(decideSecondInstanceAction(undefined, true), 'create')
+ assert.equal(decideSecondInstanceAction({ isDestroyed: () => true }, false), 'defer')
+ assert.equal(decideSecondInstanceAction(null, false), 'defer')
+ assert.equal(decideSecondInstanceAction({ isDestroyed: () => false }, true), 'activate')
+ assert.equal(decideSecondInstanceAction({ isDestroyed: () => false }, false), 'activate')
+})
+
+// Regression for #130810: an explicit relaunch restores + shows + focuses
+// (activation), so a minimized or tray-hidden window comes back instead of
+// flashing the taskbar. This must use show(), not showInactive().
+test('explicit relaunch activates a minimized tray-hidden window', () => {
+ const calls: string[] = []
+ let minimized = true
+ let visible = false
+ let focused = false
+
+ activateWindow({
+ isDestroyed: () => false,
+ isMinimized: () => minimized,
+ isVisible: () => visible,
+ isFocused: () => focused,
+ restore: () => {
+ calls.push('restore')
+ minimized = false
+ visible = false
+ },
+ show: () => {
+ calls.push('show')
+ visible = true
+ },
+ focus: () => {
+ calls.push('focus')
+ focused = true
+ }
+ })
+
+ assert.deepEqual(calls, ['restore', 'show', 'focus'])
+})
+
+test('explicit relaunch leaves an already-visible focused window alone', () => {
+ const calls: string[] = []
+
+ activateWindow({
+ isDestroyed: () => false,
+ isMinimized: () => false,
+ isVisible: () => true,
+ isFocused: () => true,
+ restore: () => calls.push('restore'),
+ show: () => calls.push('show'),
+ focus: () => calls.push('focus')
+ })
+
+ assert.deepEqual(calls, [])
+})
+
+test('explicit relaunch never touches a destroyed or missing window', () => {
+ activateWindow({ isDestroyed: () => true })
+ activateWindow(null)
+ activateWindow(undefined)
+})
diff --git a/apps/desktop/electron/main-window-lifecycle.ts b/apps/desktop/electron/main-window-lifecycle.ts
index d3edc3b05e2..e1e76e52a1d 100644
--- a/apps/desktop/electron/main-window-lifecycle.ts
+++ b/apps/desktop/electron/main-window-lifecycle.ts
@@ -2,6 +2,15 @@ type MainWindowLike = {
isDestroyed: () => boolean
}
+type ActivatableWindow = MainWindowLike & {
+ isMinimized?: () => boolean
+ isVisible?: () => boolean
+ isFocused?: () => boolean
+ restore?: () => void
+ show?: () => void
+ focus?: () => void
+}
+
type EnsureMainWindowOptions<T extends MainWindowLike> = {
isReady: boolean
createWindow: () => unknown
@@ -26,3 +35,91 @@ export function ensureMainWindow<T extends MainWindowLike>(
focusWindow(window)
}
}
+
+/**
+ * Whether `window-all-closed` must quit the app (#130810).
+ *
+ * Non-macOS platforms never keep a windowless app alive: closing the last
+ * window IS quitting. macOS keeps the Dock process alive by convention,
+ * except while handing off to a detached updater/swap/uninstall script —
+ * there the process must die so the script's PID-wait can proceed.
+ */
+export function shouldQuitOnAllClosed(platform: NodeJS.Platform | string, isQuittingForHandoff: boolean): boolean {
+ return platform !== 'darwin' || isQuittingForHandoff === true
+}
+
+/**
+ * Explicit-activation restore for a user-invoked relaunch (#130810).
+ *
+ * Unlike the ambient `focusWindow` in main.ts (showInactive, never steal
+ * foreground per #83998), a second-instance / dock-activate / tray-click is
+ * the user asking for Hermes back, so the window must come back activatable:
+ * restore a minimized window, show a tray-hidden one with `show()` (not
+ * `showInactive()` — the latter leaves a Windows hidden-minimized window
+ * painted-but-dead, #119252), then take keyboard focus when unfocused.
+ * Showing emits `show`, which lets minimize-to-tray release the window from
+ * its hidden set and clear `skipTaskbar` on Windows.
+ */
+export function activateWindow(window: ActivatableWindow | null | undefined): void {
+ if (!window || window.isDestroyed()) {
+ return
+ }
+
+ try {
+ if (typeof window.isMinimized === 'function' && window.isMinimized()) {
+ window.restore?.()
+ }
+ } catch {
+ // A window dying mid-restore must not break the relaunch path.
+ }
+
+ // Re-read visibility after the restore: a tray-hidden window reports
+ // invisible until it is shown.
+ let visible = true
+
+ try {
+ visible = typeof window.isVisible === 'function' ? window.isVisible() : true
+ } catch {
+ visible = false
+ }
+
+ if (!visible) {
+ try {
+ window.show?.()
+ } catch {
+ // Fall through to the focus attempt below.
+ }
+ }
+
+ try {
+ if (typeof window.isFocused === 'function') {
+ if (!window.isFocused()) {
+ window.focus?.()
+ }
+ } else {
+ window.focus?.()
+ }
+ } catch {
+ // Best effort: the window is at least visible again.
+ }
+}
+
+export type SecondInstanceDecision = 'create' | 'activate' | 'defer'
+
+/**
+ * Pure second-instance routing (#130810): a destroyed/missing primary is
+ * re-created once the app is ready (a pre-ready relaunch defers to the
+ * pending `whenReady` boot, which creates the first window anyway); a live
+ * primary is activated (restore + show + focus). Callers log the decision so
+ * a silent second exit stays diagnosable in desktop.log.
+ */
+export function decideSecondInstanceAction(
+ window: MainWindowLike | null | undefined,
+ isReady: boolean
+): SecondInstanceDecision {
+ if (!window || window.isDestroyed()) {
+ return isReady ? 'create' : 'defer'
+ }
+
+ return 'activate'
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 1a36826418e..7740aa935f3 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -360,7 +360,12 @@ import { localSkinProfileKey, readLocalSkinPayload } from './local-skin'
import { ACTIVE_LOG_POLL_MS, planLogRotation, reclaimActiveLogIfOversized } from './log-rotation'
import { registerMachineProfile } from './machine-profile'
import { createMainProcessLagWatchdog } from './main-process-lag-watchdog'
-import { ensureMainWindow } from './main-window-lifecycle'
+import {
+ activateWindow as activateRestoredWindow,
+ decideSecondInstanceAction,
+ ensureMainWindow,
+ shouldQuitOnAllClosed
+} from './main-window-lifecycle'
import {
assertManagedUpdatePreflightClear,
executeManagedRemoteUpdate,
@@ -13781,7 +13786,10 @@ 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 }),
+ // A tray click is an explicit relaunch gesture (#130810): restore with
+ // activation (show + focus), not the ambient showInactive path.
+ restoreMainWindow: () =>
+ ensureMainWindow(mainWindow, { isReady: app.isReady(), createWindow, focusWindow: activateRestoredWindow }),
isQuittingForHandoff: () => isQuittingForHandoff,
log: rememberLog
})
@@ -19229,6 +19237,12 @@ function handleDeepLink(url) {
mainWindow.restore()
}
+ // #130810: a tray-hidden primary reports invisible but not minimized;
+ // without an explicit show the focus below lands on a hidden window.
+ if (!mainWindow.isVisible()) {
+ mainWindow.show()
+ }
+
mainWindow.focus()
if (mainWindow.isFullScreen()) {
@@ -19252,6 +19266,15 @@ function handleDeepLink(url) {
mainWindow.restore()
}
+ // #130810: same tray-hidden case as above — a second-instance deep link
+ // must un-hide the window before delivering, otherwise the payload goes
+ // to an invisible renderer and the relaunch looks like a silent exit.
+ // Showing emits `show`, so minimize-to-tray releases the window from its
+ // hidden set (and clears skipTaskbar on Windows).
+ if (!mainWindow.isVisible()) {
+ mainWindow.show()
+ }
+
// #83998: a deep link must deliver without re-pumping the Windows
// foreground when the window already has focus.
if (shouldFocusToTakeKeyboard(mainWindow)) {
@@ -19355,13 +19378,40 @@ if (!isPrimaryInstance) {
handleDeepLink(url)
}
- ensureMainWindow(mainWindow, {
- isReady: app.isReady(),
- createWindow,
- focusWindow,
- // deep-link delivery focuses a live window after its renderer is ready.
- focusExisting: !url
- })
+ // #130810: a second Start-menu / shortcut / Hermes.exe launch must never
+ // silently exit. Restore a live (minimized or tray-hidden) primary with
+ // activation, or re-create it when it was destroyed — and log the
+ // decision so a future silent exit stays diagnosable in desktop.log.
+ const decision = decideSecondInstanceAction(mainWindow, app.isReady())
+ const destroyed = !mainWindow || mainWindow.isDestroyed()
+
+ rememberLog(
+ `[second-instance] relaunch (deepLink=${url ? 'yes' : 'no'} decision=${decision} ` +
+ `mainWindow=${destroyed ? 'destroyed' : 'live'} ` +
+ `minimized=${!destroyed && typeof mainWindow.isMinimized === 'function' ? mainWindow.isMinimized() : 'n/a'} ` +
+ `visible=${!destroyed && typeof mainWindow.isVisible === 'function' ? mainWindow.isVisible() : 'n/a'})`
+ )
+
+ if (decision === 'create') {
+ createWindow()
+
+ return
+ }
+
+ if (decision === 'defer') {
+ // Pre-ready: the pending whenReady boot creates the first window.
+ return
+ }
+
+ // A live primary: deep-link delivery already restored/shown/focused it
+ // above; a plain relaunch must activate it (restore + show + focus) so a
+ // tray-hidden or minimized window comes back instead of flashing the
+ // taskbar. Unlike the ambient focusWindow (showInactive per #83998), an
+ // explicit relaunch owns the foreground. Re-asserting activation after a
+ // deep link is idempotent (a visible + focused window is a no-op) and
+ // covers the queued-delivery case, where handleDeepLink stored the payload
+ // without showing the window yet.
+ activateRestoredWindow(mainWindow)
})
}
@@ -19511,10 +19561,12 @@ app.whenReady().then(() => {
// Recreate the primary window if it's gone. Guard on mainWindow directly
// (not just total window count) so a dock click still restores the main
// window when only secondary session windows remain open.
+ // #130810: a dock/taskbar activate is explicit, so restore with
+ // activation (restore + show + focus), not the ambient showInactive path.
if (!mainWindow || mainWindow.isDestroyed()) {
createWindow()
} else {
- focusWindow(mainWindow)
+ activateRestoredWindow(mainWindow)
}
})
})
@@ -19663,7 +19715,21 @@ function registerChatWindow(window: BrowserWindow) {
heldQuitForActiveWork(event)
})
- window.once('closed', () => chatWindows.delete(window))
+ window.once('closed', () => {
+ chatWindows.delete(window)
+
+ // #130810: hidden helpers (Quick Entry, HUD, pet overlay) are still
+ // BrowserWindows, so `window-all-closed` never fires while one lingers
+ // and a windowless app keeps holding the single-instance lock — every
+ // later launch then exits silently. A tray-absorbed close never reaches
+ // here (preventDefault), and a multi-window close still has peers left,
+ // so quitting only when no chat surface remains is safe: it forces the
+ // ordinary before-quit teardown (backends, SSH, PTYs, watchers) even when
+ // window-all-closed is blocked.
+ if (!IS_MAC && !isQuittingForHandoff && chatWindows.size === 0 && !appQuitting) {
+ app.quit()
+ }
+ })
}
app.on('before-quit', event => {
@@ -19810,7 +19876,9 @@ app.on('window-all-closed', () => {
// the bundle and relaunch — without this the script's PID-wait spins to its
// full timeout and the user is left with an invisible app (or an uninstall
// that appears to do nothing).
- if (process.platform !== 'darwin' || isQuittingForHandoff) {
+ // #130810: on Windows/Linux closing the last window IS quitting — the app
+ // must not linger windowless holding the single-instance lock.
+ if (shouldQuitOnAllClosed(process.platform, isQuittingForHandoff)) {
app.quit()
}
})