Skip to content

Commit e4452fb

Browse files
authored
fix(desktop): a quit can no longer hang on a fatal main-process error (#10396)
* fix(desktop): a fatal main-process error can no longer hang a quit * fix(desktop): a window's late show after it closed no longer throws during quit * fix(desktop): only a committed quit skips the recovery prompt
1 parent cfb0809 commit e4452fb

5 files changed

Lines changed: 152 additions & 2 deletions

File tree

‎apps/desktop/src/main/index.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,11 @@ import { createRunLedger } from '@/main/terminal/run-ledger'
118118
import { installTray, type TrayHandle } from '@/main/tray'
119119
import { checkForUpdatesInteractive, initUpdater, type UpdaterHandle } from '@/main/updater'
120120
import { installBrowserUserAgent } from '@/main/user-agent'
121-
import { createMainWindow, setupPermissionHandlers } from '@/main/window'
121+
import {
122+
createMainWindow,
123+
detachVisibilityListenersOnClose,
124+
setupPermissionHandlers,
125+
} from '@/main/window'
122126
import { attachWindowOpenPolicy, isPopupContents, type WindowPolicyDeps } from '@/main/windows'
123127

124128
const logger = createLogger('DesktopMain')
@@ -318,6 +322,7 @@ function main(): void {
318322
return getWindows().at(-1) ?? null
319323
}
320324
installMainProcessFailureObservers({ events, getWindow: getMainWindow })
325+
app.on('browser-window-created', (_event, win) => detachVisibilityListenersOnClose(win))
321326
const windowForContents = (contents: WebContents) => {
322327
const win = BrowserWindow.fromWebContents(contents)
323328
return win && windows.has(win) && !win.isDestroyed() ? win : null

‎apps/desktop/src/main/observability.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,70 @@ describe('installMainProcessFailureObservers', () => {
9494
await vi.waitFor(() => expect(app.relaunch).toHaveBeenCalledOnce())
9595
expect(app.exit).toHaveBeenCalledWith(1)
9696
})
97+
98+
function emitAppEvent(event: string) {
99+
const handler = vi.mocked(app.on).mock.calls.find(([name]) => name === event)?.[1]
100+
if (!handler) throw new Error(`No ${event} listener`)
101+
;(handler as () => void)()
102+
}
103+
104+
async function settlePrompt() {
105+
for (let turn = 0; turn < 5; turn++) await Promise.resolve()
106+
}
107+
108+
it('exits without prompting when the failure arrives once the quit is committed', () => {
109+
const events = { filePath: '/tmp/events.log', record: vi.fn() }
110+
const { handlers, source } = createProcessSource()
111+
installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source })
112+
113+
emitAppEvent('before-quit')
114+
emitAppEvent('will-quit')
115+
handlers.get('uncaughtException')?.(new Error('during shutdown') as never)
116+
117+
expect(events.record).toHaveBeenCalledWith('main_uncaught_exception', { valueType: 'Error' })
118+
expect(dialog.showMessageBox).not.toHaveBeenCalled()
119+
expect(app.relaunch).not.toHaveBeenCalled()
120+
expect(app.exit).toHaveBeenCalledWith(1)
121+
})
122+
123+
it('still offers recovery after a quit request another listener cancelled', () => {
124+
vi.mocked(dialog.showMessageBox).mockImplementationOnce(() => new Promise(() => {}))
125+
const events = { filePath: '/tmp/events.log', record: vi.fn() }
126+
const { handlers, source } = createProcessSource()
127+
installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source })
128+
129+
emitAppEvent('before-quit')
130+
handlers.get('uncaughtException')?.(new Error('after a cancelled quit') as never)
131+
132+
expect(dialog.showMessageBox).toHaveBeenCalledOnce()
133+
const [options] = vi.mocked(dialog.showMessageBox).mock.calls[0] as unknown as [
134+
{ signal?: AbortSignal },
135+
]
136+
expect(options.signal?.aborted).toBe(false)
137+
expect(app.exit).not.toHaveBeenCalled()
138+
})
139+
140+
it('answers an open recovery prompt as Quit when a quit is requested', async () => {
141+
vi.mocked(dialog.showMessageBox).mockImplementationOnce(
142+
(options: { cancelId?: number; signal?: AbortSignal }) =>
143+
new Promise((resolve) => {
144+
options.signal?.addEventListener('abort', () =>
145+
resolve({ response: options.cancelId ?? 0, checkboxChecked: false })
146+
)
147+
})
148+
)
149+
const events = { filePath: '/tmp/events.log', record: vi.fn() }
150+
const { handlers, source } = createProcessSource()
151+
installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source })
152+
153+
handlers.get('uncaughtException')?.(new Error('while running') as never)
154+
expect(dialog.showMessageBox).toHaveBeenCalledOnce()
155+
expect(app.exit).not.toHaveBeenCalled()
156+
157+
emitAppEvent('before-quit')
158+
await settlePrompt()
159+
160+
expect(app.exit).toHaveBeenCalledWith(1)
161+
expect(app.relaunch).not.toHaveBeenCalled()
162+
})
97163
})

