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/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 99d8438c6848..c8508fd71a37 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.closeDismissals() rmSync(directory, { recursive: true, force: true }) } }) it('the click-time read a Mark read sends closes and retires every alert it covers', async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-explicit-read-')) + const controller = new RuntimeMobileNotificationController() try { - const controller = new RuntimeMobileNotificationController() controller.configureDismissalStore(directory) const events: MobileNotificationEvent[] = [] controller.onDispatched((event) => events.push(event)) @@ -288,14 +289,15 @@ describe('notifications:dismiss by acknowledged subject', () => { events.filter((event) => event.type === 'dismiss').map((event) => event.notificationId) ).toEqual(['agent-attention:click-A', 'agent-attention:click-B']) } finally { + await controller.closeDismissals() rmSync(directory, { recursive: true, force: true }) } }) it('settles only the relayed prompt alerts of a session its host reports none pending for', async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-relay-settle-')) + const controller = new RuntimeMobileNotificationController() try { - const controller = new RuntimeMobileNotificationController() controller.configureDismissalStore(directory) const events: MobileNotificationEvent[] = [] controller.onDispatched((event) => events.push(event)) @@ -340,6 +342,7 @@ describe('notifications:dismiss by acknowledged subject', () => { events.filter((event) => event.type === 'dismiss').map((event) => event.notificationId) ).toEqual([key('prompt:A')]) } finally { + await controller.closeDismissals() rmSync(directory, { recursive: true, force: true }) } }) 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..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(() => { @@ -488,7 +494,8 @@ describe('registerCoreHandlers', () => { const runtime = { marker: 'runtime', getAgentBrowserBridge: () => null, - ensureStructuredAgentSessionHost: vi.fn() + ensureStructuredAgentSessionHost: vi.fn(), + closeNotificationDismissals: vi.fn(async () => {}) } const stats = { marker: 'stats' } const claudeUsage = { marker: 'claudeUsage' } @@ -540,7 +547,13 @@ describe('registerCoreHandlers', () => { openCodeUsage, museUsage }) - expect(registerAppHandlersMock).toHaveBeenCalledWith(store, { onBeforeRelaunch }) + expect(registerAppHandlersMock).toHaveBeenCalledWith(store, { + onBeforeRelaunch, + onBeforeRelaunchExit: expect.any(Function) + }) + registeredRelaunchExit = registerAppHandlersMock.mock.calls[0]?.[1]?.onBeforeRelaunchExit + await registeredRelaunchExit?.() + expect(runtime.closeNotificationDismissals).toHaveBeenCalledOnce() expect(registerCodexAccountHandlersMock).toHaveBeenCalledWith( codexAccounts, expect.any(Function) @@ -694,6 +707,26 @@ describe('registerCoreHandlers', () => { } }) + it('lets relaunch exit after 2 s when the dismissal close never settles', async () => { + vi.useFakeTimers() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + registeredRuntime?.closeNotificationDismissals.mockReturnValueOnce(new Promise(() => {})) + let exited = false + void registeredRelaunchExit?.().then(() => { + exited = true + }) + await vi.advanceTimersByTimeAsync(1_999) + expect(exited).toBe(false) + await vi.advanceTimersByTimeAsync(1) + expect(exited).toBe(true) + expect(warn).toHaveBeenCalledOnce() + } finally { + warn.mockRestore() + vi.useRealTimers() + } + }) + it('only registers IPC handlers once but always updates web contents id', () => { // The first test already called registerCoreHandlers, so the module-level // guard is now set. beforeEach reset all mocks, so call counts are 0. 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..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 @@ -144,7 +159,11 @@ export function registerCoreHandlers( } registered = true - registerAppHandlers(store, { onBeforeRelaunch: lifecycleOptions.onBeforeRelaunch }) + registerAppHandlers(store, { + onBeforeRelaunch: lifecycleOptions.onBeforeRelaunch, + // Why here, not onBeforeRelaunch: restart and profile switches quit through will-quit, which closes it. + onBeforeRelaunchExit: () => closeNotificationDismissalsBeforeRelaunch(runtime) + }) registerCliHandlers() registerPreflightHandlers() registerUsageProviderHandlers({ claudeUsage, codexUsage, openCodeUsage, museUsage }) diff --git a/src/main/orcad/orcad-entry.test.ts b/src/main/orcad/orcad-entry.test.ts index 74046415ff0c..efbffc63f3cb 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,15 @@ describe('orcad profile-state shutdown', () => { expect(freezeWritesAsync).toHaveBeenCalledOnce() }) }) + +describe('orcad runtime cleanup order', () => { + // Booting orcad here would need its whole runtime; the wiring is pinned by the entry point's text. + it('closes notification dismissals in a cleanup that runs after RPC stops', () => { + const entry = readFileSync(join(import.meta.dirname, 'orcad-entry.ts'), 'utf8') + const close = entry.indexOf('registerCleanup(() => runtime.closeNotificationDismissals())') + const rpcStop = entry.indexOf('registerCleanup(() => rpc.stop())') + expect(close).toBeGreaterThan(-1) + // Cleanups run in reverse registration order. + expect(close).toBeLessThan(rpcStop) + }) +}) diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/orcad-entry.ts index 307e1cb70b44..fd9e190b920e 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 (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/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..bb69afd76e37 100644 --- a/src/main/persistence/atomic-snapshot-writer.ts +++ b/src/main/persistence/atomic-snapshot-writer.ts @@ -44,17 +44,9 @@ export class AtomicSnapshotWriter { } this.writeRequested = true this.pendingSerialize = serialize - if (this.pendingWrite) { - return this.pendingWrite - } - const run = this.drainWrites() - const tracked = run.finally(() => { - if (this.pendingWrite === tracked) { - this.pendingWrite = null - } - }) - this.pendingWrite = tracked - return tracked + // Why safe: drainWrites awaits before its finally can clear pendingWrite, so this assignment lands first. + this.pendingWrite ??= this.drainWrites() + return this.pendingWrite } writeSync(serialize: () => string): void { @@ -155,22 +147,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 } } 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..4461bf267c82 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.close() 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..7ab9ebda82d6 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.close())) 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.close() 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.close() 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.close() const restarted = new MobileNotificationDismissalStore(h.path) expect(restarted.liveDeliveries('subject:').map((entry) => entry.notificationId)).toEqual([ 'subject:prompt:a1' @@ -111,24 +118,73 @@ 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('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) + .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 9936b005886d..4a111a3dff2f 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,23 @@ 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 + +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 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) @@ -96,9 +97,32 @@ export class MobileNotificationDismissalStore { } next = next.slice(-LIMIT) this.entries = next - if (!this.unreadable) { - writeSecureJsonFile(this.path, next) + 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 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.flush() } liveDeliveries(prefix = ''): DeliveredNotificationRecord[] { 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..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 @@ -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?.closeDismissals() + 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/runtime-mobile-notification-controller.ts b/src/main/runtime/runtime-mobile-notification-controller.ts index 87d6adddd1dd..00de771cc001 100644 --- a/src/main/runtime/runtime-mobile-notification-controller.ts +++ b/src/main/runtime/runtime-mobile-notification-controller.ts @@ -71,6 +71,15 @@ 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() + } + 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..5dad5170c2bf 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'] + closeNotificationDismissals: RuntimeMobileNotificationController['closeDismissals'] 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), + 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 0e3033f000b2..e6f298c2d79e 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.closeDismissals() 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-agent-session-mobile-retirement.test.ts b/src/main/runtime/structured-agent-session-mobile-retirement.test.ts index 25c17a8a8b6e..dbffca82fc63 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.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 d142a3a6acbc..967f34c33098 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.closeDismissals() const restarted = new RuntimeMobileNotificationController() restarted.configureDismissalStore(directory) let event: MobileNotificationDismissEvent | undefined @@ -40,6 +41,8 @@ export function captureOriginalDeliveryRetirement(directory: string): { sessionId: 'session-a', observedCursor: { epoch: 'journal-a', sequence: 1 } }) + // Why: the caller deletes the directory next; an unflushed write would recreate it. + 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 c75d2191237f..59e0d4a323e2 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, + services: 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, + ...services + } vi.doMock('electron', () => ({ app })) vi.doMock('./main-process-state', () => ({ mainProcessState: state })) for (const [moduleName, exports] of Object.entries(dependencies)) { @@ -113,3 +123,44 @@ it('stops the hook server without clearing the status store the chat teardown re await startQuit(async () => {}) expect(stopAgentHookServer).toHaveBeenCalledWith({ keepStatus: true }) }) + +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 d96163ec3771..89a4caf9728a 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; will-quit is past every veto. + const notificationDismissalClose = Promise.allSettled([ + structuredAgentSessionShutdown, + rpcStopAndClear + ]).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. @@ -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: notificationDismissalClose }, { name: 'stats', promise: statsFlush }, { name: 'state', promise: storeFlush } ]) 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..dd2909e23305 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.closeDismissals())) rmSync(directory, { recursive: true, force: true }) }) @@ -213,8 +220,8 @@ it('a restart sends the original delivery fence in the existing native gateway f if (!original) { throw new Error('prompt not delivered') } - const restarted = new RuntimeMobileNotificationController() - restarted.configureDismissalStore(directory) + 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 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() }) }) diff --git a/tests/e2e/structured-attention-read-retirement.test-fixture.tsx b/tests/e2e/structured-attention-read-retirement.test-fixture.tsx index 13335a973f3a..1479bb8b9f82 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.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 1acdbebebb21..9479588c510e 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.closeDismissals() rmSync(relayDirectory, { recursive: true, force: true }) } })