From 30c1912f2648975a2b18ac93ccd782c779c09190 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 17:36:45 -0800 Subject: [PATCH 1/3] fix(desktop): a fatal main-process error can no longer hang a quit --- apps/desktop/src/main/observability.test.ts | 43 +++++++++++++++++++++ apps/desktop/src/main/observability.ts | 19 +++++++++ 2 files changed, 62 insertions(+) diff --git a/apps/desktop/src/main/observability.test.ts b/apps/desktop/src/main/observability.test.ts index 82fbfce631b..57c8be42aba 100644 --- a/apps/desktop/src/main/observability.test.ts +++ b/apps/desktop/src/main/observability.test.ts @@ -94,4 +94,47 @@ describe('installMainProcessFailureObservers', () => { await vi.waitFor(() => expect(app.relaunch).toHaveBeenCalledOnce()) expect(app.exit).toHaveBeenCalledWith(1) }) + + function emitAppEvent(event: string) { + const handler = vi.mocked(app.on).mock.calls.find(([name]) => name === event)?.[1] + if (!handler) throw new Error(`No ${event} listener`) + ;(handler as () => void)() + } + + it('exits without prompting when the failure arrives after quitting has begun', () => { + const events = { filePath: '/tmp/events.log', record: vi.fn() } + const { handlers, source } = createProcessSource() + installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source }) + + emitAppEvent('before-quit') + handlers.get('uncaughtException')?.(new Error('during shutdown') as never) + + expect(events.record).toHaveBeenCalledWith('main_uncaught_exception', { valueType: 'Error' }) + expect(dialog.showMessageBox).not.toHaveBeenCalled() + expect(app.relaunch).not.toHaveBeenCalled() + expect(app.exit).toHaveBeenCalledWith(1) + }) + + it('answers an open recovery prompt as Quit when the app starts quitting', async () => { + vi.mocked(dialog.showMessageBox).mockImplementationOnce( + (options: { cancelId?: number; signal?: AbortSignal }) => + new Promise((resolve) => { + options.signal?.addEventListener('abort', () => + resolve({ response: options.cancelId ?? 0, checkboxChecked: false }) + ) + }) + ) + const events = { filePath: '/tmp/events.log', record: vi.fn() } + const { handlers, source } = createProcessSource() + installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source }) + + handlers.get('uncaughtException')?.(new Error('while running') as never) + expect(dialog.showMessageBox).toHaveBeenCalledOnce() + expect(app.exit).not.toHaveBeenCalled() + + emitAppEvent('will-quit') + + await vi.waitFor(() => expect(app.exit).toHaveBeenCalledWith(1)) + expect(app.relaunch).not.toHaveBeenCalled() + }) }) diff --git a/apps/desktop/src/main/observability.ts b/apps/desktop/src/main/observability.ts index 132eb026bdf..8d5ec1c086c 100644 --- a/apps/desktop/src/main/observability.ts +++ b/apps/desktop/src/main/observability.ts @@ -79,6 +79,11 @@ const FAILURE_DEDUPE_MS = 5_000 * single native recovery surface. Error text is deliberately excluded from * the structured log because rejected values can contain request payloads or * credentials; the event kind and crash dumps are enough for triage. + * + * The recovery prompt never outlives a quit: a failure once quitting has begun + * exits without asking (a dialog opened during shutdown can only fall back to + * a blocking native alert), and a quit while the prompt is open answers it as + * Quit. */ export function installMainProcessFailureObservers({ events, @@ -86,6 +91,8 @@ export function installMainProcessFailureObservers({ processSource = process, }: MainProcessFailureObserverDeps): void { let fatalRecoveryOpen = false + let quitStarted = false + const quitSignal = new AbortController() let lastChildFailure = '' let lastChildFailureAt = 0 @@ -117,6 +124,10 @@ export function installMainProcessFailureObservers({ fatalRecoveryOpen = true events.record(name, { valueType: value instanceof Error ? 'Error' : typeof value }) logger.error('Fatal main-process failure', { kind: name }) + if (quitStarted) { + app.exit(1) + return + } const options = { type: 'error' as const, buttons: ['Restart Sim', 'Quit Sim'], @@ -124,6 +135,7 @@ export function installMainProcessFailureObservers({ cancelId: 1, message: 'Sim encountered a problem', detail: 'Restart Sim to recover. Diagnostic details were saved locally.', + signal: quitSignal.signal, } const win = getWindow() const prompt = @@ -145,7 +157,14 @@ export function installMainProcessFailureObservers({ reportFatal('main_uncaught_exception', error) } + const onQuitStarted = (): void => { + quitStarted = true + quitSignal.abort() + } + app.on('child-process-gone', onChildProcessGone) + app.on('before-quit', onQuitStarted) + app.on('will-quit', onQuitStarted) processSource.on('unhandledRejection', onUnhandledRejection) processSource.on('uncaughtException', onUncaughtException) } From be9729faa407b3b8c6596939e61bc7e53c816690 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 18:31:03 -0800 Subject: [PATCH 2/3] fix(desktop): a window's late show after it closed no longer throws during quit --- apps/desktop/src/main/index.ts | 7 ++++- apps/desktop/src/main/window.test.ts | 41 +++++++++++++++++++++++++++- apps/desktop/src/main/window.ts | 15 ++++++++++ 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index cd074cbe5ee..2812b3ad3b2 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -118,7 +118,11 @@ import { createRunLedger } from '@/main/terminal/run-ledger' import { installTray, type TrayHandle } from '@/main/tray' import { checkForUpdatesInteractive, initUpdater, type UpdaterHandle } from '@/main/updater' import { installBrowserUserAgent } from '@/main/user-agent' -import { createMainWindow, setupPermissionHandlers } from '@/main/window' +import { + createMainWindow, + detachVisibilityListenersOnClose, + setupPermissionHandlers, +} from '@/main/window' import { attachWindowOpenPolicy, isPopupContents, type WindowPolicyDeps } from '@/main/windows' const logger = createLogger('DesktopMain') @@ -318,6 +322,7 @@ function main(): void { return getWindows().at(-1) ?? null } installMainProcessFailureObservers({ events, getWindow: getMainWindow }) + app.on('browser-window-created', (_event, win) => detachVisibilityListenersOnClose(win)) const windowForContents = (contents: WebContents) => { const win = BrowserWindow.fromWebContents(contents) return win && windows.has(win) && !win.isDestroyed() ? win : null diff --git a/apps/desktop/src/main/window.test.ts b/apps/desktop/src/main/window.test.ts index f8c2ca1bd02..fe4d9c88d06 100644 --- a/apps/desktop/src/main/window.test.ts +++ b/apps/desktop/src/main/window.test.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createSecureWebPreferences } from '@/main/window-preferences' @@ -7,7 +8,12 @@ import { BrowserWindow, dialog, screen, systemPreferences, WebContentsView } fro import { registerAgentWebContents } from '@/main/browser-agent/registry' import type { ConfigStore } from '@/main/config' import type { EventRecorder } from '@/main/observability' -import { createMainWindow, resolvePermission, setupPermissionHandlers } from '@/main/window' +import { + createMainWindow, + detachVisibilityListenersOnClose, + resolvePermission, + setupPermissionHandlers, +} from '@/main/window' const APP = 'https://sim.ai' @@ -195,3 +201,36 @@ describe('createMainWindow', () => { expect(event.preventDefault).toHaveBeenCalledOnce() }) }) + +describe('detachVisibilityListenersOnClose', () => { + /** A window wired the way Electron wires every BrowserWindow: its visibility listener reads the native window. */ + function electronLikeWindow() { + let destroyed = false + const win = Object.assign(new EventEmitter(), { + isVisible: () => { + if (destroyed) throw new TypeError('Object has been destroyed') + return true + }, + destroy: () => { + destroyed = true + win.emit('closed') + }, + }) + const visibilityChanged = () => win.isVisible() + for (const event of ['show', 'hide', 'minimize', 'maximize', 'restore']) { + win.on(event, visibilityChanged) + } + return win + } + + it('a visibility event delivered after the window closed no longer throws', () => { + const win = electronLikeWindow() + detachVisibilityListenersOnClose(win as never) + + win.emit('show') + win.destroy() + + expect(() => win.emit('show')).not.toThrow() + expect(() => win.emit('hide')).not.toThrow() + }) +}) diff --git a/apps/desktop/src/main/window.ts b/apps/desktop/src/main/window.ts index 095385970f8..6f0de4f05a7 100644 --- a/apps/desktop/src/main/window.ts +++ b/apps/desktop/src/main/window.ts @@ -19,6 +19,21 @@ const MIN_HEIGHT = 600 const WINDOW_TITLE = 'Sim' const BOUNDS_SAVE_DELAY_MS = 400 const ROUTE_SAVE_DELAY_MS = 500 +/** The events Electron's own per-window `visibilityChanged` listener subscribes to. */ +const VISIBILITY_EVENTS = ['show', 'hide', 'minimize', 'maximize', 'restore'] as const + +/** + * Drops a closed window's visibility listeners. macOS can deliver a window's + * `show` (an occlusion change) after the window has closed and been destroyed, + * as when the app quits just as its first window appears; Electron's own + * listener then reads `isVisible()` from the dead window and throws "Object has + * been destroyed" as an uncaught main-process exception during shutdown. + */ +export function detachVisibilityListenersOnClose(win: BrowserWindow): void { + win.once('closed', () => { + for (const event of VISIBILITY_EVENTS) win.removeAllListeners(event) + }) +} /** * The permission matrix: sanitized clipboard writes and microphone access for From fa41a2d6e659f9313d4da8f6934a5711493181e8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 18:32:35 -0800 Subject: [PATCH 3/3] fix(desktop): only a committed quit skips the recovery prompt --- apps/desktop/src/main/observability.test.ts | 31 +++++++++++++++++--- apps/desktop/src/main/observability.ts | 32 ++++++++++++--------- 2 files changed, 46 insertions(+), 17 deletions(-) diff --git a/apps/desktop/src/main/observability.test.ts b/apps/desktop/src/main/observability.test.ts index 57c8be42aba..adf6771443d 100644 --- a/apps/desktop/src/main/observability.test.ts +++ b/apps/desktop/src/main/observability.test.ts @@ -101,12 +101,17 @@ describe('installMainProcessFailureObservers', () => { ;(handler as () => void)() } - it('exits without prompting when the failure arrives after quitting has begun', () => { + async function settlePrompt() { + for (let turn = 0; turn < 5; turn++) await Promise.resolve() + } + + it('exits without prompting when the failure arrives once the quit is committed', () => { const events = { filePath: '/tmp/events.log', record: vi.fn() } const { handlers, source } = createProcessSource() installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source }) emitAppEvent('before-quit') + emitAppEvent('will-quit') handlers.get('uncaughtException')?.(new Error('during shutdown') as never) expect(events.record).toHaveBeenCalledWith('main_uncaught_exception', { valueType: 'Error' }) @@ -115,7 +120,24 @@ describe('installMainProcessFailureObservers', () => { expect(app.exit).toHaveBeenCalledWith(1) }) - it('answers an open recovery prompt as Quit when the app starts quitting', async () => { + it('still offers recovery after a quit request another listener cancelled', () => { + vi.mocked(dialog.showMessageBox).mockImplementationOnce(() => new Promise(() => {})) + const events = { filePath: '/tmp/events.log', record: vi.fn() } + const { handlers, source } = createProcessSource() + installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source }) + + emitAppEvent('before-quit') + handlers.get('uncaughtException')?.(new Error('after a cancelled quit') as never) + + expect(dialog.showMessageBox).toHaveBeenCalledOnce() + const [options] = vi.mocked(dialog.showMessageBox).mock.calls[0] as unknown as [ + { signal?: AbortSignal }, + ] + expect(options.signal?.aborted).toBe(false) + expect(app.exit).not.toHaveBeenCalled() + }) + + it('answers an open recovery prompt as Quit when a quit is requested', async () => { vi.mocked(dialog.showMessageBox).mockImplementationOnce( (options: { cancelId?: number; signal?: AbortSignal }) => new Promise((resolve) => { @@ -132,9 +154,10 @@ describe('installMainProcessFailureObservers', () => { expect(dialog.showMessageBox).toHaveBeenCalledOnce() expect(app.exit).not.toHaveBeenCalled() - emitAppEvent('will-quit') + emitAppEvent('before-quit') + await settlePrompt() - await vi.waitFor(() => expect(app.exit).toHaveBeenCalledWith(1)) + expect(app.exit).toHaveBeenCalledWith(1) expect(app.relaunch).not.toHaveBeenCalled() }) }) diff --git a/apps/desktop/src/main/observability.ts b/apps/desktop/src/main/observability.ts index 8d5ec1c086c..3a60b566f48 100644 --- a/apps/desktop/src/main/observability.ts +++ b/apps/desktop/src/main/observability.ts @@ -80,10 +80,11 @@ const FAILURE_DEDUPE_MS = 5_000 * the structured log because rejected values can contain request payloads or * credentials; the event kind and crash dumps are enough for triage. * - * The recovery prompt never outlives a quit: a failure once quitting has begun - * exits without asking (a dialog opened during shutdown can only fall back to - * a blocking native alert), and a quit while the prompt is open answers it as - * Quit. + * The recovery prompt never outlives a quit: a failure once a quit is committed + * (`will-quit`) exits without asking, since a dialog opened during shutdown can + * only fall back to a blocking native alert, and any quit request while the + * prompt is open answers it as Quit. A `before-quit` that another listener + * cancels leaves later failures their prompt. */ export function installMainProcessFailureObservers({ events, @@ -91,8 +92,8 @@ export function installMainProcessFailureObservers({ processSource = process, }: MainProcessFailureObserverDeps): void { let fatalRecoveryOpen = false - let quitStarted = false - const quitSignal = new AbortController() + let quitCommitted = false + let openPrompt: AbortController | null = null let lastChildFailure = '' let lastChildFailureAt = 0 @@ -124,10 +125,12 @@ export function installMainProcessFailureObservers({ fatalRecoveryOpen = true events.record(name, { valueType: value instanceof Error ? 'Error' : typeof value }) logger.error('Fatal main-process failure', { kind: name }) - if (quitStarted) { + if (quitCommitted) { app.exit(1) return } + const promptAbort = new AbortController() + openPrompt = promptAbort const options = { type: 'error' as const, buttons: ['Restart Sim', 'Quit Sim'], @@ -135,7 +138,7 @@ export function installMainProcessFailureObservers({ cancelId: 1, message: 'Sim encountered a problem', detail: 'Restart Sim to recover. Diagnostic details were saved locally.', - signal: quitSignal.signal, + signal: promptAbort.signal, } const win = getWindow() const prompt = @@ -157,14 +160,17 @@ export function installMainProcessFailureObservers({ reportFatal('main_uncaught_exception', error) } - const onQuitStarted = (): void => { - quitStarted = true - quitSignal.abort() + const answerOpenPromptAsQuit = (): void => { + openPrompt?.abort() + } + const onWillQuit = (): void => { + quitCommitted = true + answerOpenPromptAsQuit() } app.on('child-process-gone', onChildProcessGone) - app.on('before-quit', onQuitStarted) - app.on('will-quit', onQuitStarted) + app.on('before-quit', answerOpenPromptAsQuit) + app.on('will-quit', onWillQuit) processSource.on('unhandledRejection', onUnhandledRejection) processSource.on('uncaughtException', onUncaughtException) }