Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async function captureHostRetirement(directory: string) {
) {
throw new Error('host retirement fixture did not load')
}
const captured: unknown = fixture.captureOriginalDeliveryRetirement(directory)
const captured: unknown = await fixture.captureOriginalDeliveryRetirement(directory)
return retirementSchema.parse(captured)
}

Expand Down
31 changes: 31 additions & 0 deletions src/main/ipc/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,37 @@ describe('registerAppHandlers', () => {
expect(appExitMock).toHaveBeenCalledWith(0)
})

it('runs exit-only cleanup after pre-relaunch cleanup on relaunch, never on restart', async () => {
let finishExitCleanup!: () => void
const onBeforeRelaunch = vi.fn()
const onBeforeRelaunchExit = vi.fn(
() =>
new Promise<void>((resolve) => {
finishExitCleanup = resolve
})
)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: relaunch and restart never read the store.
registerAppHandlers({} as never, { onBeforeRelaunch, onBeforeRelaunchExit })

await handlers.get('app:restart')?.(null)
await vi.advanceTimersByTimeAsync(150)
expect(onBeforeRelaunchExit).not.toHaveBeenCalled()

const relaunchPromise = Promise.resolve(handlers.get('app:relaunch')?.(null))
await vi.advanceTimersByTimeAsync(0)
expect(onBeforeRelaunchExit).toHaveBeenCalledOnce()
expect(onBeforeRelaunch.mock.invocationCallOrder.at(-1)).toBeLessThan(
onBeforeRelaunchExit.mock.invocationCallOrder[0]
)
await vi.advanceTimersByTimeAsync(150)
expect(appExitMock).not.toHaveBeenCalled()

finishExitCleanup()
await relaunchPromise
await vi.advanceTimersByTimeAsync(150)
expect(appExitMock).toHaveBeenCalledWith(0)
})

