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/observability.test.ts b/apps/desktop/src/main/observability.test.ts index 82fbfce631b..adf6771443d 100644 --- a/apps/desktop/src/main/observability.test.ts +++ b/apps/desktop/src/main/observability.test.ts @@ -94,4 +94,70 @@ 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)() + } + + 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' }) + expect(dialog.showMessageBox).not.toHaveBeenCalled() + expect(app.relaunch).not.toHaveBeenCalled() + expect(app.exit).toHaveBeenCalledWith(1) + }) + + 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) => { + 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('before-quit') + await settlePrompt() + + 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..3a60b566f48 100644 --- a/apps/desktop/src/main/observability.ts +++ b/apps/desktop/src/main/observability.ts @@ -79,6 +79,12 @@ 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 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, @@ -86,6 +92,8 @@ export function installMainProcessFailureObservers({ processSource = process, }: MainProcessFailureObserverDeps): void { let fatalRecoveryOpen = false + let quitCommitted = false + let openPrompt: AbortController | null = null let lastChildFailure = '' let lastChildFailureAt = 0 @@ -117,6 +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 (quitCommitted) { + app.exit(1) + return + } + const promptAbort = new AbortController() + openPrompt = promptAbort const options = { type: 'error' as const, buttons: ['Restart Sim', 'Quit Sim'], @@ -124,6 +138,7 @@ export function installMainProcessFailureObservers({ cancelId: 1, message: 'Sim encountered a problem', detail: 'Restart Sim to recover. Diagnostic details were saved locally.', + signal: promptAbort.signal, } const win = getWindow() const prompt = @@ -145,7 +160,17 @@ export function installMainProcessFailureObservers({ reportFatal('main_uncaught_exception', error) } + const answerOpenPromptAsQuit = (): void => { + openPrompt?.abort() + } + const onWillQuit = (): void => { + quitCommitted = true + answerOpenPromptAsQuit() + } + app.on('child-process-gone', onChildProcessGone) + app.on('before-quit', answerOpenPromptAsQuit) + app.on('will-quit', onWillQuit) processSource.on('unhandledRejection', onUnhandledRejection) processSource.on('uncaughtException', onUncaughtException) } 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