Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): keep iOS drafts when WebKit aborts IndexedDB writes (#8209)
teo6482e20e427f
diff --git a/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts b/apps/web/src/features/email-compose/primitives/compose-persistence.test.tsindex 8ea87fa832..218beddb11 100644--- a/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts+++ b/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts@@ -1187,7 +1187,7 @@ function localSnapshot(}it.each(['standalone', 'reply'] as const)(- 'keeps one %s local-save warning until recovery or disposal',+ 'keeps one %s local-save warning until recovery and briefly warns when the write on close fails',async (surface) => {const context = createComposeContext();let diskFailed = true;@@ -1229,7 +1229,50 @@ it.each(['standalone', 'reply'] as const)(} finally {root.dispose();}+ await vi.advanceTimersByTimeAsync(0);+ const closing = vi.mocked(context.drafts.saveLocalDraft!).mock.lastCall;+ expect(decodeBase64Utf8(closing?.[0].draft.body_html ?? '')).toContain(+ 'Another failure'+ );expect(context.notices.feedback.dismiss).toHaveBeenLastCalledWith(8);+ expect(context.notices.feedback.failure).toHaveBeenCalledTimes(3);+ expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(+ 'Draft could not be saved on this device',+ { subtext: 'Error: Disk full', persistent: false }+ );+ }+);++it.each(['standalone', 'reply'] as const)(+ 'writes the unsaved %s edit once more on close',+ async (surface) => {+ const context = createComposeContext();+ let diskFailed = true;+ context.drafts.saveLocalDraft = vi.fn(async (input) => {+ if (diskFailed) throw new Error('Draft storage transaction aborted');+ return localSnapshot(input);+ });+ vi.mocked(context.notices.feedback.failure).mockReturnValueOnce(7);+ const root =+ surface === 'standalone'+ ? mountEmailComposer(context)+ : mountReplyComposer(context);+ try {+ root.edit('Typed before backgrounding');+ await vi.advanceTimersByTimeAsync(600);+ expect(context.drafts.saveDraft).not.toHaveBeenCalled();+ } finally {+ diskFailed = false;+ root.dispose();+ }+ await vi.advanceTimersByTimeAsync(1000);+ const closing = vi.mocked(context.drafts.saveLocalDraft!).mock.lastCall;+ expect(decodeBase64Utf8(closing?.[0].draft.body_html ?? '')).toContain(+ 'Typed before backgrounding'+ );+ expect(context.notices.feedback.dismiss).toHaveBeenCalledExactlyOnceWith(7);+ expect(context.notices.feedback.failure).toHaveBeenCalledOnce();+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();});diff --git a/apps/web/src/features/email-compose/primitives/draft-autosave.test.ts b/apps/web/src/features/email-compose/primitives/draft-autosave.test.tsindex 07c6871325..f3cb96a076 100644--- a/apps/web/src/features/email-compose/primitives/draft-autosave.test.ts+++ b/apps/web/src/features/email-compose/primitives/draft-autosave.test.ts@@ -135,6 +135,129 @@ it('coalesces local snapshots behind a slow write and reports durability only afautosave.cancel();});+it('persists a debounced edit as soon as visibility changes', async () => {+ vi.useFakeTimers();+ const persist = vi.fn(async (_snapshot: string) => {});+ const autosave = createRoot((dispose) => {+ disposers.push(dispose);+ return createDraftAutosave({+ capture: () => 'typed before switching apps',+ persist,+ saveLocalSnapshot: async () => {},+ paused: () => false,+ });+ });+ autosave.schedule();+ document.dispatchEvent(new Event('visibilitychange'));+ await autosave.settled();+ expect(persist).toHaveBeenCalledExactlyOnceWith(+ 'typed before switching apps'+ );+ await vi.advanceTimersByTimeAsync(1000);+ expect(persist).toHaveBeenCalledOnce();+});++it('retries a failed local write with the live draft when visibility changes', async () => {+ let body = 'aborted in background';+ const persist = vi.fn(async (_snapshot: string) => {});+ const local = vi+ .fn<(snapshot: string) => Promise<void>>()+ .mockRejectedValueOnce(new Error('Draft storage transaction aborted'))+ .mockResolvedValue(undefined);+ const autosave = createRoot((dispose) => {+ disposers.push(dispose);+ return createDraftAutosave({+ capture: () => body,+ persist,+ paused: () => false,+ saveLocalSnapshot: local,+ });+ });+ await expect(autosave.save()).rejects.toThrow('transaction aborted');+ expect(autosave.localSaveState()).toBe('failed');+ body = 'latest';+ document.dispatchEvent(new Event('visibilitychange'));+ await autosave.settled();+ expect(local).toHaveBeenLastCalledWith('latest');+ expect(persist).toHaveBeenCalledExactlyOnceWith('latest');+ expect(autosave.localSaveState()).toBe('saved');+ document.dispatchEvent(new Event('visibilitychange'));+ await autosave.settled();+ expect(local).toHaveBeenCalledTimes(2);+});++it('does not flush on visibility changes while persistence is paused', async () => {+ const persist = vi.fn(async () => {});+ const local = vi.fn(async () => {});+ let paused = false;+ const autosave = createRoot((dispose) => {+ disposers.push(dispose);+ return createDraftAutosave({+ capture: () => 'draft',+ persist,+ paused: () => paused,+ saveLocalSnapshot: local,+ });+ });+ autosave.schedule();+ await autosave.flushLocal();+ paused = true;+ document.dispatchEvent(new Event('visibilitychange'));+ await autosave.settled();+ expect(local).toHaveBeenCalledOnce();+ expect(persist).not.toHaveBeenCalled();+});++it('writes a failed local snapshot again when the editor closes', async () => {+ const persist = vi.fn(async (_snapshot: string) => {});+ const local = vi+ .fn<(snapshot: string) => Promise<void>>()+ .mockRejectedValueOnce(new Error('Draft storage transaction aborted'))+ .mockResolvedValue(undefined);+ let dispose = () => {};+ const autosave = createRoot((cleanup) => {+ dispose = cleanup;+ return createDraftAutosave({+ capture: () => 'unsaved edit',+ persist,+ paused: () => false,+ saveLocalSnapshot: local,+ });+ });+ await expect(autosave.save()).rejects.toThrow('transaction aborted');+ dispose();+ await autosave.settled();+ expect(local).toHaveBeenCalledTimes(2);+ expect(persist).toHaveBeenCalledExactlyOnceWith('unsaved edit');+});++it('drops a failed local snapshot when saving is cancelled', async () => {+ const persist = vi.fn(async (_snapshot: string) => {});+ const local = vi+ .fn<(snapshot: string) => Promise<void>>()+ .mockRejectedValueOnce(new Error('Draft storage transaction aborted'))+ .mockResolvedValue(undefined);+ let dispose = () => {};+ const autosave = createRoot((cleanup) => {+ dispose = cleanup;+ return createDraftAutosave({+ capture: () => 'discarded edit',+ persist,+ paused: () => false,+ saveLocalSnapshot: local,+ });+ });+ await expect(autosave.save()).rejects.toThrow('transaction aborted');+ // Discard, send, and terminal resets cancel before the composer closes.+ autosave.cancel();+ document.dispatchEvent(new Event('visibilitychange'));+ dispose();+ // Nothing new was queued behind the failed save.+ await expect(autosave.settled()).rejects.toThrow('transaction aborted');+ expect(local).toHaveBeenCalledOnce();+ expect(persist).not.toHaveBeenCalled();+});+it('does not enqueue a save after a disk failure and lets the next local save recover', async () => {const persist = vi.fn(async () => {});const local = vidiff --git a/apps/web/src/features/email-compose/primitives/draft-autosave.ts b/apps/web/src/features/email-compose/primitives/draft-autosave.tsindex 63d1e852b6..9c4e485166 100644--- a/apps/web/src/features/email-compose/primitives/draft-autosave.ts+++ b/apps/web/src/features/email-compose/primitives/draft-autosave.ts@@ -13,6 +13,7 @@ export function createDraftAutosave<Snapshot, Result>(options: {onLocalSaved?(): void;}) {let pending: { snapshot: Snapshot } | undefined;+ let failed: { snapshot: Snapshot } | undefined;let queue: Promise<Result | undefined> = Promise.resolve(undefined);let localWrites: Promise<void> = Promise.resolve();let newestSnapshot = 0;@@ -36,11 +37,15 @@ export function createDraftAutosave<Snapshot, Result>(options: {try {await options.saveLocalSnapshot?.(snapshot);if (revision === newestSnapshot) {+ failed = undefined;setLocalSaveState('saved');options.onLocalSaved?.();}} catch (error) {- if (revision === newestSnapshot) setLocalSaveState('failed');+ if (revision === newestSnapshot) {+ failed = { snapshot };+ setLocalSaveState('failed');+ }options.onLocalError?.(error);throw error;}@@ -52,6 +57,7 @@ export function createDraftAutosave<Snapshot, Result>(options: {const cancel = () => {scheduled.clear();pending = undefined;+ failed = undefined;};const enqueue = (snapshot: Snapshot, local: Promise<void>) => {const write = async () => {@@ -69,15 +75,27 @@ export function createDraftAutosave<Snapshot, Result>(options: {if (options.paused()) return;void save().catch((error) => options.onError?.(error));}, 500);+ // WebKit can suspend storage and timers once the app is hidden, and aborts+ // writes in flight. Send the debounced server save before that happens, and+ // retry a failed local write whenever visibility changes.+ const flushOnVisibilityChange = () => {+ if (options.paused() || (!pending && !failed)) return;+ void save().catch((error) => options.onError?.(error));+ };+ document.addEventListener('visibilitychange', flushOnVisibilityChange);onCleanup(() => {- const flush = pending;+ document.removeEventListener('visibilitychange', flushOnVisibilityChange);+ const retry = failed;+ const flush = pending ?? retry;cancel();// Reading the live thread/editor here can reenter Solid's disposal of- // that same view. The last edit already captured and queued its local copy.+ // that same view. The last edit already captured its local copy; a copy+ // that failed is written again before the editor holding it is gone.if (flush && !options.paused())- void enqueue(flush.snapshot, flushLocal()).catch((error) =>- options.onError?.(error)- );+ void enqueue(+ flush.snapshot,+ retry ? saveLocally(flush.snapshot) : flushLocal()+ ).catch((error) => options.onError?.(error));});return {save,diff --git a/apps/web/src/features/email-compose/primitives/draft-save-notice.ts b/apps/web/src/features/email-compose/primitives/draft-save-notice.tsindex 6749a84720..9f170aaa97 100644--- a/apps/web/src/features/email-compose/primitives/draft-save-notice.ts+++ b/apps/web/src/features/email-compose/primitives/draft-save-notice.ts@@ -1,7 +1,12 @@import { onCleanup } from 'solid-js';import type { EmailComposeFeedback } from '../context/compose-capabilities';-/** One warning per local-save failure episode, shared by both composers. */+/**+ * One warning per local-save failure episode, shared by both composers.+ * Closing the composer dismisses it. A write that fails after closing, such as+ * the failed edit it writes once more, shows a brief warning instead: nothing+ * is left to dismiss a persistent one.+ */export function createDraftSaveNotice(feedback: EmailComposeFeedback['feedback']) {@@ -19,11 +24,11 @@ export function createDraftSaveNotice(});return {onLocalError(error: unknown) {- if (disposed || failed) return;+ if (failed) return;failed = true;notice = feedback.failure('Draft could not be saved on this device', {subtext: String(error),- persistent: true,+ persistent: !disposed,});},onLocalSaved: clear,diff --git a/apps/web/src/lib/persistence/recoverable-idb.test.ts b/apps/web/src/lib/persistence/recoverable-idb.test.tsindex 074aa6a48d..22ac4ca88d 100644--- a/apps/web/src/lib/persistence/recoverable-idb.test.ts+++ b/apps/web/src/lib/persistence/recoverable-idb.test.ts@@ -102,6 +102,110 @@ describe('recoverable native IndexedDB connections', () => {await expect(db.transaction('items', 'readonly')).resolves.toBeDefined();});+ it('replays a transaction the platform aborts mid-write on a fresh connection', async () => {+ const lost = vi.fn();+ const db = new RecoverableIDB(+ crypto.randomUUID(),+ 1,+ (db) => db.createObjectStore('items'),+ undefined,+ lost+ );+ databases.push(db);+ const original = await db.open();+ let runs = 0;+ const value = await db.run<number>('items', 'readwrite', (tx, finish) => {+ const store = tx.objectStore('items');+ const read = store.get('count');+ read.onsuccess = () => {+ const next = (read.result ?? 0) + 1;+ store.put(next, 'count');+ finish(next);+ // WebKit stops the transaction after its requests were issued.+ if (runs++ === 0) tx.abort();+ };+ });+ expect(value).toBe(1);+ expect(runs).toBe(2);+ expect(lost).toHaveBeenCalledOnce();+ expect(await db.open()).not.toBe(original);+ });++ it('bounds replays and rejects with the interruption', async () => {+ const db = database();+ const body = vi.fn((tx: IDBTransaction) => {+ tx.objectStore('items').put('value', 'key');+ tx.abort();+ });+ await expect(db.run('items', 'readwrite', body)).rejects.toMatchObject({+ name: 'AbortError',+ });+ expect(body).toHaveBeenCalledTimes(3);+ await expect(+ db.run<string>('items', 'readonly', (tx, finish) => {+ const read = tx.objectStore('items').get('key');+ read.onsuccess = () => finish(read.result);+ })+ ).resolves.toBeUndefined();+ });++ it('does not replay request failures that are not interruptions', async () => {+ const db = database();+ await db.run('items', 'readwrite', (tx) => {+ tx.objectStore('items').add('first', 'key');+ });+ const native = await db.open();+ const body = vi.fn((tx: IDBTransaction) => {+ tx.objectStore('items').add('second', 'key');+ });+ await expect(db.run('items', 'readwrite', body)).rejects.toMatchObject({+ name: 'ConstraintError',+ });+ expect(body).toHaveBeenCalledOnce();+ expect(await db.open()).toBe(native);+ });++ it('does not replay a body that throws', async () => {+ const db = database();+ const error = new Error('Invalid input');+ const body = vi.fn((tx: IDBTransaction) => {+ tx.objectStore('items').put('partial', 'key');+ throw error;+ });+ await expect(db.run('items', 'readwrite', body)).rejects.toBe(error);+ expect(body).toHaveBeenCalledOnce();+ await expect(+ db.run<string>('items', 'readonly', (tx, finish) => {+ const read = tx.objectStore('items').get('key');+ read.onsuccess = () => finish(read.result);+ })+ ).resolves.toBeUndefined();+ });++ it('does not replay a body whose request callback throws', async () => {+ const lost = vi.fn();+ const db = new RecoverableIDB(+ crypto.randomUUID(),+ 1,+ (db) => db.createObjectStore('items'),+ undefined,+ lost+ );+ databases.push(db);+ const native = await db.open();+ const callback = vi.fn(() => {+ throw new Error('Invalid stored value');+ });+ await expect(+ db.run('items', 'readwrite', (tx) => {+ tx.objectStore('items').get('key').onsuccess = callback;+ })+ ).rejects.toMatchObject({ name: 'AbortError' });+ expect(callback).toHaveBeenCalledOnce();+ expect(lost).not.toHaveBeenCalled();+ expect(await db.open()).toBe(native);+ });+it('closes an in-flight open and never revives a disposed owner', async () => {const db = database();const pending = db.transaction('items', 'readonly');diff --git a/apps/web/src/lib/persistence/recoverable-idb.ts b/apps/web/src/lib/persistence/recoverable-idb.tsindex 7a85371c91..f62dacc090 100644--- a/apps/web/src/lib/persistence/recoverable-idb.ts+++ b/apps/web/src/lib/persistence/recoverable-idb.ts@@ -1,4 +1,19 @@-/** Reopens stale connections without replaying requests or started transactions. */+/** Errors WebKit raises when it suspends or drops a connection under a running transaction. */+const INTERRUPTIONS = new Set([+ 'AbortError',+ 'InvalidStateError',+ 'TransactionInactiveError',+ 'UnknownError',+]);+const RUN_ATTEMPTS = 3;++class Interrupted extends Error {+ constructor(readonly error: DOMException) {+ super(error.message);+ }+}++/** Reopens stale connections; only `run` replays a started transaction. */export class RecoverableIDB {private connection?: Promise<IDBDatabase>;private disposed = false;@@ -7,7 +22,9 @@ export class RecoverableIDB {private readonly name: string,private readonly version: number,private readonly upgrade: (db: IDBDatabase, tx: IDBTransaction) => void,- private readonly onVersionChange?: () => void+ private readonly onVersionChange?: () => void,+ /** A connection closed or a transaction was interrupted underneath its owner. */+ private readonly onConnectionLost?: () => void) {}open(): Promise<IDBDatabase> {@@ -27,18 +44,19 @@ export class RecoverableIDB {};request.onsuccess = () => {const db = request.result;- const invalidate = () => {- if (this.connection === opening) this.connection = undefined;+ db.onclose = () => {+ if (this.connection !== opening) return;+ this.connection = undefined;+ this.onConnectionLost?.();};- db.onclose = invalidate;db.onversionchange = () => {db.close();- invalidate();+ if (this.connection === opening) this.connection = undefined;this.onVersionChange?.();};if (this.disposed) {db.close();- invalidate();+ if (this.connection === opening) this.connection = undefined;reject(new DOMException('Database connection disposed',@@ -55,6 +73,40 @@ export class RecoverableIDB {}async transaction(stores: string | string[], mode: IDBTransactionMode) {+ return (await this.begin(stores, mode)).tx;+ }++ /**+ * Runs `body` in one transaction and resolves with the value it passes to+ * `finish` once the transaction commits. When the platform aborts the+ * transaction after it started, the connection is replaced and `body` runs+ * again from the start, a bounded number of times. An aborted transaction+ * commits nothing, but a commit can land after the page saw the abort, so+ * `body` must read the state it depends on inside the transaction and be+ * safe to repeat. Report domain failures through the value, not+ * `tx.abort()`, which looks like an interruption. A body that throws, or+ * whose request callback throws, is not replayed.+ */+ async run<T>(+ stores: string | string[],+ mode: IDBTransactionMode,+ body: (tx: IDBTransaction, finish: (value: T) => void) => void+ ): Promise<T> {+ for (let attempt = 1; ; attempt++) {+ const { tx, opening } = await this.begin(stores, mode);+ try {+ return await settle(tx, body);+ } catch (error) {+ if (!(error instanceof Interrupted)) throw error;+ if (this.connection === opening) this.connection = undefined;+ tx.db.close();+ this.onConnectionLost?.();+ if (attempt === RUN_ATTEMPTS || this.disposed) throw error.error;+ }+ }+ }++ private async begin(stores: string | string[], mode: IDBTransactionMode) {for (let attempt = 0; ; attempt++) {const opening = this.open();const db = await opening;@@ -64,7 +116,7 @@ export class RecoverableIDB {'InvalidStateError');try {- return db.transaction(stores, mode);+ return { tx: db.transaction(stores, mode), opening };} catch (error) {if (!(error instanceof DOMException) ||@@ -73,6 +125,7 @@ export class RecoverableIDB {throw error;if (this.connection === opening) this.connection = undefined;db.close();+ this.onConnectionLost?.();// Creation failed before any requests ran, so a single retry is safe.if (attempt === 1) throw error;}@@ -91,3 +144,45 @@ export class RecoverableIDB {}}}++function settle<T>(+ tx: IDBTransaction,+ body: (tx: IDBTransaction, finish: (value: T) => void) => void+): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ let value: T;+ let thrown: { error: unknown } | undefined;+ let requestError: DOMException | null = null;+ tx.oncomplete = () => resolve(value);+ // A request error bubbles before `tx.error` is set and before rollback+ // finishes. Settle only on abort, so callers see the real cause and a+ // replay never starts while the old transaction is still rolling back.+ tx.onerror = (event) => {+ requestError ??= (event.target as IDBRequest | null)?.error ?? null;+ };+ tx.onabort = () => {+ if (thrown) {+ reject(thrown.error);+ return;+ }+ // WebKit fails pending requests before it sets `tx.error`, often to null.+ const cause =+ tx.error ??+ requestError ??+ new DOMException('The transaction was aborted', 'AbortError');+ // An exception thrown in a request callback aborts with a non-null+ // AbortError. That is a bug in the body, so it is never replayed.+ const interrupted =+ INTERRUPTIONS.has(cause.name) && tx.error?.name !== 'AbortError';+ reject(interrupted ? new Interrupted(cause) : cause);+ };+ try {+ body(tx, (next) => {+ value = next;+ });+ } catch (error) {+ thrown = { error };+ tx.abort();+ }+ });+}diff --git a/apps/web/src/lib/queries/email/email-send-journal.ts b/apps/web/src/lib/queries/email/email-send-journal.tsindex cd6fe68660..24d20a5703 100644--- a/apps/web/src/lib/queries/email/email-send-journal.ts+++ b/apps/web/src/lib/queries/email/email-send-journal.ts@@ -218,13 +218,25 @@ export function createEmailSendJournal(session: Session,uuid: string): Promise<RestoredEmailSend | undefined> {+ // Kept across replays so one can recognize a restore that already landed.+ let landed: RestoredEmailSend | undefined;const result = await transaction<RestoredEmailSend | Error | undefined>('readwrite',(tx, finish) =>withSession(tx,session,- () => restoreEmailSendTransaction(tx, session, uuid, finish),+ () =>+ restoreEmailSendTransaction(+ tx,+ session,+ uuid,+ (value) => {+ if (value && !(value instanceof Error)) landed = value;+ finish(value);+ },+ landed+ ),finish,undefined)diff --git a/apps/web/src/lib/queries/email/email-send-restoration.ts b/apps/web/src/lib/queries/email/email-send-restoration.tsindex ffbe7f4b88..0f475d2c7e 100644--- a/apps/web/src/lib/queries/email/email-send-restoration.ts+++ b/apps/web/src/lib/queries/email/email-send-restoration.ts@@ -7,17 +7,34 @@ import { type EmailSendIntent, isEmailSendIntent } from './send-intent';export type RestoredEmailSend = { draft: LocalDraft; intent: EmailSendIntent };-/** Cancellation, copy restoration and authority retirement share one transaction. */+/**+ * Cancellation, copy restoration and authority retirement share one transaction.+ * `landed` is this call's result from an attempt the page saw abort; when the+ * send is gone and the copy still has that attempt's generation, the attempt+ * committed and its result stands.+ */export function restoreEmailSendTransaction(tx: IDBTransaction,session: DraftStorageSession,uuid: string,- finish: (result: RestoredEmailSend | Error | undefined) => void+ finish: (result: RestoredEmailSend | Error | undefined) => void,+ landed?: RestoredEmailSend) {const sends = tx.objectStore('sends');const request = sends.get(uuid);request.onsuccess = () => {const intent = request.result as EmailSendIntent | undefined;+ if (!intent && landed) {+ const copy = tx.objectStore('drafts').get(landed.draft.key);+ copy.onsuccess = () =>+ finish(+ (copy.result as LocalDraft | undefined)?.generation ===+ landed.draft.generation+ ? landed+ : undefined+ );+ return;+ }if (!isEmailSendIntent(intent) ||intent.accountId !== session.accountId ||diff --git a/apps/web/src/lib/queries/email/local-draft-store.test.ts b/apps/web/src/lib/queries/email/local-draft-store.test.tsindex a6e87ea657..092edb7e1f 100644--- a/apps/web/src/lib/queries/email/local-draft-store.test.ts+++ b/apps/web/src/lib/queries/email/local-draft-store.test.ts@@ -29,6 +29,25 @@ const snapshot = (attachments: [],status: 'dirty',});+/**+ * The next transaction commits, but the connection drops before the page hears+ * about it, so it observes an abort instead of completion and replays.+ */+const landBeforeAbort = () => {+ const transaction = IDBDatabase.prototype.transaction;+ vi.spyOn(IDBDatabase.prototype, 'transaction').mockImplementationOnce(+ function (this: IDBDatabase, ...args) {+ const tx = transaction.apply(this, args);+ Object.defineProperty(tx, 'oncomplete', {+ set: () =>+ tx.addEventListener('complete', () =>+ tx.onabort?.call(tx, new Event('abort'))+ ),+ });+ return tx;+ }+ );+};afterEach(async () => {for (const store of stores.splice(0)) await store.close();vi.unstubAllGlobals();@@ -190,7 +209,10 @@ describe('draft connection recovery', () => {expect(transaction).toHaveBeenCalledTimes(2);await expect(store.save(session, snapshot())).rejects.toBe(error);expect(transaction).toHaveBeenCalledTimes(4);- expect(report).toHaveBeenCalledExactlyOnceWith({ type: 'failed', error });+ expect(report.mock.calls).toEqual([+ [{ type: 'closed' }],+ [{ type: 'failed', error }],+ ]);transaction.mockRestore();await store.save(session, snapshot());expect(report).toHaveBeenLastCalledWith({ type: 'recovered' });@@ -212,7 +234,7 @@ describe('draft connection recovery', () => {await store.save(session, snapshot());});- it('never replays a started transaction when a request throws InvalidStateError', async () => {+ it('does not replay a transaction whose body throws InvalidStateError', async () => {const store = open();const session = await store.activate('owner');const error = new DOMException('Request failed', 'InvalidStateError');@@ -267,6 +289,122 @@ describe('draft connection recovery', () => {expect(connections).toHaveLength(2);});+ it('reopens and replays a save whose transaction the platform aborts mid-write', async () => {+ const report = vi.fn();+ const store = createLocalDraftStore(crypto.randomUUID(), report);+ stores.push(store);+ const session = await store.activate('owner');+ const put = IDBObjectStore.prototype.put;+ let interrupted = 0;+ vi.spyOn(IDBObjectStore.prototype, 'put').mockImplementation(function (+ this: IDBObjectStore,+ ...args+ ) {+ const request = put.apply(this, args);+ // WebKit stops in-flight transactions when the app is backgrounded:+ // pending requests fail before the transaction reports its abort.+ if (this.name === 'drafts' && interrupted++ === 0)+ this.transaction.abort();+ return request;+ });+ const saved = await store.save(session, snapshot('Typed in background'));+ expect(saved).toMatchObject({ revision: 1 });+ expect(interrupted).toBe(2);+ expect(connections).toHaveLength(2);+ expect(await store.read(session, 'local')).toMatchObject({+ revision: 1,+ content: { subject: 'Typed in background' },+ });+ expect(report.mock.calls).toEqual([+ [{ type: 'closed' }],+ [{ type: 'recovered' }],+ ]);+ });++ it('does not reject a save whose commit landed before the page saw an abort', async () => {+ const store = open();+ const session = await store.activate('owner');+ landBeforeAbort();+ expect(await store.save(session, snapshot())).toMatchObject({+ revision: 1,+ });+ expect(await store.save(session, snapshot('Next edit', 1))).toMatchObject({+ revision: 2,+ });+ });++ it('bounds replays when every attempt is aborted and keeps the committed draft', async () => {+ const report = vi.fn();+ const store = createLocalDraftStore(crypto.randomUUID(), report);+ stores.push(store);+ const session = await store.activate('owner');+ await store.save(session, snapshot('Committed earlier'));+ const put = IDBObjectStore.prototype.put;+ const abort = vi+ .spyOn(IDBObjectStore.prototype, 'put')+ .mockImplementation(function (this: IDBObjectStore, ...args) {+ const request = put.apply(this, args);+ if (this.name === 'drafts') this.transaction.abort();+ return request;+ });+ await expect(+ store.save(session, snapshot('Never committed', 1))+ ).rejects.toMatchObject({ name: 'AbortError' });+ expect(abort).toHaveBeenCalledTimes(3);+ expect(report).toHaveBeenLastCalledWith({+ type: 'failed',+ error: expect.objectContaining({ name: 'AbortError' }),+ });+ abort.mockRestore();+ expect(await store.read(session, 'local')).toMatchObject({+ revision: 1,+ content: { subject: 'Committed earlier' },+ });+ await store.save(session, snapshot('After returning', 1));+ expect(report).toHaveBeenLastCalledWith({ type: 'recovered' });+ });++ it('replays an interrupted send claim on a new connection', async () => {+ const store = open();+ const session = await store.activate('owner');+ await store.save(session, snapshot());+ await store.putSend(session, sendIntent(), true);+ const put = IDBObjectStore.prototype.put;+ let interrupted = 0;+ vi.spyOn(IDBObjectStore.prototype, 'put').mockImplementation(function (+ this: IDBObjectStore,+ ...args+ ) {+ const request = put.apply(this, args);+ if (this.name === 'sends' && interrupted++ === 0)+ this.transaction.abort();+ return request;+ });+ const claimed = await store.claimSend(session, 'attempt', 'worker', 1_000);+ expect(claimed?.dispatch).toMatchObject({ generation: 1, owner: 'worker' });+ expect(interrupted).toBe(2);+ expect(connections).toHaveLength(2);+ });++ it('does not claim a send twice when the claim committed before the page saw an abort', async () => {+ const store = open();+ const session = await store.activate('owner');+ await store.save(session, snapshot());+ await store.putSend(session, sendIntent(), true);+ landBeforeAbort();+ // The replay finds its own lease and declines rather than sending again.+ expect(+ await store.claimSend(session, 'attempt', 'worker', 1_000)+ ).toBeUndefined();+ const [row] = await store.sends(session);+ expect(row.submissionStarted).toBe(true);+ expect(row.dispatch).toMatchObject({ generation: 1, owner: 'worker' });+ // Once the lease expires, the next claim resumes the same send.+ expect(+ await store.claimSend(session, 'attempt', 'worker', 62_000)+ ).toMatchObject({ dispatch: { generation: 2 } });+ });+it('keeps persistence working when recovery reporting throws', async () => {const report = vi.fn(() => {throw new Error('Telemetry unavailable');@@ -276,7 +414,10 @@ describe('draft connection recovery', () => {const session = await store.activate('owner');connections[0].close();await store.save(session, snapshot());- expect(report).toHaveBeenCalledExactlyOnceWith({ type: 'recovered' });+ expect(report.mock.calls).toEqual([+ [{ type: 'closed' }],+ [{ type: 'recovered' }],+ ]);expect(await store.list(session)).toHaveLength(1);});});@@ -417,6 +558,15 @@ describe('working-copy concurrency fences', () => {await store.list(await store.activate('owner', 'new-epoch'))).toEqual([]);});+ it('keeps the logout fence when a landed clear is replayed', async () => {+ const store = open();+ await store.activate('owner', 'old-epoch');+ landBeforeAbort();+ await store.clear(true, 'old-epoch');+ await expect(store.activate('owner', 'old-epoch')).rejects.toThrow(+ 'no longer active'+ );+ });it('merges upload receipts committed after a snapshot was captured', async () => {const store = open();const owner = await store.activate('owner');@@ -687,6 +837,24 @@ describe('independent send recovery records', () => {})).resolves.toMatchObject({ revision: restored.revision + 1 });});+ it('returns the restored copy when a restore that already landed is replayed', async () => {+ const store = open(),+ owner = await store.activate('owner');+ await store.save(owner, snapshot());+ await store.putSend(+ owner,+ { ...sendIntent(), cancellationRequested: true },+ true+ );+ landBeforeAbort();+ const restored = await store.restoreSend(owner, sendIntent().uuid);+ expect(restored?.intent.uuid).toBe(sendIntent().uuid);+ expect(await store.read(owner, 'local')).toMatchObject({+ generation: restored?.draft.generation,+ revision: restored?.draft.revision,+ });+ expect(await store.sends(owner)).toEqual([]);+ });it('clears send content and fences old sessions on account changes and logout', async () => {const store = open(),owner = await store.activate('owner');diff --git a/apps/web/src/lib/queries/email/local-draft-store.ts b/apps/web/src/lib/queries/email/local-draft-store.tsindex 4ff3394cd9..5bdd820c87 100644--- a/apps/web/src/lib/queries/email/local-draft-store.ts+++ b/apps/web/src/lib/queries/email/local-draft-store.ts@@ -2,6 +2,7 @@ import type {DraftAttempt,LocalDraft,} from '@app/features/email-compose/core/local-draft';+import { RecoverableIDB } from '../../persistence/recoverable-idb';import {createEmailSendJournal,restoreEmailSendLocks,@@ -14,7 +15,8 @@ type AttemptRecord = DraftAttempt & {storageGeneration: string;};export type DraftStorageSession = { accountId: string; epoch: string };-type StoredDraft = LocalDraft & { epoch: string };+/** `writeId` identifies the save that produced the record, so a replay can recognize its own commit. */+type StoredDraft = LocalDraft & { epoch: string; writeId?: string };const STORES = ['drafts', 'files', 'attempts', 'sends', 'meta'] as const;export type DraftStorageEvent =@@ -26,7 +28,6 @@ export function createLocalDraftStore(dbName = 'macro-email-working-copies-v1',onStorageEvent?: (event: DraftStorageEvent) => void) {- let connection: Promise<IDBDatabase> | undefined;let recovering = false;let failed = false;const report = (event: DraftStorageEvent) => {@@ -55,16 +56,13 @@ export function createLocalDraftStore(/* Durable state remains readable without notifications. */}};- const open = () => {- if (connection) return connection;- const request = indexedDB.open(dbName, 3);- const opening = new Promise<IDBDatabase>((resolve, reject) => {- request.onupgradeneeded = () => {+ const connect = () =>+ new RecoverableIDB(+ dbName,+ 3,+ (db, tx) => {for (const name of STORES)- if (!request.result.objectStoreNames.contains(name))- request.result.createObjectStore(name);- const tx = request.transaction;- if (!tx) return;+ if (!db.objectStoreNames.contains(name)) db.createObjectStore(name);const owner = tx.objectStore('meta').get('session');owner.onsuccess = () => {const session = owner.result as DraftStorageSession | undefined;@@ -80,92 +78,34 @@ export function createLocalDraftStore(row.continue();};};- };- request.onerror = () => {- if (connection === opening) connection = undefined;- reject(request.error);- };- request.onsuccess = () => {- const db = request.result;- db.onclose = () => {- if (connection !== opening) return;- connection = undefined;- recovering = true;- report({ type: 'closed' });- };- db.onversionchange = () => {- db.close();- if (connection === opening) connection = undefined;- };- resolve(db);- try {- if (typeof BroadcastChannel !== 'undefined' && !channel) {- channel = new BroadcastChannel(dbName);- channel.onmessage = notify;- }- } catch {- /* Embedded browsers may expose an unavailable channel. */- }- };- });- connection = opening;- return opening;- };- async function beginTransaction(mode: IDBTransactionMode) {- for (let attempt = 0; ; attempt++) {- const opening = open();- const db = await opening;- try {- return db.transaction([...STORES], mode);- } catch (error) {- if (- !(error instanceof DOMException) ||- error.name !== 'InvalidStateError'- )- throw error;- if (connection === opening) connection = undefined;- db.close();+ },+ undefined,+ () => {+ if (!recovering) report({ type: 'closed' });recovering = true;- // No requests have run yet. Never replay a started draft transaction.- if (attempt === 1) throw error;}+ );+ let database = connect();+ const listen = () => {+ try {+ if (typeof BroadcastChannel !== 'undefined' && !channel) {+ channel = new BroadcastChannel(dbName);+ channel.onmessage = notify;+ }+ } catch {+ /* Embedded browsers may expose an unavailable channel. */}- }+ };+ /** Every body re-reads its fences inside the transaction, so a replay after an interruption is safe. */async function transaction<T>(mode: IDBTransactionMode,run: (tx: IDBTransaction, finish: (value: T) => void) => void,publish = true): Promise<T> {try {- const tx = await beginTransaction(mode);- const result = await new Promise<T>((resolve, reject) => {- let value: T;- let executionError: unknown;- tx.oncomplete = () => {- resolve(value);- if (mode === 'readwrite' && publish) changed();- };- // Request errors bubble before tx.error is set and before rollback- // finishes. Settle only on abort so callers see the real cause and- // cannot start recovery against a transaction that is still running.- tx.onabort = () =>- reject(- executionError ??- tx.error ??- new DOMException(- 'Draft storage transaction aborted',- 'AbortError'- )- );- try {- run(tx, (next) => {- value = next;- });- } catch (error) {- executionError = error;- tx.abort();- }- });+ const result = await database.run([...STORES], mode, run);+ listen();+ if (mode === 'readwrite' && publish) changed();if (recovering || failed) report({ type: 'recovered' });recovering = false;failed = false;@@ -226,14 +166,15 @@ export function createLocalDraftStore(epoch?: string,isCurrent = () => true): Promise<DraftStorageSession> {- return await transaction(+ const fenced = new Error('This draft session is no longer active');+ const result = await transaction<DraftStorageSession | Error>('readwrite',(tx, finish) => {const meta = tx.objectStore('meta');const retired = meta.get(['retired-session', epoch ?? '']);retired.onsuccess = () => {if (epoch && retired.result) {- tx.abort();+ finish(fenced);return;}const request = meta.get('session');@@ -247,7 +188,7 @@ export function createLocalDraftStore(previous.accountId !== accountId &&(!epoch || previous.epoch === epoch))) {- tx.abort();+ finish(fenced);return;}if (@@ -271,6 +212,8 @@ export function createLocalDraftStore(},false);+ if (result instanceof Error) throw result;+ return result;},read,async generation(@@ -333,6 +276,7 @@ export function createLocalDraftStore(> & { expectedRevision: number },files: ReadonlyMap<string, Blob> = new Map()): Promise<LocalDraft> {+ const writeId = crypto.randomUUID();const result = await transaction<LocalDraft | Error | undefined>('readwrite',(tx, finish) =>@@ -362,6 +306,10 @@ export function createLocalDraftStore(const request = drafts.get(input.key);request.onsuccess = () => {const previous = request.result as StoredDraft | undefined;+ if (previous?.writeId === writeId) {+ finish(previous);+ return;+ }if (previous && previous.generation !== input.generation) {finish(undefined);return;@@ -387,6 +335,7 @@ export function createLocalDraftStore(const draft: StoredDraft = {...snapshot,epoch: session.epoch,+ writeId,latestAttemptId: previous?.latestAttemptId,queuedAttemptId: previous?.queuedAttemptId,attachments: input.attachments.map((attachment) => {@@ -624,8 +573,10 @@ export function createLocalDraftStore(}for (const name of STORES)if (name !== 'sends') tx.objectStore(name).clear();- if (retire && previous)- meta.put(true, ['retired-session', previous.epoch]);+ // A replay of a clear that already landed finds no session; the+ // caller's epoch still names the session to fence.+ const retired = previous?.epoch ?? expectedEpoch;+ if (retire && retired) meta.put(true, ['retired-session', retired]);finish();};});@@ -636,9 +587,11 @@ export function createLocalDraftStore(listeners.delete(listener);};},+ /** Releases the connection; a later operation opens a new one. */async close() {- if (connection) (await connection).close();- connection = undefined;+ const closing = database;+ database = connect();+ await closing.close();try {channel?.close();} catch {diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 9b94f80896..c24f24691c 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -273,7 +273,7 @@ native offline archive support therefore requires a full app build, not just OTAThe per-query caches for email threads, channels, and native offline documentcontext reopen closed IndexedDB connections. Verify a cached read and a subsequentwrite after closing the connection, then clear/logout during recovery: old-account-entries must not return. Only transaction creation retries automatically; persistent+entries must not return. These caches retry only transaction creation; persistentstorage failures still follow the existing cache fallback behavior.Performance check: switch Signal → All twice against a large synchronized cache.@@ -513,19 +513,28 @@ sits below the header and that editing while failed continues saving locallywithout repeatedly submitting the rejected request.Local draft storage reopens unexpectedly closed IndexedDB connections. If creatinga transaction fails because the connection is closing, it retries once before-running any writes. Verify by closing the draft database connection, then editing:-the latest content must persist locally and server autosave must continue without-reloading. Repeat across background/resume on an iPhone. A transaction that has-already started is never automatically replayed. Persistent failures still block-server autosave; copy unsaved content before restarting. Storage failures and-recovery report current page visibility and network state without draft content.+running any writes. When WebKit aborts a started transaction (typically while the+iOS app is backgrounded), the whole transaction, draft or outbox, replays on a new+connection, at most three attempts; a save recognizes its own commit, so a replay+never duplicates a revision. Each edit is written locally at once; any visibility+change, such as hiding the app, also sends the debounced server save immediately+and retries a failed local write with the live editor content. Verify by closing+the draft database connection, then editing: the latest content must persist+locally and server autosave must continue without reloading. Repeat across+background/resume on an iPhone. Persistent failures still block server autosave;+copy unsaved content before restarting. Storage failures and recovery report+current page visibility and network state without draft content.Request errors settle only after the transaction's abort event, preserving the-underlying IndexedDB error and waiting for rollback before recovery. To verify,-force a request constraint failure: the prior draft must remain intact, the error-must be `ConstraintError`, and a subsequent valid save must succeed.--Repeated local-save failures show one persistent warning per composer; recovery-or closing that composer dismisses it. A later failure shows a new warning.+underlying IndexedDB error and waiting for rollback before recovery or replay. To+verify, force a request constraint failure: the prior draft must remain intact,+the error must be `ConstraintError` and is not replayed, and a subsequent valid+save must succeed.++Repeated local-save failures show one persistent warning per composer; a later+successful write or closing the composer dismisses it. Closing writes the failed+edit once more, unless send, discard, or a reset already cancelled it; if that+write also fails, a brief warning shows after the composer closes. A later+failure shows a new warning.Retry preserves the original draft handle. An already-sent rejection drops thelocal copy rather than recreating the sent message. The REST compose path keepsits existing behavior.diff --git a/docs/architecture/email.md b/docs/architecture/email.mdindex 6d30dc235e..30d87a627c 100644--- a/docs/architecture/email.md+++ b/docs/architecture/email.md@@ -157,7 +157,7 @@ The compose controllers now assemble these smaller responsibilities:| `email-send-schedule.ts` | Confirmed send time, pending changes, unscheduling and archive feedback. Send Later and schedule updates save the draft first, then schedule it through the REST endpoint. Cancellation only unlocks editing after confirmation. || `draft-session.ts` / `draft-persistence.ts` | Shared draft identity, queued-write status, rejection policy, and save/delete ordering. Server identity and a committed latest save are separate facts; uploads and updates to existing legacy schedules wait for a committed save. || `send-readiness.ts` | Outbox admission allows offline delivery with complete attachment references and rejects unfinished uploads. |-| `draft-autosave.ts` | One debounce and serialized write queue used by reply and standalone compose. Captures editor values before queueing, flushes pending edits on disposal, and exposes cancellation and completion for send/discard. |+| `draft-autosave.ts` | One debounce and serialized write queue used by reply and standalone compose. Captures editor values before queueing, flushes pending edits when visibility changes and on disposal, retries a failed local write on visibility changes and disposal unless cancelled, and exposes cancellation and completion for send/discard. || `reply-recipient-fields.ts` | Recipient field expansion, drag/drop and outside interaction. Receives values, a setter and a change callback; it knows nothing about saving or sending. || `reply-composer-focus.ts` | Deferred editor/recipient focus and the forward focus guard. Receives DOM accessors and an editor `focus()` capability. Its timers, animation frames and event listeners end with its owner. || `views/reply-envelope.tsx` | Sender, recipients and subject presentation. One recipient input implementation supplies the desktop/mobile layouts while the parent keeps a single editor mounted. |diff --git a/rules/ast-grep/ts-indexeddb-through-recoverable-idb.yml b/rules/ast-grep/ts-indexeddb-through-recoverable-idb.ymlnew file mode 100644index 0000000000..1d2c597dc9--- /dev/null+++ b/rules/ast-grep/ts-indexeddb-through-recoverable-idb.yml@@ -0,0 +1,21 @@+id: ts-indexeddb-through-recoverable-idb+language: typescript+severity: error+message: Open IndexedDB through RecoverableIDB (src/lib/persistence/recoverable-idb.ts), not indexedDB.open.+note: |-+ WebKit closes connections and aborts started transactions when an iOS app is+ backgrounded. RecoverableIDB reopens closed connections, and its `run` method+ replays a transaction the platform interrupted, so its body must re-read the+ state it depends on inside the transaction and be safe to repeat. A raw+ connection held for the page's lifetime fails writes instead.+files:+ - apps/web/src/**+ignores:+ - apps/web/src/lib/persistence/recoverable-idb.ts+ - '**/*.test.ts'+ - '**/browser-test/**'+rule:+ any:+ - pattern: indexedDB.open($$$)+ - pattern: window.indexedDB.open($$$)+ - pattern: globalThis.indexedDB.open($$$)