it('marks restart as expected shutdown before quitting through the normal pipeline', async () => {
const onBeforeRelaunch = vi.fn()
registerAppHandlers({} as never, { onBeforeRelaunch })
Expand Down
3 changes: 3 additions & 0 deletions src/main/ipc/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { readCommandStdout, readKeyboardInputSourceId } from './macos-keyboard-i

type RegisterAppHandlersOptions = {
onBeforeRelaunch?: () => void | Promise<void>
/** Only for app:relaunch, whose app.exit(0) is committed and skips will-quit. */
onBeforeRelaunchExit?: () => void | Promise<void>
}

async function pickFloatingMarkdownDocument(
Expand Down Expand Up @@ -151,6 +153,7 @@ export function registerAppHandlers(store: Store, options: RegisterAppHandlersOp
ipcMain.handle('app:relaunch', async () => {
// Why: brief delay lets the renderer paint "Restarting…" before the window tears down.
await runBeforeRelaunchCleanup(options.onBeforeRelaunch)
await runBeforeRelaunchCleanup(options.onBeforeRelaunchExit)
setTimeout(() => {
// Why: app.exit(0) skips before-quit, so destroy the Windows tray manually to avoid a stale icon.
destroySystemTray()
Expand Down
9 changes: 6 additions & 3 deletions src/main/ipc/notifications-subject-retirement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,8 @@ describe('notifications:dismiss by acknowledged subject', () => {
// Positioned alerts outlive a no-read or earlier-bounded dismiss: a view ack can run before the transcript shows the edge.
it('pane dismissal retires older-host structured alerts but not positioned ones past the read', async () => {
const directory = mkdtempSync(join(tmpdir(), 'orca-pane-boundary-'))
const controller = new RuntimeMobileNotificationController()
try {
const controller = new RuntimeMobileNotificationController()
controller.configureDismissalStore(directory)
const events: MobileNotificationEvent[] = []
controller.onDispatched((event) => events.push(event))
Expand Down Expand Up @@ -232,13 +232,14 @@ describe('notifications:dismiss by acknowledged subject', () => {
expect(dismissMobileNotification).toHaveBeenCalledTimes(1)
expect(events.filter((event) => event.type === 'dismiss')).toHaveLength(2)
} finally {
await controller.closeDismissals()
rmSync(directory, { recursive: true, force: true })
}
})
it('the click-time read a Mark read sends closes and retires every alert it covers', async () => {
const directory = mkdtempSync(join(tmpdir(), 'orca-explicit-read-'))
const controller = new RuntimeMobileNotificationController()
try {
const controller = new RuntimeMobileNotificationController()
controller.configureDismissalStore(directory)
const events: MobileNotificationEvent[] = []
controller.onDispatched((event) => events.push(event))
Expand Down Expand Up @@ -288,14 +289,15 @@ describe('notifications:dismiss by acknowledged subject', () => {
events.filter((event) => event.type === 'dismiss').map((event) => event.notificationId)
).toEqual(['agent-attention:click-A', 'agent-attention:click-B'])
} finally {
await controller.closeDismissals()
rmSync(directory, { recursive: true, force: true })
}
})

it('settles only the relayed prompt alerts of a session its host reports none pending for', async () => {
const directory = mkdtempSync(join(tmpdir(), 'orca-relay-settle-'))
const controller = new RuntimeMobileNotificationController()
try {
const controller = new RuntimeMobileNotificationController()
controller.configureDismissalStore(directory)
const events: MobileNotificationEvent[] = []
controller.onDispatched((event) => events.push(event))
Expand Down Expand Up @@ -340,6 +342,7 @@ describe('notifications:dismiss by acknowledged subject', () => {
events.filter((event) => event.type === 'dismiss').map((event) => event.notificationId)
).toEqual([key('prompt:A')])
} finally {
await controller.closeDismissals()
rmSync(directory, { recursive: true, force: true })
}
})
Expand Down
39 changes: 36 additions & 3 deletions src/main/ipc/register-core-handlers/register-core-handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,13 @@ import { registerCoreHandlers } from './register-core-handlers'
let registeredAiVaultOptions: {
ensureStructuredSessionOwnership: () => Promise<void>
}
let registeredRuntime: { ensureStructuredAgentSessionHost: ReturnType<typeof vi.fn> } | undefined
let registeredRuntime:
| {
ensureStructuredAgentSessionHost: ReturnType<typeof vi.fn>
closeNotificationDismissals: ReturnType<typeof vi.fn>
}
| undefined
let registeredRelaunchExit: (() => Promise<void>) | undefined

describe('registerCoreHandlers', () => {
beforeEach(() => {
Expand Down Expand Up @@ -488,7 +494,8 @@ describe('registerCoreHandlers', () => {
const runtime = {
marker: 'runtime',
getAgentBrowserBridge: () => null,
ensureStructuredAgentSessionHost: vi.fn()
ensureStructuredAgentSessionHost: vi.fn(),
closeNotificationDismissals: vi.fn(async () => {})
}
const stats = { marker: 'stats' }
const claudeUsage = { marker: 'claudeUsage' }
Expand Down Expand Up @@ -540,7 +547,13 @@ describe('registerCoreHandlers', () => {
openCodeUsage,
museUsage
})
expect(registerAppHandlersMock).toHaveBeenCalledWith(store, { onBeforeRelaunch })
expect(registerAppHandlersMock).toHaveBeenCalledWith(store, {
onBeforeRelaunch,
onBeforeRelaunchExit: expect.any(Function)
})
registeredRelaunchExit = registerAppHandlersMock.mock.calls[0]?.[1]?.onBeforeRelaunchExit
await registeredRelaunchExit?.()
expect(runtime.closeNotificationDismissals).toHaveBeenCalledOnce()
expect(registerCodexAccountHandlersMock).toHaveBeenCalledWith(
codexAccounts,
expect.any(Function)
Expand Down Expand Up @@ -694,6 +707,26 @@ describe('registerCoreHandlers', () => {
}
})

it('lets relaunch exit after 2 s when the dismissal close never settles', async () => {
vi.useFakeTimers()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
try {
registeredRuntime?.closeNotificationDismissals.mockReturnValueOnce(new Promise(() => {}))
let exited = false
void registeredRelaunchExit?.().then(() => {
exited = true
})
await vi.advanceTimersByTimeAsync(1_999)
expect(exited).toBe(false)
await vi.advanceTimersByTimeAsync(1)
expect(exited).toBe(true)
expect(warn).toHaveBeenCalledOnce()
} finally {
warn.mockRestore()
vi.useRealTimers()
}
})

it('only registers IPC handlers once but always updates web contents id', () => {
// The first test already called registerCoreHandlers, so the module-level
// guard is now set. beforeEach reset all mocks, so call counts are 0.
Expand Down
21 changes: 20 additions & 1 deletion src/main/ipc/register-core-handlers/register-core-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,23 @@ import { callRuntimeSessionSearch } from '../../ai-vault/runtime-session-search-
import { ensureStructuredAgentSessionHostUnlessRefused } from '../../runtime/structured-agent-session-host-refusal'
import type { PluginService } from '../../plugins/plugin-service'
import type { PluginMarketplaceHandlerServices } from '../plugin-marketplaces'
import { settleWithinMs } from '../../quit-teardown-deadline'

let registered = false
// Same cap as the restart path's auth preservation: bookkeeping must not hold Restart on a stalled disk.
const RELAUNCH_DISMISSAL_CLOSE_TIMEOUT_MS = 2_000

async function closeNotificationDismissalsBeforeRelaunch(
runtime: OrcaRuntimeService
): Promise<void> {
const result = await settleWithinMs(
runtime.closeNotificationDismissals(),
RELAUNCH_DISMISSAL_CLOSE_TIMEOUT_MS
)
if (result.outcome === 'timed-out') {
console.warn('[notifications] Relaunching before dismissal recovery state finished saving')
}
}

type CoreHandlerLifecycleOptions = {
onBeforeRelaunch?: () => void | Promise<void>
Expand Down Expand Up @@ -144,7 +159,11 @@ export function registerCoreHandlers(
}
registered = true

registerAppHandlers(store, { onBeforeRelaunch: lifecycleOptions.onBeforeRelaunch })
registerAppHandlers(store, {
onBeforeRelaunch: lifecycleOptions.onBeforeRelaunch,
// Why here, not onBeforeRelaunch: restart and profile switches quit through will-quit, which closes it.
onBeforeRelaunchExit: () => closeNotificationDismissalsBeforeRelaunch(runtime)
})
registerCliHandlers()
registerPreflightHandlers()
registerUsageProviderHandlers({ claudeUsage, codexUsage, openCodeUsage, museUsage })
Expand Down
14 changes: 14 additions & 0 deletions src/main/orcad/orcad-entry.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import {
flushOrcadProfileStoreForShutdown,
Expand Down Expand Up @@ -168,3 +170,15 @@ describe('orcad profile-state shutdown', () => {
expect(freezeWritesAsync).toHaveBeenCalledOnce()
})
})

describe('orcad runtime cleanup order', () => {
// Booting orcad here would need its whole runtime; the wiring is pinned by the entry point's text.
it('closes notification dismissals in a cleanup that runs after RPC stops', () => {
const entry = readFileSync(join(import.meta.dirname, 'orcad-entry.ts'), 'utf8')
const close = entry.indexOf('registerCleanup(() => runtime.closeNotificationDismissals())')
const rpcStop = entry.indexOf('registerCleanup(() => rpc.stop())')
expect(close).toBeGreaterThan(-1)
// Cleanups run in reverse registration order.
expect(close).toBeLessThan(rpcStop)
})
})
2 changes: 2 additions & 0 deletions src/main/orcad/orcad-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,8 @@ async function startOrcadRuntime(
await runtime.refreshRestoredOrchestrationAuthority()
await runtime.reconcileLegacyWorkerTerminals()

// Runs after RPC stops (cleanups run reversed); later records save synchronously until exit.
registerCleanup(() => runtime.closeNotificationDismissals())
// A retry armed during recovery would otherwise write after the final profile flush.
registerCleanup(() => runtime.stopLegacyWorkerTerminalRecovery())

Expand Down
1 change: 1 addition & 0 deletions src/main/orcad/orcad-push-startup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ vi.mock('../runtime/orca-runtime', () => ({
async refreshRestoredOrchestrationAuthority() {}
async reconcileLegacyWorkerTerminals() {}
async stopLegacyWorkerTerminalRecovery() {}
async closeNotificationDismissals() {}
syncWindowGraph() {}
setMobilePushRegistrar(
registrar: Parameters<RuntimeMobileNotificationController['setPushRegistrar']>[0]
Expand Down
41 changes: 41 additions & 0 deletions src/main/persistence/atomic-snapshot-writer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,26 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type * as NodeFsPromises from 'node:fs/promises'
import { AtomicSnapshotWriter } from './atomic-snapshot-writer'

const renameHook = vi.hoisted(() => {
const hook: { afterRename: (() => void) | null } = { afterRename: null }
return hook
})
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof NodeFsPromises>()
return {
...actual,
rename: async (from: string, to: string) => {
await actual.rename(from, to)
const afterRename = renameHook.afterRename
renameHook.afterRename = null
afterRename?.()
}
}
})

describe('AtomicSnapshotWriter', () => {
let dir: string
let file: string
Expand Down Expand Up @@ -57,6 +75,29 @@ describe('AtomicSnapshotWriter', () => {
expect(readFileSync(file, 'utf8')).toBe('three')
})

it('drains a write requested in any microtask after the previous rename completes', async () => {
const nested = (depth: number, fn: () => void): void => {
if (depth === 0) {
fn()
return
}
queueMicrotask(() => nested(depth - 1, fn))
}
for (let depth = 0; depth < 8; depth += 1) {
const writer = new AtomicSnapshotWriter(() => file)
let second: Promise<void> | null = null
renameHook.afterRename = () =>
nested(depth, () => {
second = writer.write(() => `second ${depth}`)
})
await writer.write(() => `first ${depth}`)
await vi.waitFor(() => expect(second).not.toBeNull())
await second
await writer.waitForPendingWrite()
expect(readFileSync(file, 'utf8')).toBe(`second ${depth}`)
}
})

it('skips identical bytes, including content primed from disk', async () => {
const writer = new AtomicSnapshotWriter(() => file, { skipUnchanged: true })
await writer.write(() => 'same')
Expand Down
47 changes: 22 additions & 25 deletions src/main/persistence/atomic-snapshot-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,9 @@ export class AtomicSnapshotWriter {
}
this.writeRequested = true
this.pendingSerialize = serialize
if (this.pendingWrite) {
return this.pendingWrite
}
const run = this.drainWrites()
const tracked = run.finally(() => {
if (this.pendingWrite === tracked) {
this.pendingWrite = null
}
})
this.pendingWrite = tracked
return tracked
// Why safe: drainWrites awaits before its finally can clear pendingWrite, so this assignment lands first.
this.pendingWrite ??= this.drainWrites()
return this.pendingWrite
}

writeSync(serialize: () => string): void {
Expand Down Expand Up @@ -155,22 +147,27 @@ export class AtomicSnapshotWriter {
}

private async drainWrites(): Promise<void> {
await this.staleTempCleanup
let firstError: unknown = null
while (this.writeRequested && !this.closed) {
this.writeRequested = false
const serialize = this.pendingSerialize!
try {
await this.writeToDiskAsync(serialize)
} catch (error) {
firstError ??= error
if (!this.writeRequested) {
throw error
try {
await this.staleTempCleanup
let firstError: unknown = null
while (this.writeRequested && !this.closed) {
this.writeRequested = false
const serialize = this.pendingSerialize!
try {
await this.writeToDiskAsync(serialize)
} catch (error) {
firstError ??= error
if (!this.writeRequested) {
throw error
}
}
}
}
if (firstError) {
throw firstError
if (firstError) {
throw firstError
}
} finally {
// Why: clear in the same tick the loop saw no request left, so a later write() starts a new drain.
this.pendingWrite = null
}
}

Expand Down
Loading
Loading