Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion apps/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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
Expand Down
66 changes: 66 additions & 0 deletions apps/desktop/src/main/observability.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Comment on lines +104 to +106

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Shared test helper is duplicated

settlePrompt() redefines the existing flushMicrotasks() helper. The testing guide requires using shared helpers instead of redefining them. Replace this function with flushMicrotasks(5) from @sim/testing/helpers/async, adding the workspace dependency if needed.

This repository requirement must be satisfied before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!


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()
})
})
25 changes: 25 additions & 0 deletions apps/desktop/src/main/observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,21 @@ 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,
getWindow,
processSource = process,
}: MainProcessFailureObserverDeps): void {
let fatalRecoveryOpen = false
let quitCommitted = false
let openPrompt: AbortController | null = null
let lastChildFailure = ''
let lastChildFailureAt = 0

Expand Down Expand Up @@ -117,13 +125,20 @@ 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'],
defaultId: 0,
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 =
Expand All @@ -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)
}
Expand Down
41 changes: 40 additions & 1 deletion apps/desktop/src/main/window.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { EventEmitter } from 'node:events'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createSecureWebPreferences } from '@/main/window-preferences'

Expand All @@ -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'

Expand Down Expand Up @@ -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()
})
})
15 changes: 15 additions & 0 deletions apps/desktop/src/main/window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Comment on lines +33 to +35

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Late window events still throw

detachVisibilityListenersOnClose leaves Electron's listener active until closed. The PR description reports that some late show events arrive after destruction but before closed. In that order, visibilityChanged still calls isVisible() on a destroyed window and raises a fatal error during quit.

Guard the listener with isDestroyed() before it runs, and cover that event order in the test.

}

/**
* The permission matrix: sanitized clipboard writes and microphone access for
Expand Down
Loading