From e18057db5885b6180116e58165f58ab39351959f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:50:26 -0700 Subject: [PATCH 1/7] perf(notifications): save mobile dismissal history off the main thread Every agent notification recorded its id in mobile-notification-dismissals.json through the secure-file writer. On Windows that writer runs about five synchronous icacls launches per write, so each notification froze every Orca window (STA-9692). The file holds notification ids, sequence numbers and session ids, not credentials, so it now goes through the existing AtomicSnapshotWriter: async temp-plus-rename, mode 0600, bursts coalesced into one write of the latest entries. Memory stays authoritative, so delivery and retirement are unchanged. The pending write is flushed in the quit barrier after chat and RPC teardown, and in the pre-relaunch hook, since renderer relaunch exits without the quit pipeline. --- .../push-original-delivery-retirement.test.ts | 2 +- ...otification-dismissal-read-failure.test.ts | 4 +- ...obile-notification-dismissal-store.test.ts | 60 ++++++++++++++----- .../mobile-notification-dismissal-store.ts | 28 +++++---- .../runtime-mobile-notification-controller.ts | 4 ++ .../runtime-service-command-surface.ts | 2 + ...tured-agent-session-mobile-restore.test.ts | 2 + ...ttention-original-delivery.test-fixture.ts | 5 +- .../main-process-quit-pending-writer.test.ts | 37 +++++++++++- src/main/startup/main-process-quit.ts | 6 ++ src/main/startup/main-window-core-services.ts | 2 + ...ttention-host-read-retirement.unit.test.ts | 1 + ...ctured-attention-prompt-relay.unit.test.ts | 49 ++++++++------- 13 files changed, 146 insertions(+), 56 deletions(-) diff --git a/mobile/src/notifications/push-original-delivery-retirement.test.ts b/mobile/src/notifications/push-original-delivery-retirement.test.ts index fa0c572276e1..48821d5c0481 100644 --- a/mobile/src/notifications/push-original-delivery-retirement.test.ts +++ b/mobile/src/notifications/push-original-delivery-retirement.test.ts @@ -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) } diff --git a/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts b/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts index a665e9b4444f..fbf21d733209 100644 --- a/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts +++ b/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts @@ -8,7 +8,7 @@ vi.mock('node:fs', async (original) => { const f = await original() return { ...f, readFileSync: vi.fn(f.readFileSync) } }) -it('preserves dismissal history after EIO', () => { +it('preserves dismissal history after EIO', async () => { const dir = mkdtempSync(join(tmpdir(), 'push-comment-')) try { const store = new MobileNotificationDismissalStore(dir) @@ -18,6 +18,7 @@ it('preserves dismissal history after EIO', () => { notificationEpoch: 'epoch', notificationSeq: 1 }) + await store.flush() const path = join(dir, 'mobile-notification-dismissals.json') const before = readFileSync(path, 'utf8') vi.mocked(readFileSync).mockImplementationOnce(() => { @@ -30,6 +31,7 @@ it('preserves dismissal history after EIO', () => { notificationEpoch: 'epoch', notificationSeq: 2 }) + await restarted.flush() expect(readFileSync(path, 'utf8')).toBe(before) } finally { vi.restoreAllMocks() diff --git a/src/main/runtime/mobile-notification-dismissal-store.test.ts b/src/main/runtime/mobile-notification-dismissal-store.test.ts index f90a41b7a0b3..b541778c7874 100644 --- a/src/main/runtime/mobile-notification-dismissal-store.test.ts +++ b/src/main/runtime/mobile-notification-dismissal-store.test.ts @@ -1,17 +1,21 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import { MobileNotificationDismissalStore } from './mobile-notification-dismissal-store' const paths: string[] = [] -afterEach(() => { +const stores: MobileNotificationDismissalStore[] = [] +afterEach(async () => { + await Promise.all(stores.splice(0).map((store) => store.flush())) paths.splice(0).forEach((path) => rmSync(path, { recursive: true, force: true })) vi.restoreAllMocks() }) function fixture() { const path = mkdtempSync(join(tmpdir(), 'orca-dismissals-')) paths.push(path) - return { path, store: new MobileNotificationDismissalStore(path) } + const store = new MobileNotificationDismissalStore(path) + stores.push(store) + return { path, store } } const shown = { notificationId: 'same', notificationEpoch: 'old', notificationSeq: 12 } const alert = { @@ -20,9 +24,10 @@ const alert = { title: 'QA', body: '' } -it('reconciles an old delivered alert after desktop restart and preserves unrelated identities', () => { +it('reconciles an old delivered alert after desktop restart and preserves unrelated identities', async () => { const h = fixture() h.store.record({ ...alert, ...shown }) + await h.store.flush() const restarted = new MobileNotificationDismissalStore(h.path) restarted.record({ type: 'dismiss', @@ -30,6 +35,7 @@ it('reconciles an old delivered alert after desktop restart and preserves unrela notificationEpoch: 'new', notificationSeq: 1 }) + await restarted.flush() const loaded = new MobileNotificationDismissalStore(h.path) expect( loaded.reconcile([ @@ -55,7 +61,7 @@ it('does not dismiss a newer replacement and does not treat missing or expired h expect(h.store.reconcile([shown])).toEqual([]) expect(new MobileNotificationDismissalStore(`${h.path}-unknown`).reconcile([shown])).toEqual([]) }) -it('names the live deliveries a subject can still retire, across a restart', () => { +it('names the live deliveries a subject can still retire, across a restart', async () => { const h = fixture() const keyed = (notificationId: string, notificationSeq: number) => ({ ...alert, @@ -72,6 +78,7 @@ it('names the live deliveries a subject can still retire, across a restart', () notificationEpoch: 'e', notificationSeq: 4 }) + await h.store.flush() const restarted = new MobileNotificationDismissalStore(h.path) expect(restarted.liveDeliveries('subject:').map((entry) => entry.notificationId)).toEqual([ 'subject:prompt:a1' @@ -111,24 +118,45 @@ it('keeps a record whose origin a newer build wrote, losing only that origin', ( ]) }) -it('retains in-memory delivery and retirement when durable writes fail', () => { +it('retains in-memory delivery and retirement when durable writes fail', async () => { const h = fixture() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) mkdirSync(join(h.path, 'mobile-notification-dismissals.json')) - expect(() => h.store.record({ ...alert, ...shown })).toThrow() + h.store.record({ ...alert, ...shown }) expect(h.store.liveDeliveries(shown.notificationId)).toHaveLength(1) - expect(() => - h.store.record({ - type: 'dismiss', - notificationId: shown.notificationId, - notificationEpoch: 'current', - notificationSeq: 1, - dismissedDelivery: shown - }) - ).toThrow() + h.store.record({ + type: 'dismiss', + notificationId: shown.notificationId, + notificationEpoch: 'current', + notificationSeq: 1, + dismissedDelivery: shown + }) + await h.store.flush() + expect(warn).toHaveBeenCalledWith( + '[notifications] Could not persist dismissal recovery state', + expect.anything() + ) expect(h.store.liveDeliveries(shown.notificationId)).toEqual([]) expect(h.store.reconcile([shown])).toEqual([shown]) }) +it('coalesces a burst of records into writes of the latest entries, off the caller', async () => { + const h = fixture() + const file = join(h.path, 'mobile-notification-dismissals.json') + for (let seq = 0; seq < 20; seq += 1) { + h.store.record({ + ...alert, + notificationId: `n${seq}`, + notificationEpoch: 'e', + notificationSeq: seq + }) + } + expect(existsSync(file)).toBe(false) + await h.store.flush() + const saved: unknown = JSON.parse(readFileSync(file, 'utf8')) + expect(Array.isArray(saved) ? saved.length : 0).toBe(20) +}) + it('a targeted old delivery cannot retire a newer replacement with the same logical id', () => { const h = fixture() h.store.record({ ...alert, ...shown }) diff --git a/src/main/runtime/mobile-notification-dismissal-store.ts b/src/main/runtime/mobile-notification-dismissal-store.ts index 9936b005886d..497a64fe2522 100644 --- a/src/main/runtime/mobile-notification-dismissal-store.ts +++ b/src/main/runtime/mobile-notification-dismissal-store.ts @@ -1,11 +1,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' -import { - writeSecureJsonFile, - hardenExistingSecureFile, - isUnreadableError -} from '../../shared/secure-file' -import { removeStaleDurableWriteTempFiles } from '../durable-file-write' +import { isUnreadableError } from '../../shared/secure-file' +import { AtomicSnapshotWriter } from '../persistence/atomic-snapshot-writer' import type { MobileNotificationEvent } from './runtime-mobile-notification-controller' import type { DeliveredNotificationIdentity } from '../../shared/mobile-notification-identity' import { @@ -20,18 +16,18 @@ export type DeliveredNotificationRecord = DeliveredNotificationIdentity & { type RecordEntry = DeliveredNotificationRecord & { dismissedThrough: number; expiresAt: number } const LIMIT = 4096 const RETENTION_MS = 7 * 86400_000 -const STALE_WRITE_TEMP_AGE_MS = 86400_000 export class MobileNotificationDismissalStore { private readonly path: string private entries: RecordEntry[] = [] private unreadable = false + // Why not the secure writer: this holds notification ids, not credentials, and its synchronous + // Windows icacls launches froze every window on each notification (STA-9692). + private readonly writer: AtomicSnapshotWriter constructor(userDataPath: string) { this.path = join(userDataPath, 'mobile-notification-dismissals.json') - // Why: a write killed between writeFile and rename (e.g. a hung icacls, #20497) orphans its temp forever. - void removeStaleDurableWriteTempFiles(this.path, { minimumAgeMs: STALE_WRITE_TEMP_AGE_MS }) + this.writer = new AtomicSnapshotWriter(() => this.path, { fileMode: 0o600 }) try { - hardenExistingSecureFile(this.path) const value: unknown = JSON.parse(readFileSync(this.path, 'utf8')) if (Array.isArray(value)) { this.entries = value.flatMap(readEntry).slice(-LIMIT) @@ -97,10 +93,20 @@ export class MobileNotificationDismissalStore { next = next.slice(-LIMIT) this.entries = next if (!this.unreadable) { - writeSecureJsonFile(this.path, next) + // Coalesced: a burst of records costs one write of the latest entries. + this.writer + .write(() => JSON.stringify(this.entries, null, 2)) + .catch((error: unknown) => { + console.warn('[notifications] Could not persist dismissal recovery state', error) + }) } } + /** Resolves once every recorded change has been written or has failed to write. */ + flush(): Promise { + return this.writer.waitForPendingWrite().catch(() => {}) + } + liveDeliveries(prefix = ''): DeliveredNotificationRecord[] { const now = Date.now() return this.entries diff --git a/src/main/runtime/runtime-mobile-notification-controller.ts b/src/main/runtime/runtime-mobile-notification-controller.ts index 87d6adddd1dd..ecc9629c60ef 100644 --- a/src/main/runtime/runtime-mobile-notification-controller.ts +++ b/src/main/runtime/runtime-mobile-notification-controller.ts @@ -71,6 +71,10 @@ export class RuntimeMobileNotificationController { this.dismissalStore = new MobileNotificationDismissalStore(userDataPath) } + flushDismissals(): Promise { + return this.dismissalStore?.flush() ?? Promise.resolve() + } + reconcileDismissedPushes( delivered: readonly DeliveredNotificationIdentity[] ): DeliveredNotificationIdentity[] { diff --git a/src/main/runtime/runtime-service-command-surface.ts b/src/main/runtime/runtime-service-command-surface.ts index 966976e1a946..2e56f5407d92 100644 --- a/src/main/runtime/runtime-service-command-surface.ts +++ b/src/main/runtime/runtime-service-command-surface.ts @@ -32,6 +32,7 @@ export type RuntimeServiceCommandSurface = { dispatchMobileNotification: RuntimeMobileNotificationController['dispatch'] getMissedNotificationsSince: RuntimeMobileNotificationController['getMissedSince'] configureNotificationDismissalStore: RuntimeMobileNotificationController['configureDismissalStore'] + flushNotificationDismissals: RuntimeMobileNotificationController['flushDismissals'] reconcileDismissedPushes: RuntimeMobileNotificationController['reconcileDismissedPushes'] getMobileNotificationEpoch: RuntimeMobileNotificationController['getEpoch'] dismissMobileNotification: RuntimeMobileNotificationController['dismiss'] @@ -131,6 +132,7 @@ export function installRuntimeServiceCommandSurface( dispatchMobileNotification: notifications.dispatch.bind(notifications), getMissedNotificationsSince: notifications.getMissedSince.bind(notifications), configureNotificationDismissalStore: notifications.configureDismissalStore.bind(notifications), + flushNotificationDismissals: notifications.flushDismissals.bind(notifications), reconcileDismissedPushes: notifications.reconcileDismissedPushes.bind(notifications), getMobileNotificationEpoch: notifications.getEpoch.bind(notifications), dismissMobileNotification: notifications.dismiss.bind(notifications), diff --git a/src/main/runtime/structured-agent-session-mobile-restore.test.ts b/src/main/runtime/structured-agent-session-mobile-restore.test.ts index 0e3033f000b2..bf49c8c86d1f 100644 --- a/src/main/runtime/structured-agent-session-mobile-restore.test.ts +++ b/src/main/runtime/structured-agent-session-mobile-restore.test.ts @@ -80,6 +80,7 @@ describe('prompt delivery after host recovery', () => { notificationSeq: delivered.notificationSeq } unsubscribe() + await original.flushDismissals() const restarted = new RuntimeMobileNotificationController() restarted.configureDismissalStore(h.root) const events: MobileNotificationEvent[] = [] @@ -109,6 +110,7 @@ describe('prompt delivery after host recovery', () => { expect(events.filter((event) => event.type === 'dismiss')).toEqual([ expect.objectContaining({ dismissedDelivery: identity }) ]) + await restarted.flushDismissals() expect( new MobileNotificationDismissalStore(h.root).liveDeliveries(identity.notificationId) ).toEqual([]) diff --git a/src/main/runtime/structured-attention-original-delivery.test-fixture.ts b/src/main/runtime/structured-attention-original-delivery.test-fixture.ts index d142a3a6acbc..4834d3b068f7 100644 --- a/src/main/runtime/structured-attention-original-delivery.test-fixture.ts +++ b/src/main/runtime/structured-attention-original-delivery.test-fixture.ts @@ -3,11 +3,11 @@ import { type MobileNotificationDismissEvent } from './runtime-mobile-notification-controller' -export function captureOriginalDeliveryRetirement(directory: string): { +export async function captureOriginalDeliveryRetirement(directory: string): Promise<{ originalEpoch: string restartedEpoch: string event: MobileNotificationDismissEvent -} { +}> { const original = new RuntimeMobileNotificationController() original.configureDismissalStore(directory) original.dispatch({ @@ -28,6 +28,7 @@ export function captureOriginalDeliveryRetirement(directory: string): { cause: { kind: 'prompt', promptId: 'A' } } }) + await original.flushDismissals() const restarted = new RuntimeMobileNotificationController() restarted.configureDismissalStore(directory) let event: MobileNotificationDismissEvent | undefined diff --git a/src/main/startup/main-process-quit-pending-writer.test.ts b/src/main/startup/main-process-quit-pending-writer.test.ts index c75d2191237f..f897db7eaf7f 100644 --- a/src/main/startup/main-process-quit-pending-writer.test.ts +++ b/src/main/startup/main-process-quit-pending-writer.test.ts @@ -5,6 +5,7 @@ import { WILL_QUIT_TEARDOWN_DEADLINE_MS } from '../quit-teardown-deadline' const settled = () => vi.fn(async () => {}) const idle = () => vi.fn() const stopAgentHookServer = idle() +const stopStructuredAgentSessionRuntime = settled() // Every teardown member settles except the profile store, so only the writer can hold quit. const dependencies: Record> = { @@ -19,7 +20,7 @@ const dependencies: Record> = { '../agent-hooks/managed-agent-hook-controls': { removeManagedAgentHooksAsync: vi.fn(async () => []) }, - '../runtime/structured-agent-session-runtime': { stopStructuredAgentSessionRuntime: settled() }, + '../runtime/structured-agent-session-runtime': { stopStructuredAgentSessionRuntime }, '../runtime/structured-agent-session-runtime-teardown': { setStructuredAgentSessionTeardownTrigger: idle() }, @@ -58,7 +59,10 @@ afterEach(() => { vi.resetModules() }) -async function startQuit(flushFinalOrThrowAsync: () => Promise) { +async function startQuit( + flushFinalOrThrowAsync: () => Promise, + runtime?: Record +) { vi.resetModules() vi.useFakeTimers() const app = Object.assign(new EventEmitter(), { quit: vi.fn() }) @@ -68,7 +72,13 @@ async function startQuit(flushFinalOrThrowAsync: () => Promise) { freezeWritesAsync: settled() } const profileStateAdmission: typeof admission | undefined = admission - const state = { isQuitting: false, watcherShutdownDone: true, store, profileStateAdmission } + const state = { + isQuitting: false, + watcherShutdownDone: true, + store, + profileStateAdmission, + runtime + } vi.doMock('electron', () => ({ app })) vi.doMock('./main-process-state', () => ({ mainProcessState: state })) for (const [moduleName, exports] of Object.entries(dependencies)) { @@ -113,3 +123,24 @@ it('stops the hook server without clearing the status store the chat teardown re await startQuit(async () => {}) expect(stopAgentHookServer).toHaveBeenCalledWith({ keepStatus: true }) }) + +it('holds quit for the notification dismissal flush, started after chat teardown settles', async () => { + const flushNotificationDismissals = vi.fn(() => new Promise(() => {})) + const { app } = await startQuit(async () => {}, { + getOffscreenBrowserBackend: () => null, + getAgentBrowserBridge: () => null, + getEmulatorBridge: () => null, + disposeSkillUploadSessions: settled(), + getRuntimeId: () => undefined, + flushNotificationDismissals + }) + expect(stopStructuredAgentSessionRuntime).toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(0) + expect(flushNotificationDismissals).toHaveBeenCalledOnce() + expect(app.quit).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(WILL_QUIT_TEARDOWN_DEADLINE_MS) + expect(console.warn).toHaveBeenCalledWith('[shutdown] Quit teardown deadline reached', { + pendingTeardowns: ['notification-dismissals'] + }) + expect(app.quit).toHaveBeenCalledOnce() +}) diff --git a/src/main/startup/main-process-quit.ts b/src/main/startup/main-process-quit.ts index d96163ec3771..1e6aa481a32f 100644 --- a/src/main/startup/main-process-quit.ts +++ b/src/main/startup/main-process-quit.ts @@ -249,6 +249,11 @@ function installWillQuitHandler(): void { }) .catch((error) => console.error('[runtime] Failed to stop local RPC transport:', error)) : Promise.resolve() + // After session and RPC teardown, which can still retire notifications. + const notificationDismissalFlush = Promise.allSettled([ + structuredAgentSessionShutdown, + rpcStopAndClear + ]).then(() => state.runtime?.flushNotificationDismissals()) // Why: allSettled (not all) keeps fail-open — a daemon-disconnect rejection still quits instead of hanging. // Why: telemetry flush folds in before app.quit() (bounded 2s); catch defensively so a flush failure can't cancel the quit chain. // Why: normal quits keep the detached daemon for warm reattach, but a dead dev parent leaves the temp/dev profile ownerless. @@ -274,6 +279,7 @@ function installWillQuitHandler(): void { { name: 'codex-backfill-recovery', promise: codexBackfillRecoveryShutdown }, { name: 'structured-agent-session', promise: structuredAgentSessionShutdown }, { name: 'usage-cache', promise: usageCacheFlush }, + { name: 'notification-dismissals', promise: notificationDismissalFlush }, { name: 'stats', promise: statsFlush }, { name: 'state', promise: storeFlush } ]) diff --git a/src/main/startup/main-window-core-services.ts b/src/main/startup/main-window-core-services.ts index 7185b743e89e..c053decca5b9 100644 --- a/src/main/startup/main-window-core-services.ts +++ b/src/main/startup/main-window-core-services.ts @@ -94,6 +94,8 @@ export function attachMainWindowCoreServices( state.isQuitting = true state.desktopRelayService?.fenceAndCloseNow() await preserveAgentAuthBeforeRestart({ codexRuntimeHome, store }) + // Why: renderer relaunch exits via app.exit(0), which skips the quit pipeline's flush. + await runtime.flushNotificationDismissals() }, onOrcaProfileAuthMutation: () => { // Why: a provider whose launch-time install failed is installed by the next auth change. diff --git a/tests/e2e/structured-attention-host-read-retirement.unit.test.ts b/tests/e2e/structured-attention-host-read-retirement.unit.test.ts index 87734e999424..2643aad2ad70 100644 --- a/tests/e2e/structured-attention-host-read-retirement.unit.test.ts +++ b/tests/e2e/structured-attention-host-read-retirement.unit.test.ts @@ -213,6 +213,7 @@ it('a restart sends the original delivery fence in the existing native gateway f if (!original) { throw new Error('prompt not delivered') } + await h.controller.flushDismissals() const restarted = new RuntimeMobileNotificationController() restarted.configureDismissalStore(directory) const gateway = createHarness({ diff --git a/tests/e2e/structured-attention-prompt-relay.unit.test.ts b/tests/e2e/structured-attention-prompt-relay.unit.test.ts index 4744934afc79..304824627db2 100644 --- a/tests/e2e/structured-attention-prompt-relay.unit.test.ts +++ b/tests/e2e/structured-attention-prompt-relay.unit.test.ts @@ -155,7 +155,10 @@ describe('Delayed remote prompt delivery', () => { result: edge }) }, - liveDeliveries: () => new MobileNotificationDismissalStore(relayDirectory).liveDeliveries() + liveDeliveries: async () => { + await relay.flushDismissals() + return new MobileNotificationDismissalStore(relayDirectory).liveDeliveries() + } } } @@ -205,7 +208,7 @@ describe('Delayed remote prompt delivery', () => { await act(async () => relay.release()) expect(transport.dispatch).not.toHaveBeenCalled() expect(relay.relayEvents).toEqual([]) - expect(relay.liveDeliveries()).toEqual([]) + expect(await relay.liveDeliveries()).toEqual([]) expect(useAppStore.getState().unreadAgentCompletionPanes[SUBJECT]).toBeUndefined() } ) @@ -230,7 +233,7 @@ describe('Delayed remote prompt delivery', () => { expect(relay.relayEvents).toMatchObject([ { type: 'notification', notificationId: agentSessionPromptAttentionKey(SCOPE, SESSION, 'B') } ]) - expect(relay.liveDeliveries()).toHaveLength(1) + expect(await relay.liveDeliveries()).toHaveLength(1) expect(useAppStore.getState().unreadAgentCompletionPanes[SUBJECT]).toBe('agent-completion') }) @@ -271,7 +274,7 @@ describe('Delayed remote prompt delivery', () => { expect(dismissIds()).toEqual([]) await act(async () => relay.release()) expect(relay.relayEvents).toMatchObject([{ type: 'notification' }]) - expect(relay.liveDeliveries()).toHaveLength(1) + expect(await relay.liveDeliveries()).toHaveLength(1) }) it('a genuine read during unread writes prevents the final relay delivery', async () => { @@ -294,7 +297,7 @@ describe('Delayed remote prompt delivery', () => { expect(readDuringUnread).toBe(true) await waitFor(() => expect(dismissIds()).toHaveLength(1)) expect(relay.relayEvents).toEqual([]) - expect(relay.liveDeliveries()).toEqual([]) + expect(await relay.liveDeliveries()).toEqual([]) } finally { stop() } @@ -351,7 +354,7 @@ describe('Delayed remote prompt delivery', () => { ) } expect(relay.relayEvents).toMatchObject([{ type: 'notification' }]) - expect(relay.liveDeliveries()).toHaveLength(1) + expect(await relay.liveDeliveries()).toHaveLength(1) } ) @@ -395,7 +398,7 @@ describe('Delayed remote prompt delivery', () => { notificationId: `${agentSessionAttentionSubjectPrefix(SCOPE, SESSION)}turn:turn-1` } ]) - expect(relay.liveDeliveries()).toHaveLength(1) + expect(await relay.liveDeliveries()).toHaveLength(1) } ) }) @@ -478,10 +481,12 @@ describe('Remote prompt settlement', () => { await waitFor(() => expect(fixture.completion).toBeTypeOf('function')) await waitFor(() => expect(fixture.status).toBeTypeOf('function')) act(() => publishStatus()) - const live = (kind: 'prompt' | 'completion') => - new MobileNotificationDismissalStore(relayDirectory) + const live = async (kind: 'prompt' | 'completion') => { + await relay.flushDismissals() + return new MobileNotificationDismissalStore(relayDirectory) .liveDeliveries() .filter((entry) => entry.structuredOrigin?.cause.kind === kind) + } if (options?.raise === false) { return { live } } @@ -492,7 +497,7 @@ describe('Remote prompt settlement', () => { } publishView() }) - await waitFor(() => expect(live('prompt')).toHaveLength(1)) + await waitFor(async () => expect(await live('prompt')).toHaveLength(1)) return { live } } @@ -567,7 +572,7 @@ describe('Remote prompt settlement', () => { fixture.hostFeed.observe(SESSION) publishStatus() }) - await waitFor(() => expect(relay.live('prompt')).toEqual([])) + await waitFor(async () => expect(await relay.live('prompt')).toEqual([])) expect(readCalls()).toBe(0) expect(transport.settle).toHaveBeenCalledOnce() // Prompt settlement never touches a completion alert. @@ -575,7 +580,7 @@ describe('Remote prompt settlement', () => { ([request]: [NotificationDispatchRequest]) => request.structuredOrigin?.cause.kind === 'completion' ) - expect(relay.live('completion')).toHaveLength(relayedCompletions.length) + expect(await relay.live('completion')).toHaveLength(relayedCompletions.length) } ) @@ -586,7 +591,7 @@ describe('Remote prompt settlement', () => { revise((item) => interrupt(resolveA('cancelled')(item))) await waitFor(() => expect(fixture.status).not.toBe(before)) act(() => publishStatus()) - await waitFor(() => expect(relay.live('prompt')).toEqual([])) + await waitFor(async () => expect(await relay.live('prompt')).toEqual([])) }) it('keeps the relayed prompt alert while the host still reports a prompt pending', async () => { @@ -597,7 +602,7 @@ describe('Remote prompt settlement', () => { }) await act(async () => {}) expect(transport.settle).not.toHaveBeenCalled() - expect(relay.live('prompt')).toHaveLength(1) + expect(await relay.live('prompt')).toHaveLength(1) }) it('never settles from a status the desktop lost contact with', async () => { @@ -606,7 +611,7 @@ describe('Remote prompt settlement', () => { act(() => endStatusStream()) await act(async () => {}) expect(transport.settle).not.toHaveBeenCalled() - expect(relay.live('prompt')).toHaveLength(1) + expect(await relay.live('prompt')).toHaveLength(1) }) it('settles once per relayed prompt, not on every later status update', async () => { @@ -633,7 +638,7 @@ describe('Remote prompt settlement', () => { act(() => publishStatus()) await act(async () => {}) expect(transport.settle).not.toHaveBeenCalled() - expect(relay.live('prompt')).toHaveLength(1) + expect(await relay.live('prompt')).toHaveLength(1) }) it('keeps it when a queued frame lands in the same task as the edge', async () => { @@ -644,7 +649,7 @@ describe('Remote prompt settlement', () => { }) await act(async () => {}) expect(transport.settle).not.toHaveBeenCalled() - expect(relay.live('prompt')).toHaveLength(2) + expect(await relay.live('prompt')).toHaveLength(2) }) it('retries a settlement that failed on the next qualifying row', async () => { @@ -657,13 +662,13 @@ describe('Remote prompt settlement', () => { publishStatus() }) await waitFor(() => expect(transport.settle).toHaveBeenCalledOnce()) - expect(relay.live('prompt')).toHaveLength(1) + expect(await relay.live('prompt')).toHaveLength(1) transport.settle.mockImplementation(settle ?? (async () => {})) act(() => { revise((item) => item) publishStatus() }) - await waitFor(() => expect(relay.live('prompt')).toEqual([])) + await waitFor(async () => expect(await relay.live('prompt')).toEqual([])) expect(transport.settle).toHaveBeenCalledTimes(2) }) @@ -686,7 +691,7 @@ describe('Remote prompt settlement', () => { addPrompt('B') publishStatus() }) - await waitFor(() => expect(relay.live('prompt')).toHaveLength(1)) + await waitFor(async () => expect(await relay.live('prompt')).toHaveLength(1)) act(() => { revise(resolvePrompt('B', 'resolved')) fixture.hostFeed.observe(SESSION) @@ -696,7 +701,7 @@ describe('Remote prompt settlement', () => { expect(replies).toHaveLength(1) // The host goes quiet; the reply alone must re-judge the mirror. await act(async () => replies[0]?.()) - await waitFor(() => expect(relay.live('prompt')).toEqual([])) + await waitFor(async () => expect(await relay.live('prompt')).toEqual([])) }) it('settles a prompt whose edge arrives after its own resolution row', async () => { @@ -721,7 +726,7 @@ describe('Remote prompt settlement', () => { ) ).toBe(true) ) - await waitFor(() => expect(relay.live('prompt')).toEqual([])) + await waitFor(async () => expect(await relay.live('prompt')).toEqual([])) expect(transport.settle).toHaveBeenCalledOnce() }) }) From f9011be40b22d382cbaa96ad398f23f9d582d482 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 11 Oct 2026 19:28:32 -0700 Subject: [PATCH 2/7] perf(notifications): flush dismissal history when a headless host shuts down orcad never runs the desktop quit barrier, so its cleanup list awaits the pending dismissal write after RPC stops. --- src/main/orcad/orcad-entry.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/orcad-entry.ts index 307e1cb70b44..30062c61855d 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/orcad-entry.ts @@ -340,6 +340,8 @@ async function startOrcadRuntime( await runtime.refreshRestoredOrchestrationAuthority() await runtime.reconcileLegacyWorkerTerminals() + // Runs after RPC stops; orcad has no desktop quit barrier to save pending dismissals. + registerCleanup(() => runtime.flushNotificationDismissals()) // A retry armed during recovery would otherwise write after the final profile flush. registerCleanup(() => runtime.stopLegacyWorkerTerminalRecovery()) From 51cea3acdb960003c7a573445685188324ad2af9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 11 Oct 2026 20:13:33 -0700 Subject: [PATCH 3/7] fix(persistence): drain a snapshot write requested just after a drain ends AtomicSnapshotWriter cleared its pending-write promise one microtask after the drain loop saw no more requests. A write() in that gap set writeRequested, got the settling promise back, and nothing drained it, so the newest bytes stayed unwritten and waitForPendingWrite() (the dismissal store's flush) resolved without them. The drain now clears the pending promise in the same tick its loop exits, on success and failure, so a later write() always starts a new drain. --- .../atomic-snapshot-writer.test.ts | 41 +++++++++++++++++ .../persistence/atomic-snapshot-writer.ts | 46 +++++++++---------- 2 files changed, 62 insertions(+), 25 deletions(-) diff --git a/src/main/persistence/atomic-snapshot-writer.test.ts b/src/main/persistence/atomic-snapshot-writer.test.ts index e3243697bf0a..a33a86406dba 100644 --- a/src/main/persistence/atomic-snapshot-writer.test.ts +++ b/src/main/persistence/atomic-snapshot-writer.test.ts @@ -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() + 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 @@ -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 | 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') diff --git a/src/main/persistence/atomic-snapshot-writer.ts b/src/main/persistence/atomic-snapshot-writer.ts index 9a30d6b42b73..145d77eb2dcd 100644 --- a/src/main/persistence/atomic-snapshot-writer.ts +++ b/src/main/persistence/atomic-snapshot-writer.ts @@ -44,17 +44,8 @@ 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 + this.pendingWrite ??= this.drainWrites() + return this.pendingWrite } writeSync(serialize: () => string): void { @@ -155,22 +146,27 @@ export class AtomicSnapshotWriter { } private async drainWrites(): Promise { - 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 } } From ec0ccfd01b2ae95ba0d1a25775c66cc467bdf2c4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 11 Oct 2026 20:23:55 -0700 Subject: [PATCH 4/7] test(notifications): flush dismissal writes before deleting temp state dirs Dismissal history now saves asynchronously, and the writer recreates its directory before each write. Tests that deleted their temp dir with a write still pending left recreated dirs behind in the system temp folder and could race the delete on Windows. They now await the controller's flush first. --- .../ipc/notifications-subject-retirement.test.ts | 9 ++++++--- .../structured-agent-session-attention-ack.test.ts | 6 +++++- ...uctured-agent-session-mobile-retirement.test.ts | 5 +++-- ...red-attention-original-delivery.test-fixture.ts | 2 ++ ...red-attention-host-read-retirement.unit.test.ts | 14 ++++++++++---- ...ured-attention-read-retirement.test-fixture.tsx | 3 ++- ...ructured-attention-read-retirement.unit.test.ts | 3 ++- 7 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/main/ipc/notifications-subject-retirement.test.ts b/src/main/ipc/notifications-subject-retirement.test.ts index 99d8438c6848..3d4953e950d6 100644 --- a/src/main/ipc/notifications-subject-retirement.test.ts +++ b/src/main/ipc/notifications-subject-retirement.test.ts @@ -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)) @@ -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.flushDismissals() 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)) @@ -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.flushDismissals() 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)) @@ -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.flushDismissals() rmSync(directory, { recursive: true, force: true }) } }) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-attention-ack.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-attention-ack.test.ts index e5cae666b8a5..68cdf07127de 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-attention-ack.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-attention-ack.test.ts @@ -14,12 +14,15 @@ import { } from './structured-agent-session-rpc.test-fixture' let directory: string +let hostController: RuntimeMobileNotificationController | undefined beforeEach(() => { installStructuredHostStub() directory = mkdtempSync(join(tmpdir(), 'orca-attention-ack-')) }) -afterEach(() => { +afterEach(async () => { clearStructuredHostStub() + await hostController?.flushDismissals() + hostController = undefined rmSync(directory, { recursive: true, force: true }) }) @@ -35,6 +38,7 @@ const scope = (executionHostId: HostId): StructuredAttentionOrigin['scope'] => ( function hostWithDeliveries() { const controller = new RuntimeMobileNotificationController() controller.configureDismissalStore(directory) + hostController = controller const dismissed: string[] = [] controller.onDispatched((event) => { if (event.type === 'dismiss') { diff --git a/src/main/runtime/structured-agent-session-mobile-retirement.test.ts b/src/main/runtime/structured-agent-session-mobile-retirement.test.ts index 25c17a8a8b6e..011972647d57 100644 --- a/src/main/runtime/structured-agent-session-mobile-retirement.test.ts +++ b/src/main/runtime/structured-agent-session-mobile-retirement.test.ts @@ -73,14 +73,14 @@ describe('host prompt delivery and retirement', () => { ['failure', true] ] as const)( 'withdraws the prompt beside %s (announced earlier: %s)', - (outcome, announcedEarlier) => { + async (outcome, announcedEarlier) => { const directory = mkdtempSync(join(tmpdir(), 'orca-prompt-retirement-')) + const controller = new RuntimeMobileNotificationController() try { let items = [USER, turn()] let sequence = 1 const events: MobileNotificationEvent[] = [] const legacy: AgentSessionTurnCompletionEvent[] = [] - const controller = new RuntimeMobileNotificationController() controller.configureDismissalStore(directory) controller.onDispatched((event) => events.push(event)) const delivery = createStructuredAttentionMobileDelivery({ @@ -164,6 +164,7 @@ describe('host prompt delivery and retirement', () => { Number(promptAnnounced) + (outcome === 'failure' ? 1 : 0) ) } finally { + await controller.flushDismissals() rmSync(directory, { recursive: true, force: true }) } } diff --git a/src/main/runtime/structured-attention-original-delivery.test-fixture.ts b/src/main/runtime/structured-attention-original-delivery.test-fixture.ts index 4834d3b068f7..4d53c9d31074 100644 --- a/src/main/runtime/structured-attention-original-delivery.test-fixture.ts +++ b/src/main/runtime/structured-attention-original-delivery.test-fixture.ts @@ -41,6 +41,8 @@ export async function captureOriginalDeliveryRetirement(directory: string): Prom sessionId: 'session-a', observedCursor: { epoch: 'journal-a', sequence: 1 } }) + // Why: the caller deletes the directory next; an unflushed write would recreate it. + await restarted.flushDismissals() if (!event) { throw new Error('read did not withdraw the prompt') } diff --git a/tests/e2e/structured-attention-host-read-retirement.unit.test.ts b/tests/e2e/structured-attention-host-read-retirement.unit.test.ts index 2643aad2ad70..b98807ef7f51 100644 --- a/tests/e2e/structured-attention-host-read-retirement.unit.test.ts +++ b/tests/e2e/structured-attention-host-read-retirement.unit.test.ts @@ -53,9 +53,15 @@ function prompt(id: string, sequence: number): AgentJournalRenderItem { } } } -function attentionPath(directory: string) { +const controllers: RuntimeMobileNotificationController[] = [] +function storeController(directory: string): RuntimeMobileNotificationController { const controller = new RuntimeMobileNotificationController() controller.configureDismissalStore(directory) + controllers.push(controller) + return controller +} +function attentionPath(directory: string) { + const controller = storeController(directory) const events: MobileNotificationEvent[] = [] controller.onDispatched((event) => events.push(event)) let items: AgentJournalRenderItem[] = [ @@ -131,8 +137,9 @@ beforeEach(() => { installStructuredHostStub() vi.clearAllMocks() }) -afterEach(() => { +afterEach(async () => { clearStructuredHostStub() + await Promise.all(controllers.splice(0).map((controller) => controller.flushDismissals())) rmSync(directory, { recursive: true, force: true }) }) @@ -214,8 +221,7 @@ it('a restart sends the original delivery fence in the existing native gateway f throw new Error('prompt not delivered') } await h.controller.flushDismissals() - const restarted = new RuntimeMobileNotificationController() - restarted.configureDismissalStore(directory) + const restarted = storeController(directory) const gateway = createHarness({ devices: [{ deviceId: 'phone', pushRegistration: registration() }] }) diff --git a/tests/e2e/structured-attention-read-retirement.test-fixture.tsx b/tests/e2e/structured-attention-read-retirement.test-fixture.tsx index 13335a973f3a..d56e43dd6c92 100644 --- a/tests/e2e/structured-attention-read-retirement.test-fixture.tsx +++ b/tests/e2e/structured-attention-read-retirement.test-fixture.tsx @@ -338,7 +338,7 @@ beforeEach(() => { settings: createGlobalSettingsFixture({ experimentalTerminalAttention: true }) }) }) -afterEach(() => { +afterEach(async () => { cleanup() clearStructuredHostStub() resetStructuredAgentSessionReadOwnersForTests() @@ -346,5 +346,6 @@ afterEach(() => { resetStructuredAgentSessionStatusFeedsForTests() vi.unstubAllGlobals() vi.restoreAllMocks() + await fixture.controller.flushDismissals() rmSync(fixture.directory, { recursive: true, force: true }) }) diff --git a/tests/e2e/structured-attention-read-retirement.unit.test.ts b/tests/e2e/structured-attention-read-retirement.unit.test.ts index 1acdbebebb21..6cfe82f7adf4 100644 --- a/tests/e2e/structured-attention-read-retirement.unit.test.ts +++ b/tests/e2e/structured-attention-read-retirement.unit.test.ts @@ -542,13 +542,13 @@ describe('Accepted structured history read retirement', () => { it('retries a failed local desktop relay withdrawal on a later explicit read', async () => { const relayDirectory = mkdtempSync(join(tmpdir(), 'orca-relay-read-retry-')) + const relay = new RuntimeMobileNotificationController() try { addPrompt('A') const sent = fixture.events.find((event) => event.type === 'notification') if (!sent?.notificationId || sent.type !== 'notification') { throw new Error('prompt not sent') } - const relay = new RuntimeMobileNotificationController() relay.configureDismissalStore(relayDirectory) relay.dispatch(sent) const withdrawals: string[] = [] @@ -584,6 +584,7 @@ describe('Accepted structured history read retirement', () => { transport.dismiss.mock.calls.filter(([, , reads]) => Array.isArray(reads)) ).toHaveLength(2) } finally { + await relay.flushDismissals() rmSync(relayDirectory, { recursive: true, force: true }) } }) From 6f4e51dc5b277830a77a0ca4ca1e3bdbd0472cbe Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 11 Oct 2026 20:42:47 -0700 Subject: [PATCH 5/7] perf(notifications): close dismissal history at committed exits The shutdown flush only waited for writes already queued. A notification recorded after it (orcad cleanups still running, or the 150 ms before a renderer relaunch calls app.exit) started an async write the exit dropped, so the phone could keep an alert the desktop could no longer withdraw. The store's flush() becomes close(): it waits for the pending write, and every later record saves synchronously through the snapshot writer's existing writeSync (plain fs, no icacls; a failure only warns). It is called only where the exit can no longer be vetoed: the will-quit teardown, a new exit-only hook that app:relaunch runs before app.exit(0) (restart and profile switches share onBeforeRelaunch but quit through will-quit), and orcad's cleanup after RPC stops. The quit test now holds chat teardown and RPC stop and proves the close starts only after both settle, in either order. The orcad push-startup runtime mock gains the method the entry now calls. --- src/main/ipc/app.test.ts | 31 +++++++++ src/main/ipc/app.ts | 3 + .../notifications-subject-retirement.test.ts | 6 +- .../register-core-handlers.test.ts | 10 ++- .../register-core-handlers.ts | 6 +- src/main/orcad/orcad-entry.test.ts | 12 ++++ src/main/orcad/orcad-entry.ts | 4 +- src/main/orcad/orcad-push-startup.test.ts | 1 + ...otification-dismissal-read-failure.test.ts | 4 +- ...obile-notification-dismissal-store.test.ts | 40 ++++++++++-- .../mobile-notification-dismissal-store.ts | 31 ++++++--- ...ctured-agent-session-attention-ack.test.ts | 2 +- .../runtime-mobile-notification-controller.ts | 4 +- .../runtime-service-command-surface.ts | 4 +- ...tured-agent-session-mobile-restore.test.ts | 4 +- ...ed-agent-session-mobile-retirement.test.ts | 2 +- ...ttention-original-delivery.test-fixture.ts | 4 +- .../main-process-quit-pending-writer.test.ts | 64 ++++++++++++------- src/main/startup/main-process-quit.ts | 8 +-- src/main/startup/main-window-core-services.ts | 2 - ...ttention-host-read-retirement.unit.test.ts | 4 +- ...ctured-attention-prompt-relay.unit.test.ts | 4 +- ...attention-read-retirement.test-fixture.tsx | 2 +- ...red-attention-read-retirement.unit.test.ts | 2 +- 24 files changed, 185 insertions(+), 69 deletions(-) diff --git a/src/main/ipc/app.test.ts b/src/main/ipc/app.test.ts index c7ee26436afd..83b749350f7d 100644 --- a/src/main/ipc/app.test.ts +++ b/src/main/ipc/app.test.ts @@ -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((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 }) diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.ts index 7623c4642d49..d6447ab81095 100644 --- a/src/main/ipc/app.ts +++ b/src/main/ipc/app.ts @@ -30,6 +30,8 @@ import { readCommandStdout, readKeyboardInputSourceId } from './macos-keyboard-i type RegisterAppHandlersOptions = { onBeforeRelaunch?: () => void | Promise + /** Only for app:relaunch, whose app.exit(0) is committed and skips will-quit. */ + onBeforeRelaunchExit?: () => void | Promise } async function pickFloatingMarkdownDocument( @@ -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() diff --git a/src/main/ipc/notifications-subject-retirement.test.ts b/src/main/ipc/notifications-subject-retirement.test.ts index 3d4953e950d6..c8508fd71a37 100644 --- a/src/main/ipc/notifications-subject-retirement.test.ts +++ b/src/main/ipc/notifications-subject-retirement.test.ts @@ -232,7 +232,7 @@ describe('notifications:dismiss by acknowledged subject', () => { expect(dismissMobileNotification).toHaveBeenCalledTimes(1) expect(events.filter((event) => event.type === 'dismiss')).toHaveLength(2) } finally { - await controller.flushDismissals() + await controller.closeDismissals() rmSync(directory, { recursive: true, force: true }) } }) @@ -289,7 +289,7 @@ 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.flushDismissals() + await controller.closeDismissals() rmSync(directory, { recursive: true, force: true }) } }) @@ -342,7 +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.flushDismissals() + await controller.closeDismissals() rmSync(directory, { recursive: true, force: true }) } }) diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers/register-core-handlers.test.ts index 7620a07c8db0..97e700f466c8 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.test.ts @@ -488,7 +488,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' } @@ -540,7 +541,12 @@ describe('registerCoreHandlers', () => { openCodeUsage, museUsage }) - expect(registerAppHandlersMock).toHaveBeenCalledWith(store, { onBeforeRelaunch }) + expect(registerAppHandlersMock).toHaveBeenCalledWith(store, { + onBeforeRelaunch, + onBeforeRelaunchExit: expect.any(Function) + }) + await registerAppHandlersMock.mock.calls[0]?.[1]?.onBeforeRelaunchExit() + expect(runtime.closeNotificationDismissals).toHaveBeenCalledOnce() expect(registerCodexAccountHandlersMock).toHaveBeenCalledWith( codexAccounts, expect.any(Function) diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index 9045aee3c22c..1997a845d43d 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -144,7 +144,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: () => runtime.closeNotificationDismissals() + }) registerCliHandlers() registerPreflightHandlers() registerUsageProviderHandlers({ claudeUsage, codexUsage, openCodeUsage, museUsage }) diff --git a/src/main/orcad/orcad-entry.test.ts b/src/main/orcad/orcad-entry.test.ts index 74046415ff0c..f50660d64b9c 100644 --- a/src/main/orcad/orcad-entry.test.ts +++ b/src/main/orcad/orcad-entry.test.ts @@ -1,3 +1,5 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { flushOrcadProfileStoreForShutdown, @@ -168,3 +170,13 @@ describe('orcad profile-state shutdown', () => { expect(freezeWritesAsync).toHaveBeenCalledOnce() }) }) + +// 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) +}) diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/orcad-entry.ts index 30062c61855d..fd9e190b920e 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/orcad-entry.ts @@ -340,8 +340,8 @@ async function startOrcadRuntime( await runtime.refreshRestoredOrchestrationAuthority() await runtime.reconcileLegacyWorkerTerminals() - // Runs after RPC stops; orcad has no desktop quit barrier to save pending dismissals. - registerCleanup(() => runtime.flushNotificationDismissals()) + // 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()) diff --git a/src/main/orcad/orcad-push-startup.test.ts b/src/main/orcad/orcad-push-startup.test.ts index b1dec6a8252c..3697e0ade6c1 100644 --- a/src/main/orcad/orcad-push-startup.test.ts +++ b/src/main/orcad/orcad-push-startup.test.ts @@ -130,6 +130,7 @@ vi.mock('../runtime/orca-runtime', () => ({ async refreshRestoredOrchestrationAuthority() {} async reconcileLegacyWorkerTerminals() {} async stopLegacyWorkerTerminalRecovery() {} + async closeNotificationDismissals() {} syncWindowGraph() {} setMobilePushRegistrar( registrar: Parameters[0] diff --git a/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts b/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts index fbf21d733209..885bfcdce1fc 100644 --- a/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts +++ b/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts @@ -18,7 +18,7 @@ it('preserves dismissal history after EIO', async () => { notificationEpoch: 'epoch', notificationSeq: 1 }) - await store.flush() + await store.close() const path = join(dir, 'mobile-notification-dismissals.json') const before = readFileSync(path, 'utf8') vi.mocked(readFileSync).mockImplementationOnce(() => { @@ -31,7 +31,7 @@ it('preserves dismissal history after EIO', async () => { notificationEpoch: 'epoch', notificationSeq: 2 }) - await restarted.flush() + await restarted.close() expect(readFileSync(path, 'utf8')).toBe(before) } finally { vi.restoreAllMocks() diff --git a/src/main/runtime/mobile-notification-dismissal-store.test.ts b/src/main/runtime/mobile-notification-dismissal-store.test.ts index b541778c7874..57b6c610555a 100644 --- a/src/main/runtime/mobile-notification-dismissal-store.test.ts +++ b/src/main/runtime/mobile-notification-dismissal-store.test.ts @@ -6,7 +6,7 @@ import { MobileNotificationDismissalStore } from './mobile-notification-dismissa const paths: string[] = [] const stores: MobileNotificationDismissalStore[] = [] afterEach(async () => { - await Promise.all(stores.splice(0).map((store) => store.flush())) + await Promise.all(stores.splice(0).map((store) => store.close())) paths.splice(0).forEach((path) => rmSync(path, { recursive: true, force: true })) vi.restoreAllMocks() }) @@ -27,7 +27,7 @@ const alert = { it('reconciles an old delivered alert after desktop restart and preserves unrelated identities', async () => { const h = fixture() h.store.record({ ...alert, ...shown }) - await h.store.flush() + await h.store.close() const restarted = new MobileNotificationDismissalStore(h.path) restarted.record({ type: 'dismiss', @@ -35,7 +35,7 @@ it('reconciles an old delivered alert after desktop restart and preserves unrela notificationEpoch: 'new', notificationSeq: 1 }) - await restarted.flush() + await restarted.close() const loaded = new MobileNotificationDismissalStore(h.path) expect( loaded.reconcile([ @@ -78,7 +78,7 @@ it('names the live deliveries a subject can still retire, across a restart', asy notificationEpoch: 'e', notificationSeq: 4 }) - await h.store.flush() + await h.store.close() const restarted = new MobileNotificationDismissalStore(h.path) expect(restarted.liveDeliveries('subject:').map((entry) => entry.notificationId)).toEqual([ 'subject:prompt:a1' @@ -131,7 +131,7 @@ it('retains in-memory delivery and retirement when durable writes fail', async ( notificationSeq: 1, dismissedDelivery: shown }) - await h.store.flush() + await h.store.close() expect(warn).toHaveBeenCalledWith( '[notifications] Could not persist dismissal recovery state', expect.anything() @@ -152,11 +152,39 @@ it('coalesces a burst of records into writes of the latest entries, off the call }) } expect(existsSync(file)).toBe(false) - await h.store.flush() + await h.store.close() const saved: unknown = JSON.parse(readFileSync(file, 'utf8')) expect(Array.isArray(saved) ? saved.length : 0).toBe(20) }) +it('saves records synchronously once closed, including one made while the last async write runs', async () => { + const h = fixture() + const savedIds = () => + new MobileNotificationDismissalStore(h.path) + .liveDeliveries() + .map((entry) => entry.notificationId) + h.store.record({ ...alert, ...shown, notificationId: 'before-close' }) + const closing = h.store.close() + h.store.record({ ...alert, ...shown, notificationId: 'while-closing' }) + expect(savedIds()).toEqual(['before-close', 'while-closing']) + await closing + h.store.record({ ...alert, ...shown, notificationId: 'after-close' }) + expect(savedIds()).toEqual(['before-close', 'while-closing', 'after-close']) +}) + +it('only warns when a synchronous save after close fails', async () => { + const h = fixture() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + mkdirSync(join(h.path, 'mobile-notification-dismissals.json')) + await h.store.close() + expect(() => h.store.record({ ...alert, ...shown })).not.toThrow() + expect(warn).toHaveBeenCalledWith( + '[notifications] Could not persist dismissal recovery state', + expect.anything() + ) + expect(h.store.liveDeliveries(shown.notificationId)).toHaveLength(1) +}) + it('a targeted old delivery cannot retire a newer replacement with the same logical id', () => { const h = fixture() h.store.record({ ...alert, ...shown }) diff --git a/src/main/runtime/mobile-notification-dismissal-store.ts b/src/main/runtime/mobile-notification-dismissal-store.ts index 497a64fe2522..4c35904fd0bd 100644 --- a/src/main/runtime/mobile-notification-dismissal-store.ts +++ b/src/main/runtime/mobile-notification-dismissal-store.ts @@ -17,10 +17,15 @@ type RecordEntry = DeliveredNotificationRecord & { dismissedThrough: number; exp const LIMIT = 4096 const RETENTION_MS = 7 * 86400_000 +function warnPersistFailed(error: unknown): void { + console.warn('[notifications] Could not persist dismissal recovery state', error) +} + export class MobileNotificationDismissalStore { private readonly path: string private entries: RecordEntry[] = [] private unreadable = false + private closed = false // Why not the secure writer: this holds notification ids, not credentials, and its synchronous // Windows icacls launches froze every window on each notification (STA-9692). private readonly writer: AtomicSnapshotWriter @@ -92,18 +97,26 @@ export class MobileNotificationDismissalStore { } next = next.slice(-LIMIT) this.entries = next - if (!this.unreadable) { - // Coalesced: a burst of records costs one write of the latest entries. - this.writer - .write(() => JSON.stringify(this.entries, null, 2)) - .catch((error: unknown) => { - console.warn('[notifications] Could not persist dismissal recovery state', error) - }) + if (this.unreadable) { + return + } + const serialize = () => JSON.stringify(this.entries, null, 2) + if (this.closed) { + // Why sync: the process is exiting and would drop an async write. + try { + this.writer.writeSync(serialize) + } catch (error) { + warnPersistFailed(error) + } + return } + // Coalesced: a burst of records costs one write of the latest entries. + this.writer.write(serialize).catch(warnPersistFailed) } - /** Resolves once every recorded change has been written or has failed to write. */ - flush(): Promise { + /** Committed exits only: later records save synchronously; resolves when the pending write settles. */ + close(): Promise { + this.closed = true return this.writer.waitForPendingWrite().catch(() => {}) } diff --git a/src/main/runtime/rpc/methods/structured-agent-session-attention-ack.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-attention-ack.test.ts index 68cdf07127de..058d85261590 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-attention-ack.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-attention-ack.test.ts @@ -21,7 +21,7 @@ beforeEach(() => { }) afterEach(async () => { clearStructuredHostStub() - await hostController?.flushDismissals() + await hostController?.closeDismissals() hostController = undefined rmSync(directory, { recursive: true, force: true }) }) diff --git a/src/main/runtime/runtime-mobile-notification-controller.ts b/src/main/runtime/runtime-mobile-notification-controller.ts index ecc9629c60ef..bcbbc93419f6 100644 --- a/src/main/runtime/runtime-mobile-notification-controller.ts +++ b/src/main/runtime/runtime-mobile-notification-controller.ts @@ -71,8 +71,8 @@ export class RuntimeMobileNotificationController { this.dismissalStore = new MobileNotificationDismissalStore(userDataPath) } - flushDismissals(): Promise { - return this.dismissalStore?.flush() ?? Promise.resolve() + closeDismissals(): Promise { + return this.dismissalStore?.close() ?? Promise.resolve() } reconcileDismissedPushes( diff --git a/src/main/runtime/runtime-service-command-surface.ts b/src/main/runtime/runtime-service-command-surface.ts index 2e56f5407d92..5dad5170c2bf 100644 --- a/src/main/runtime/runtime-service-command-surface.ts +++ b/src/main/runtime/runtime-service-command-surface.ts @@ -32,7 +32,7 @@ export type RuntimeServiceCommandSurface = { dispatchMobileNotification: RuntimeMobileNotificationController['dispatch'] getMissedNotificationsSince: RuntimeMobileNotificationController['getMissedSince'] configureNotificationDismissalStore: RuntimeMobileNotificationController['configureDismissalStore'] - flushNotificationDismissals: RuntimeMobileNotificationController['flushDismissals'] + closeNotificationDismissals: RuntimeMobileNotificationController['closeDismissals'] reconcileDismissedPushes: RuntimeMobileNotificationController['reconcileDismissedPushes'] getMobileNotificationEpoch: RuntimeMobileNotificationController['getEpoch'] dismissMobileNotification: RuntimeMobileNotificationController['dismiss'] @@ -132,7 +132,7 @@ export function installRuntimeServiceCommandSurface( dispatchMobileNotification: notifications.dispatch.bind(notifications), getMissedNotificationsSince: notifications.getMissedSince.bind(notifications), configureNotificationDismissalStore: notifications.configureDismissalStore.bind(notifications), - flushNotificationDismissals: notifications.flushDismissals.bind(notifications), + closeNotificationDismissals: notifications.closeDismissals.bind(notifications), reconcileDismissedPushes: notifications.reconcileDismissedPushes.bind(notifications), getMobileNotificationEpoch: notifications.getEpoch.bind(notifications), dismissMobileNotification: notifications.dismiss.bind(notifications), diff --git a/src/main/runtime/structured-agent-session-mobile-restore.test.ts b/src/main/runtime/structured-agent-session-mobile-restore.test.ts index bf49c8c86d1f..2c1187dbc5e9 100644 --- a/src/main/runtime/structured-agent-session-mobile-restore.test.ts +++ b/src/main/runtime/structured-agent-session-mobile-restore.test.ts @@ -80,7 +80,7 @@ describe('prompt delivery after host recovery', () => { notificationSeq: delivered.notificationSeq } unsubscribe() - await original.flushDismissals() + await original.closeDismissals() const restarted = new RuntimeMobileNotificationController() restarted.configureDismissalStore(h.root) const events: MobileNotificationEvent[] = [] @@ -110,7 +110,7 @@ describe('prompt delivery after host recovery', () => { expect(events.filter((event) => event.type === 'dismiss')).toEqual([ expect.objectContaining({ dismissedDelivery: identity }) ]) - await restarted.flushDismissals() + await restarted.closeDismissals() expect( new MobileNotificationDismissalStore(h.root).liveDeliveries(identity.notificationId) ).toEqual([]) diff --git a/src/main/runtime/structured-agent-session-mobile-retirement.test.ts b/src/main/runtime/structured-agent-session-mobile-retirement.test.ts index 011972647d57..dbffca82fc63 100644 --- a/src/main/runtime/structured-agent-session-mobile-retirement.test.ts +++ b/src/main/runtime/structured-agent-session-mobile-retirement.test.ts @@ -164,7 +164,7 @@ describe('host prompt delivery and retirement', () => { Number(promptAnnounced) + (outcome === 'failure' ? 1 : 0) ) } finally { - await controller.flushDismissals() + await controller.closeDismissals() rmSync(directory, { recursive: true, force: true }) } } diff --git a/src/main/runtime/structured-attention-original-delivery.test-fixture.ts b/src/main/runtime/structured-attention-original-delivery.test-fixture.ts index 4d53c9d31074..967f34c33098 100644 --- a/src/main/runtime/structured-attention-original-delivery.test-fixture.ts +++ b/src/main/runtime/structured-attention-original-delivery.test-fixture.ts @@ -28,7 +28,7 @@ export async function captureOriginalDeliveryRetirement(directory: string): Prom cause: { kind: 'prompt', promptId: 'A' } } }) - await original.flushDismissals() + await original.closeDismissals() const restarted = new RuntimeMobileNotificationController() restarted.configureDismissalStore(directory) let event: MobileNotificationDismissEvent | undefined @@ -42,7 +42,7 @@ export async function captureOriginalDeliveryRetirement(directory: string): Prom observedCursor: { epoch: 'journal-a', sequence: 1 } }) // Why: the caller deletes the directory next; an unflushed write would recreate it. - await restarted.flushDismissals() + await restarted.closeDismissals() if (!event) { throw new Error('read did not withdraw the prompt') } diff --git a/src/main/startup/main-process-quit-pending-writer.test.ts b/src/main/startup/main-process-quit-pending-writer.test.ts index f897db7eaf7f..59e0d4a323e2 100644 --- a/src/main/startup/main-process-quit-pending-writer.test.ts +++ b/src/main/startup/main-process-quit-pending-writer.test.ts @@ -61,7 +61,7 @@ afterEach(() => { async function startQuit( flushFinalOrThrowAsync: () => Promise, - runtime?: Record + services: Record = {} ) { vi.resetModules() vi.useFakeTimers() @@ -77,7 +77,7 @@ async function startQuit( watcherShutdownDone: true, store, profileStateAdmission, - runtime + ...services } vi.doMock('electron', () => ({ app })) vi.doMock('./main-process-state', () => ({ mainProcessState: state })) @@ -124,23 +124,43 @@ it('stops the hook server without clearing the status store the chat teardown re expect(stopAgentHookServer).toHaveBeenCalledWith({ keepStatus: true }) }) -it('holds quit for the notification dismissal flush, started after chat teardown settles', async () => { - const flushNotificationDismissals = vi.fn(() => new Promise(() => {})) - const { app } = await startQuit(async () => {}, { - getOffscreenBrowserBackend: () => null, - getAgentBrowserBridge: () => null, - getEmulatorBridge: () => null, - disposeSkillUploadSessions: settled(), - getRuntimeId: () => undefined, - flushNotificationDismissals - }) - expect(stopStructuredAgentSessionRuntime).toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(0) - expect(flushNotificationDismissals).toHaveBeenCalledOnce() - expect(app.quit).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(WILL_QUIT_TEARDOWN_DEADLINE_MS) - expect(console.warn).toHaveBeenCalledWith('[shutdown] Quit teardown deadline reached', { - pendingTeardowns: ['notification-dismissals'] - }) - expect(app.quit).toHaveBeenCalledOnce() -}) +it.each([ + ['chat teardown', 'RPC stop'], + ['RPC stop', 'chat teardown'] +] as const)( + 'closes notification dismissals only once %s and then %s settle', + async (first, second) => { + const sessionTeardown = Promise.withResolvers() + const rpcStop = Promise.withResolvers() + const release = { 'chat teardown': sessionTeardown.resolve, 'RPC stop': rpcStop.resolve } + stopStructuredAgentSessionRuntime.mockClear() + stopStructuredAgentSessionRuntime.mockImplementationOnce(() => sessionTeardown.promise) + const closeNotificationDismissals = vi.fn(() => new Promise(() => {})) + const { app } = await startQuit(async () => {}, { + runtime: { + getOffscreenBrowserBackend: () => null, + getAgentBrowserBridge: () => null, + getEmulatorBridge: () => null, + disposeSkillUploadSessions: settled(), + getRuntimeId: () => undefined, + closeNotificationDismissals + }, + runtimeRpc: { setMobileRelayPairingProvider: idle(), stop: vi.fn(() => rpcStop.promise) } + }) + expect(stopStructuredAgentSessionRuntime).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(0) + expect(closeNotificationDismissals).not.toHaveBeenCalled() + release[first]() + await vi.advanceTimersByTimeAsync(0) + expect(closeNotificationDismissals).not.toHaveBeenCalled() + release[second]() + await vi.advanceTimersByTimeAsync(0) + expect(closeNotificationDismissals).toHaveBeenCalledOnce() + expect(app.quit).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(WILL_QUIT_TEARDOWN_DEADLINE_MS) + expect(console.warn).toHaveBeenCalledWith('[shutdown] Quit teardown deadline reached', { + pendingTeardowns: ['notification-dismissals'] + }) + expect(app.quit).toHaveBeenCalledOnce() + } +) diff --git a/src/main/startup/main-process-quit.ts b/src/main/startup/main-process-quit.ts index 1e6aa481a32f..89a4caf9728a 100644 --- a/src/main/startup/main-process-quit.ts +++ b/src/main/startup/main-process-quit.ts @@ -249,11 +249,11 @@ function installWillQuitHandler(): void { }) .catch((error) => console.error('[runtime] Failed to stop local RPC transport:', error)) : Promise.resolve() - // After session and RPC teardown, which can still retire notifications. - const notificationDismissalFlush = Promise.allSettled([ + // After session and RPC teardown, which can still retire notifications; will-quit is past every veto. + const notificationDismissalClose = Promise.allSettled([ structuredAgentSessionShutdown, rpcStopAndClear - ]).then(() => state.runtime?.flushNotificationDismissals()) + ]).then(() => state.runtime?.closeNotificationDismissals()) // Why: allSettled (not all) keeps fail-open — a daemon-disconnect rejection still quits instead of hanging. // Why: telemetry flush folds in before app.quit() (bounded 2s); catch defensively so a flush failure can't cancel the quit chain. // Why: normal quits keep the detached daemon for warm reattach, but a dead dev parent leaves the temp/dev profile ownerless. @@ -279,7 +279,7 @@ function installWillQuitHandler(): void { { name: 'codex-backfill-recovery', promise: codexBackfillRecoveryShutdown }, { name: 'structured-agent-session', promise: structuredAgentSessionShutdown }, { name: 'usage-cache', promise: usageCacheFlush }, - { name: 'notification-dismissals', promise: notificationDismissalFlush }, + { name: 'notification-dismissals', promise: notificationDismissalClose }, { name: 'stats', promise: statsFlush }, { name: 'state', promise: storeFlush } ]) diff --git a/src/main/startup/main-window-core-services.ts b/src/main/startup/main-window-core-services.ts index c053decca5b9..7185b743e89e 100644 --- a/src/main/startup/main-window-core-services.ts +++ b/src/main/startup/main-window-core-services.ts @@ -94,8 +94,6 @@ export function attachMainWindowCoreServices( state.isQuitting = true state.desktopRelayService?.fenceAndCloseNow() await preserveAgentAuthBeforeRestart({ codexRuntimeHome, store }) - // Why: renderer relaunch exits via app.exit(0), which skips the quit pipeline's flush. - await runtime.flushNotificationDismissals() }, onOrcaProfileAuthMutation: () => { // Why: a provider whose launch-time install failed is installed by the next auth change. diff --git a/tests/e2e/structured-attention-host-read-retirement.unit.test.ts b/tests/e2e/structured-attention-host-read-retirement.unit.test.ts index b98807ef7f51..dd2909e23305 100644 --- a/tests/e2e/structured-attention-host-read-retirement.unit.test.ts +++ b/tests/e2e/structured-attention-host-read-retirement.unit.test.ts @@ -139,7 +139,7 @@ beforeEach(() => { }) afterEach(async () => { clearStructuredHostStub() - await Promise.all(controllers.splice(0).map((controller) => controller.flushDismissals())) + await Promise.all(controllers.splice(0).map((controller) => controller.closeDismissals())) rmSync(directory, { recursive: true, force: true }) }) @@ -220,7 +220,7 @@ it('a restart sends the original delivery fence in the existing native gateway f if (!original) { throw new Error('prompt not delivered') } - await h.controller.flushDismissals() + await h.controller.closeDismissals() const restarted = storeController(directory) const gateway = createHarness({ devices: [{ deviceId: 'phone', pushRegistration: registration() }] diff --git a/tests/e2e/structured-attention-prompt-relay.unit.test.ts b/tests/e2e/structured-attention-prompt-relay.unit.test.ts index 304824627db2..5b174ba48501 100644 --- a/tests/e2e/structured-attention-prompt-relay.unit.test.ts +++ b/tests/e2e/structured-attention-prompt-relay.unit.test.ts @@ -156,7 +156,7 @@ describe('Delayed remote prompt delivery', () => { }) }, liveDeliveries: async () => { - await relay.flushDismissals() + await relay.closeDismissals() return new MobileNotificationDismissalStore(relayDirectory).liveDeliveries() } } @@ -482,7 +482,7 @@ describe('Remote prompt settlement', () => { await waitFor(() => expect(fixture.status).toBeTypeOf('function')) act(() => publishStatus()) const live = async (kind: 'prompt' | 'completion') => { - await relay.flushDismissals() + await relay.closeDismissals() return new MobileNotificationDismissalStore(relayDirectory) .liveDeliveries() .filter((entry) => entry.structuredOrigin?.cause.kind === kind) diff --git a/tests/e2e/structured-attention-read-retirement.test-fixture.tsx b/tests/e2e/structured-attention-read-retirement.test-fixture.tsx index d56e43dd6c92..1479bb8b9f82 100644 --- a/tests/e2e/structured-attention-read-retirement.test-fixture.tsx +++ b/tests/e2e/structured-attention-read-retirement.test-fixture.tsx @@ -346,6 +346,6 @@ afterEach(async () => { resetStructuredAgentSessionStatusFeedsForTests() vi.unstubAllGlobals() vi.restoreAllMocks() - await fixture.controller.flushDismissals() + await fixture.controller.closeDismissals() rmSync(fixture.directory, { recursive: true, force: true }) }) diff --git a/tests/e2e/structured-attention-read-retirement.unit.test.ts b/tests/e2e/structured-attention-read-retirement.unit.test.ts index 6cfe82f7adf4..9479588c510e 100644 --- a/tests/e2e/structured-attention-read-retirement.unit.test.ts +++ b/tests/e2e/structured-attention-read-retirement.unit.test.ts @@ -584,7 +584,7 @@ describe('Accepted structured history read retirement', () => { transport.dismiss.mock.calls.filter(([, , reads]) => Array.isArray(reads)) ).toHaveLength(2) } finally { - await relay.flushDismissals() + await relay.closeDismissals() rmSync(relayDirectory, { recursive: true, force: true }) } }) From b0118af23745b52f46cb7edfe78a48bc86728d52 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 11 Oct 2026 21:22:49 -0700 Subject: [PATCH 6/7] fix(notifications): bound the dismissal close before a renderer relaunch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit app:relaunch waited on the dismissal store's close with no limit, so a stalled userData disk left Restart stuck on "Restarting…" with a half-quit app saving synchronously. The close now races a 2 s cap through the existing settleWithinMs helper, the same cap the restart path's auth preservation uses, and logs when it gives up. --- .../register-core-handlers.test.ts | 31 +++++++++++++++++-- .../register-core-handlers.ts | 17 +++++++++- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers/register-core-handlers.test.ts index 97e700f466c8..3bebbb5f7a6c 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.test.ts @@ -413,7 +413,13 @@ import { registerCoreHandlers } from './register-core-handlers' let registeredAiVaultOptions: { ensureStructuredSessionOwnership: () => Promise } -let registeredRuntime: { ensureStructuredAgentSessionHost: ReturnType } | undefined +let registeredRuntime: + | { + ensureStructuredAgentSessionHost: ReturnType + closeNotificationDismissals: ReturnType + } + | undefined +let registeredRelaunchExit: (() => Promise) | undefined describe('registerCoreHandlers', () => { beforeEach(() => { @@ -545,7 +551,8 @@ describe('registerCoreHandlers', () => { onBeforeRelaunch, onBeforeRelaunchExit: expect.any(Function) }) - await registerAppHandlersMock.mock.calls[0]?.[1]?.onBeforeRelaunchExit() + registeredRelaunchExit = registerAppHandlersMock.mock.calls[0]?.[1]?.onBeforeRelaunchExit + await registeredRelaunchExit?.() expect(runtime.closeNotificationDismissals).toHaveBeenCalledOnce() expect(registerCodexAccountHandlersMock).toHaveBeenCalledWith( codexAccounts, @@ -700,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. diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index 1997a845d43d..e4e89005d379 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -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 { + 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 @@ -147,7 +162,7 @@ export function registerCoreHandlers( registerAppHandlers(store, { onBeforeRelaunch: lifecycleOptions.onBeforeRelaunch, // Why here, not onBeforeRelaunch: restart and profile switches quit through will-quit, which closes it. - onBeforeRelaunchExit: () => runtime.closeNotificationDismissals() + onBeforeRelaunchExit: () => closeNotificationDismissalsBeforeRelaunch(runtime) }) registerCliHandlers() registerPreflightHandlers() From 5e4bbc11dbd06d6e0039a26c7db79891a6780117 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 11 Oct 2026 21:22:51 -0700 Subject: [PATCH 7/7] test(notifications): keep async dismissal writes under test between reads Mid-test disk reads used closeDismissals() as a barrier, which switched every later record to the exit-only synchronous path. The store gains a non-closing flush() (close() = mark closed + flush), exposed on the controller as flushDismissals for tests; mid-test barriers use it, and close stays only where a test simulates an exit or teardown. Also notes why the writer's pendingWrite assignment is safe, renames a store test to what it covers, and groups the orcad cleanup-order test under a describe. --- src/main/orcad/orcad-entry.test.ts | 18 ++++++++++-------- src/main/persistence/atomic-snapshot-writer.ts | 1 + ...notification-dismissal-read-failure.test.ts | 2 +- ...mobile-notification-dismissal-store.test.ts | 6 +++--- .../mobile-notification-dismissal-store.ts | 7 ++++++- .../runtime-mobile-notification-controller.ts | 5 +++++ ...ctured-agent-session-mobile-restore.test.ts | 2 +- ...uctured-attention-prompt-relay.unit.test.ts | 4 ++-- 8 files changed, 29 insertions(+), 16 deletions(-) diff --git a/src/main/orcad/orcad-entry.test.ts b/src/main/orcad/orcad-entry.test.ts index f50660d64b9c..efbffc63f3cb 100644 --- a/src/main/orcad/orcad-entry.test.ts +++ b/src/main/orcad/orcad-entry.test.ts @@ -171,12 +171,14 @@ describe('orcad profile-state shutdown', () => { }) }) -// 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) +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) + }) }) diff --git a/src/main/persistence/atomic-snapshot-writer.ts b/src/main/persistence/atomic-snapshot-writer.ts index 145d77eb2dcd..bb69afd76e37 100644 --- a/src/main/persistence/atomic-snapshot-writer.ts +++ b/src/main/persistence/atomic-snapshot-writer.ts @@ -44,6 +44,7 @@ export class AtomicSnapshotWriter { } this.writeRequested = true this.pendingSerialize = serialize + // Why safe: drainWrites awaits before its finally can clear pendingWrite, so this assignment lands first. this.pendingWrite ??= this.drainWrites() return this.pendingWrite } diff --git a/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts b/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts index 885bfcdce1fc..4461bf267c82 100644 --- a/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts +++ b/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts @@ -31,7 +31,7 @@ it('preserves dismissal history after EIO', async () => { notificationEpoch: 'epoch', notificationSeq: 2 }) - await restarted.close() + await restarted.flush() expect(readFileSync(path, 'utf8')).toBe(before) } finally { vi.restoreAllMocks() diff --git a/src/main/runtime/mobile-notification-dismissal-store.test.ts b/src/main/runtime/mobile-notification-dismissal-store.test.ts index 57b6c610555a..7ab9ebda82d6 100644 --- a/src/main/runtime/mobile-notification-dismissal-store.test.ts +++ b/src/main/runtime/mobile-notification-dismissal-store.test.ts @@ -131,7 +131,7 @@ it('retains in-memory delivery and retirement when durable writes fail', async ( notificationSeq: 1, dismissedDelivery: shown }) - await h.store.close() + await h.store.flush() expect(warn).toHaveBeenCalledWith( '[notifications] Could not persist dismissal recovery state', expect.anything() @@ -152,12 +152,12 @@ it('coalesces a burst of records into writes of the latest entries, off the call }) } expect(existsSync(file)).toBe(false) - await h.store.close() + await h.store.flush() const saved: unknown = JSON.parse(readFileSync(file, 'utf8')) expect(Array.isArray(saved) ? saved.length : 0).toBe(20) }) -it('saves records synchronously once closed, including one made while the last async write runs', async () => { +it('saves records synchronously from the moment close() is called, ahead of the queued async write', async () => { const h = fixture() const savedIds = () => new MobileNotificationDismissalStore(h.path) diff --git a/src/main/runtime/mobile-notification-dismissal-store.ts b/src/main/runtime/mobile-notification-dismissal-store.ts index 4c35904fd0bd..4a111a3dff2f 100644 --- a/src/main/runtime/mobile-notification-dismissal-store.ts +++ b/src/main/runtime/mobile-notification-dismissal-store.ts @@ -114,10 +114,15 @@ export class MobileNotificationDismissalStore { this.writer.write(serialize).catch(warnPersistFailed) } + /** Resolves once the pending write settles; its failure is already warned. */ + flush(): Promise { + return this.writer.waitForPendingWrite().catch(() => {}) + } + /** Committed exits only: later records save synchronously; resolves when the pending write settles. */ close(): Promise { this.closed = true - return this.writer.waitForPendingWrite().catch(() => {}) + return this.flush() } liveDeliveries(prefix = ''): DeliveredNotificationRecord[] { diff --git a/src/main/runtime/runtime-mobile-notification-controller.ts b/src/main/runtime/runtime-mobile-notification-controller.ts index bcbbc93419f6..00de771cc001 100644 --- a/src/main/runtime/runtime-mobile-notification-controller.ts +++ b/src/main/runtime/runtime-mobile-notification-controller.ts @@ -71,6 +71,11 @@ export class RuntimeMobileNotificationController { this.dismissalStore = new MobileNotificationDismissalStore(userDataPath) } + /** Waits for the pending dismissal write without closing the store. */ + flushDismissals(): Promise { + return this.dismissalStore?.flush() ?? Promise.resolve() + } + closeDismissals(): Promise { return this.dismissalStore?.close() ?? Promise.resolve() } diff --git a/src/main/runtime/structured-agent-session-mobile-restore.test.ts b/src/main/runtime/structured-agent-session-mobile-restore.test.ts index 2c1187dbc5e9..e6f298c2d79e 100644 --- a/src/main/runtime/structured-agent-session-mobile-restore.test.ts +++ b/src/main/runtime/structured-agent-session-mobile-restore.test.ts @@ -110,7 +110,7 @@ describe('prompt delivery after host recovery', () => { expect(events.filter((event) => event.type === 'dismiss')).toEqual([ expect.objectContaining({ dismissedDelivery: identity }) ]) - await restarted.closeDismissals() + await restarted.flushDismissals() expect( new MobileNotificationDismissalStore(h.root).liveDeliveries(identity.notificationId) ).toEqual([]) diff --git a/tests/e2e/structured-attention-prompt-relay.unit.test.ts b/tests/e2e/structured-attention-prompt-relay.unit.test.ts index 5b174ba48501..304824627db2 100644 --- a/tests/e2e/structured-attention-prompt-relay.unit.test.ts +++ b/tests/e2e/structured-attention-prompt-relay.unit.test.ts @@ -156,7 +156,7 @@ describe('Delayed remote prompt delivery', () => { }) }, liveDeliveries: async () => { - await relay.closeDismissals() + await relay.flushDismissals() return new MobileNotificationDismissalStore(relayDirectory).liveDeliveries() } } @@ -482,7 +482,7 @@ describe('Remote prompt settlement', () => { await waitFor(() => expect(fixture.status).toBeTypeOf('function')) act(() => publishStatus()) const live = async (kind: 'prompt' | 'completion') => { - await relay.closeDismissals() + await relay.flushDismissals() return new MobileNotificationDismissalStore(relayDirectory) .liveDeliveries() .filter((entry) => entry.structuredOrigin?.cause.kind === kind)