‎apps/desktop/src/main/observability.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,21 @@ const FAILURE_DEDUPE_MS = 5_000
7979
* single native recovery surface. Error text is deliberately excluded from
8080
* the structured log because rejected values can contain request payloads or
8181
* credentials; the event kind and crash dumps are enough for triage.
82+
*
83+
* The recovery prompt never outlives a quit: a failure once a quit is committed
84+
* (`will-quit`) exits without asking, since a dialog opened during shutdown can
85+
* only fall back to a blocking native alert, and any quit request while the
86+
* prompt is open answers it as Quit. A `before-quit` that another listener
87+
* cancels leaves later failures their prompt.
8288
*/
8389
export function installMainProcessFailureObservers({
8490
events,
8591
getWindow,
8692
processSource = process,
8793
}: MainProcessFailureObserverDeps): void {
8894
let fatalRecoveryOpen = false
95+
let quitCommitted = false
96+
let openPrompt: AbortController | null = null
8997
let lastChildFailure = ''
9098
let lastChildFailureAt = 0
9199

@@ -117,13 +125,20 @@ export function installMainProcessFailureObservers({
117125
fatalRecoveryOpen = true
118126
events.record(name, { valueType: value instanceof Error ? 'Error' : typeof value })
119127
logger.error('Fatal main-process failure', { kind: name })
128+
if (quitCommitted) {
129+
app.exit(1)
130+
return
131+
}
132+
const promptAbort = new AbortController()
133+
openPrompt = promptAbort
120134
const options = {
121135
type: 'error' as const,
122136
buttons: ['Restart Sim', 'Quit Sim'],
123137
defaultId: 0,
124138
cancelId: 1,
125139
message: 'Sim encountered a problem',
126140
detail: 'Restart Sim to recover. Diagnostic details were saved locally.',
141+
signal: promptAbort.signal,
127142
}
128143
const win = getWindow()
129144
const prompt =
@@ -145,7 +160,17 @@ export function installMainProcessFailureObservers({
145160
reportFatal('main_uncaught_exception', error)
146161
}
147162

163+
const answerOpenPromptAsQuit = (): void => {
164+
openPrompt?.abort()
165+
}
166+
const onWillQuit = (): void => {
167+
quitCommitted = true
168+
answerOpenPromptAsQuit()
169+
}
170+
148171
app.on('child-process-gone', onChildProcessGone)
172+
app.on('before-quit', answerOpenPromptAsQuit)
173+
app.on('will-quit', onWillQuit)
149174
processSource.on('unhandledRejection', onUnhandledRejection)
150175
processSource.on('uncaughtException', onUncaughtException)
151176
}

‎apps/desktop/src/main/window.test.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { EventEmitter } from 'node:events'
12
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
23
import { createSecureWebPreferences } from '@/main/window-preferences'
34

@@ -7,7 +8,12 @@ import { BrowserWindow, dialog, screen, systemPreferences, WebContentsView } fro
78
import { registerAgentWebContents } from '@/main/browser-agent/registry'
89
import type { ConfigStore } from '@/main/config'
910
import type { EventRecorder } from '@/main/observability'
10-
import { createMainWindow, resolvePermission, setupPermissionHandlers } from '@/main/window'
11+
import {
12+
createMainWindow,
13+
detachVisibilityListenersOnClose,
14+
resolvePermission,
15+
setupPermissionHandlers,
16+
} from '@/main/window'
1117

1218
const APP = 'https://sim.ai'
1319

@@ -195,3 +201,36 @@ describe('createMainWindow', () => {
195201
expect(event.preventDefault).toHaveBeenCalledOnce()
196202
})
197203
})
204+
205+
describe('detachVisibilityListenersOnClose', () => {
206+
/** A window wired the way Electron wires every BrowserWindow: its visibility listener reads the native window. */
207+
function electronLikeWindow() {
208+
let destroyed = false
209+
const win = Object.assign(new EventEmitter(), {
210+
isVisible: () => {
211+
if (destroyed) throw new TypeError('Object has been destroyed')
212+
return true
213+
},
214+
destroy: () => {
215+
destroyed = true
216+
win.emit('closed')
217+
},
218+
})
219+
const visibilityChanged = () => win.isVisible()
220+
for (const event of ['show', 'hide', 'minimize', 'maximize', 'restore']) {
221+
win.on(event, visibilityChanged)
222+
}
223+
return win
224+
}
225+
226+
it('a visibility event delivered after the window closed no longer throws', () => {
227+
const win = electronLikeWindow()
228+
detachVisibilityListenersOnClose(win as never)
229+
230+
win.emit('show')
231+
win.destroy()
232+
233+
expect(() => win.emit('show')).not.toThrow()
234+
expect(() => win.emit('hide')).not.toThrow()
235+
})
236+
})

‎apps/desktop/src/main/window.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,21 @@ const MIN_HEIGHT = 600
1919
const WINDOW_TITLE = 'Sim'
2020
const BOUNDS_SAVE_DELAY_MS = 400
2121
const ROUTE_SAVE_DELAY_MS = 500
22+
/** The events Electron's own per-window `visibilityChanged` listener subscribes to. */
23+
const VISIBILITY_EVENTS = ['show', 'hide', 'minimize', 'maximize', 'restore'] as const
24+
25+
/**
26+
* Drops a closed window's visibility listeners. macOS can deliver a window's
27+
* `show` (an occlusion change) after the window has closed and been destroyed,
28+
* as when the app quits just as its first window appears; Electron's own
29+
* listener then reads `isVisible()` from the dead window and throws "Object has
30+
* been destroyed" as an uncaught main-process exception during shutdown.
31+
*/
32+
export function detachVisibilityListenersOnClose(win: BrowserWindow): void {
33+
win.once('closed', () => {
34+
for (const event of VISIBILITY_EVENTS) win.removeAllListeners(event)
35+
})
36+
}
2237

2338
/**
2439
* The permission matrix: sanitized clipboard writes and microphone access for

0 commit comments

Comments
 (0)