Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(gql): email mutations can not block queue (#7397)

Peter Chinmana4c4a2834c11
diff --git a/apps/web/src/features/email-compose/components/draft-sync-status.test.tsx b/apps/web/src/features/email-compose/components/draft-sync-status.test.tsx
new file mode 100644
index 0000000000..8589958f47
--- /dev/null
+++ b/apps/web/src/features/email-compose/components/draft-sync-status.test.tsx
@@ -0,0 +1,77 @@
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import type { DraftSyncViewState } from '../core/local-draft';
+import { DraftSyncStatus } from './draft-sync-status';
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+const saved = (version: string): DraftSyncViewState => ({
+ message: 'Draft saved',
+ savedVersion: version,
+ failed: false,
+ canKeepEditing: false,
+});
+
+it('hides after two seconds and restarts only for another saved version', () => {
+ vi.useFakeTimers();
+ const [state, setState] = createSignal(saved('1'));
+ render(() => (
+ <DraftSyncStatus
+ state={state()}
+ busy={false}
+ onRetry={() => {}}
+ onKeepEditing={() => {}}
+ />
+ ));
+ const label = screen.getByText('Draft saved');
+ expect(label.getAttribute('aria-hidden')).toBe('false');
+ vi.advanceTimersByTime(1_500);
+ // Reading the same version again during queue settlement must not extend it.
+ setState(saved('1'));
+ vi.advanceTimersByTime(500);
+ expect(label.getAttribute('aria-hidden')).toBe('true');
+ setState(saved('2'));
+ expect(label.getAttribute('aria-hidden')).toBe('false');
+ vi.advanceTimersByTime(1_500);
+ setState(saved('3'));
+ vi.advanceTimersByTime(500);
+ expect(label.getAttribute('aria-hidden')).toBe('false');
+ vi.advanceTimersByTime(1_500);
+ expect(label.getAttribute('aria-hidden')).toBe('true');
+});
+
+it('keeps retry visible until recovery, then briefly acknowledges success', () => {
+ vi.useFakeTimers();
+ const [state, setState] = createSignal(saved('1'));
+ render(() => (
+ <DraftSyncStatus
+ state={state()}
+ busy={false}
+ onRetry={() => {}}
+ onKeepEditing={() => {}}
+ />
+ ));
+ setState({
+ message: 'Draft could not be synced',
+ failed: true,
+ action: 'retry',
+ canKeepEditing: false,
+ });
+ vi.advanceTimersByTime(10_000);
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeDefined();
+ setState(saved('1'));
+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();
+ expect(screen.getByText('Draft saved').getAttribute('aria-hidden')).toBe(
+ 'false'
+ );
+ vi.advanceTimersByTime(2_000);
+ expect(screen.getByText('Draft saved').getAttribute('aria-hidden')).toBe(
+ 'true'
+ );
+ cleanup();
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/apps/web/src/features/email-compose/components/draft-sync-status.tsx b/apps/web/src/features/email-compose/components/draft-sync-status.tsx
new file mode 100644
index 0000000000..481da80f06
--- /dev/null
+++ b/apps/web/src/features/email-compose/components/draft-sync-status.tsx
@@ -0,0 +1,83 @@
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ onCleanup,
+ Show,
+} from 'solid-js';
+import type { DraftSyncViewState } from '../core/local-draft';
+
+/** Durable recovery remains visible after remounting a failed draft. */
+export function DraftSyncStatus(props: {
+ state?: DraftSyncViewState;
+ busy: boolean;
+ error?: string;
+ onRetry(): void;
+ onKeepEditing(): void;
+}) {
+ const [showSaved, setShowSaved] = createSignal(false);
+ const savedVersion = createMemo(() =>
+ props.state?.failed || props.error ? undefined : props.state?.savedVersion
+ );
+ createEffect(() => {
+ if (!savedVersion()) {
+ setShowSaved(false);
+ return;
+ }
+ setShowSaved(true);
+ const timer = setTimeout(() => setShowSaved(false), 2_000);
+ onCleanup(() => clearTimeout(timer));
+ });
+ return (
+ <Show when={props.state}>
+ {(state) => (
+ <div
+ class="mr-2 flex shrink-0 items-center gap-2 whitespace-nowrap text-xs text-ink-muted"
+ role={state().failed || props.error ? 'alert' : 'status'}
+ title={
+ state().failed || props.error
+ ? (props.error ?? state().detail ?? state().message)
+ : undefined
+ }
+ >
+ <Show
+ when={state().action || props.error}
+ fallback={
+ <span
+ class="transition-opacity duration-200 motion-reduce:transition-none"
+ classList={{ 'opacity-0': !showSaved() }}
+ aria-hidden={!showSaved()}
+ >
+ {state().message}
+ </span>
+ }
+ >
+ <button
+ type="button"
+ class="text-failure-ink underline disabled:opacity-50"
+ disabled={props.busy}
+ onClick={props.onRetry}
+ >
+ {state().action === 'retry-discard' ? 'Retry discard' : 'Retry'}
+ </button>
+ </Show>
+ <Show when={state().canKeepEditing}>
+ <button
+ type="button"
+ class="underline"
+ disabled={props.busy}
+ onClick={props.onKeepEditing}
+ >
+ Keep editing
+ </button>
+ </Show>
+ <Show when={state().failed || props.error}>
+ <span class="sr-only">
+ {props.error ?? state().detail ?? state().message}
+ </span>
+ </Show>
+ </div>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx b/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx
index cca7fdcb55..fda94eefe1 100644
--- a/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx
+++ b/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx
@@ -30,19 +30,23 @@ export function MobileReplyToolbar(props: {
editingDisabled: boolean;
scheduleSummary?: JSX.Element;
scheduleControl?: JSX.Element;
+ status?: JSX.Element;
}) {
return (
<div
data-corvu-no-drag=""
class="sticky top-0 inset-x-0 z-10 flex shrink-0 flex-wrap items-center justify-between gap-y-2 bg-surface p-3 pt-0"
>
- <ToolbarButton
- label={props.discardLabel}
- onClick={props.onDiscard}
- disabled={props.editingDisabled}
- >
- <Trash class="size-(--mobile-chrome-icon-size)" />
- </ToolbarButton>
+ <div class="flex items-center">
+ {props.status}
+ <ToolbarButton
+ label={props.discardLabel}
+ onClick={props.onDiscard}
+ disabled={props.editingDisabled}
+ >
+ <Trash class="size-(--mobile-chrome-icon-size)" />
+ </ToolbarButton>
+ </div>
{props.scheduleSummary}
<div class="ml-auto flex items-center gap-2">
{props.scheduleControl}
diff --git a/apps/web/src/features/email-compose/compose-adapter.ts b/apps/web/src/features/email-compose/compose-adapter.ts
index 59a1b1eb3f..45e0fd58e2 100644
--- a/apps/web/src/features/email-compose/compose-adapter.ts
+++ b/apps/web/src/features/email-compose/compose-adapter.ts
@@ -38,6 +38,7 @@ import {
} from '@queries/email/draft';
import { markThreadDraftSaved } from '@queries/email/draft-cache';
import {
+ assertEmailDraftQueueAvailable,
deleteEmailDraftQueued,
draftQueueActive,
readEmailDraft,
@@ -53,6 +54,15 @@ import {
findPrimaryEmailLinkId,
nonPrimaryEmailLinkIdHeader,
} from '@queries/email/link';
+import {
+ clearLocalAttachmentReceipt,
+ forgetLocalDraft,
+ readLocalDraft,
+ recordLocalAttachment,
+ resumeLocalDraft,
+ reviveLocalDraft,
+ saveLocalDraft,
+} from '@queries/email/local-drafts';
import { useMailAccountsQuery } from '@queries/email/mail-accounts';
import {
fetchAndCacheThread,
@@ -73,6 +83,7 @@ import {
type EmailComposeContext,
type SaveEmailDraft,
} from './context/compose-capabilities';
+import { localDraftReadyForDelivery } from './core/local-draft';
import { readDroppedEmailFiles, withVideoAttachments } from './editor-adapter';
import { makeAttachmentPublic } from './make-attachment-public';
import {
@@ -134,6 +145,16 @@ export function createEmailComposeContext(
});
const reportError = (error: unknown) =>
Telemetry.error(error instanceof Error ? error : new Error(String(error)));
+ const requireSavedDraftForDelivery = async (
+ draftId: string | null | undefined
+ ) => {
+ if (!queueActive() || !draftId) return;
+ const local = await readLocalDraft(draftId);
+ if (local && !localDraftReadyForDelivery(local))
+ throw new Error(
+ 'Save the latest draft and attachments before sending or scheduling'
+ );
+ };
// A thread view renders its latest draft as the composer until the thread
// is read again, so every delivery change refetches it.
const refreshThread = (threadId: string | undefined) => {
@@ -254,6 +275,24 @@ export function createEmailComposeContext(
reportError,
},
drafts: {
+ get saveLocalDraft() {
+ return queueActive()
+ ? (input: import('@queries/email/local-drafts').LocalDraftInput) =>
+ saveLocalDraft({
+ ...input,
+ inboxId: input.inboxId ?? primaryId(),
+ senderEmail:
+ inboxSource
+ .inboxes()
+ .find(
+ (inbox) => inbox.id === (input.inboxId ?? primaryId())
+ )?.email_address ?? viewerEmail(),
+ })
+ : undefined;
+ },
+ get retryDraft() {
+ return queueActive() ? resumeLocalDraft : undefined;
+ },
get readDraft() {
return queueActive() ? readEmailDraft : undefined;
},
@@ -266,23 +305,44 @@ export function createEmailComposeContext(
inboxId,
...input
}) {
+ assertEmailDraftQueueAvailable();
const handles = queueHandles(input);
if (handles) {
- const senderLinkId = inboxId ?? primaryId() ?? '';
+ if (!(await readLocalDraft(handles.draftId)))
+ await saveLocalDraft({
+ ...input,
+ clientHandles: handles,
+ inboxId: inboxId ?? primaryId(),
+ attachments: [],
+ });
+ const local = await readLocalDraft(handles.draftId);
+ const senderLinkId = local?.inboxId ?? inboxId ?? primaryId() ?? '';
const outcome = await saveEmailDraftQueued({
- args: queuedDraftSaveArgs({
- draft: input.draft,
- handles,
- senderLinkId,
- senderAccount: accounts.isSuccess
- ? accounts.data?.links.find((link) => link.id === senderLinkId)
- : undefined,
- senderEmail:
- inboxSource.inboxes().find((inbox) => inbox.id === senderLinkId)
- ?.email_address ??
- viewerEmail() ??
- '',
- }),
+ args: {
+ ...queuedDraftSaveArgs({
+ draft: local?.content ?? input.draft,
+ handles: local
+ ? {
+ draftId: local.draftId,
+ threadId: local.threadId ?? handles.threadId,
+ }
+ : handles,
+ senderLinkId,
+ senderAccount: accounts.isSuccess
+ ? accounts.data?.links.find(
+ (link) => link.id === senderLinkId
+ )
+ : undefined,
+ senderEmail:
+ inboxSource
+ .inboxes()
+ .find((inbox) => inbox.id === senderLinkId)
+ ?.email_address ??
+ viewerEmail() ??
+ '',
+ }),
+ localRevision: local?.revision,
+ },
completingThread,
previousThreadId,
});
@@ -326,6 +386,7 @@ export function createEmailComposeContext(
};
},
async deleteDraft({ completingThread, inboxId, ...input }) {
+ assertEmailDraftQueueAvailable();
if (input.threadId && queueActive()) {
const outcome = await deleteEmailDraftQueued({
draftId: input.draftId,
@@ -370,18 +431,22 @@ export function createEmailComposeContext(
}
if (draft && html !== undefined)
await restoreDraftBodyAfterUndo(draft, html, headerId(inboxId));
+ if (queueActive()) await reviveLocalDraft(draftId);
if (threadId && isFeatureEnabled(enableGraphqlSoup))
void fetchAndCacheThread(threadId);
},
},
delivery: {
async sendMessage({ completingThread, inboxId, ...input }) {
+ await requireSavedDraftForDelivery(input.message.db_id);
const result = await send.mutateAsync({
...input,
linkId: headerId(inboxId),
skipSoupRefetch: completingThread,
});
try {
+ if (queueActive() && input.message.db_id)
+ await forgetLocalDraft(input.message.db_id);
if (result.message.db_id)
publishDraftLifecycleChange(
result.message.db_id,
@@ -417,6 +482,7 @@ export function createEmailComposeContext(
{ draftId, threadId, sendTime, includeSignature },
inboxId
) => {
+ await requireSavedDraftForDelivery(draftId);
await scheduleEmailMessage(
{
draftID: draftId,
@@ -459,6 +525,23 @@ export function createEmailComposeContext(
...input,
draftID: draftId,
linkId: headerId(inboxId),
+ onAttachmentAdded: async (file, id) => {
+ input.onAttachmentAdded?.(file, id);
+ if (queueActive())
+ await recordLocalAttachment(draftId, file, id, false);
+ },
+ onAttachmentUploaded: async (file, id) => {
+ input.onAttachmentUploaded?.(file, id);
+ if (queueActive())
+ await recordLocalAttachment(draftId, file, id, true);
+ },
+ onAttachmentUploadFailed: (file) => {
+ if (queueActive())
+ void recordLocalAttachment(draftId, file, undefined, false).catch(
+ reportError
+ );
+ input.onAttachmentUploadFailed?.(file);
+ },
}),
addForwardedAttachments: ({ draftId, attachments, inboxId }) =>
forward.mutateAsync({
@@ -468,12 +551,20 @@ export function createEmailComposeContext(
})),
linkId: headerId(inboxId),
}),
- removeAttachment: ({ draftId, attachmentId, inboxId }) =>
- removeAttachment.mutateAsync({
+ removeAttachment: async ({ draftId, attachmentId, inboxId }) => {
+ await removeAttachment.mutateAsync({
draftID: draftId,
attachmentID: attachmentId,
linkId: headerId(inboxId),
- }),
+ });
+ if (queueActive()) {
+ try {
+ await clearLocalAttachmentReceipt(draftId, attachmentId);
+ } catch (error) {
+ reportError(error);
+ }
+ }
+ },
removeForwardedAttachment: ({ draftId, attachmentId, inboxId }) =>
removeForwarded.mutateAsync({
draftID: draftId,
diff --git a/apps/web/src/features/email-compose/context/compose-capabilities.ts b/apps/web/src/features/email-compose/context/compose-capabilities.ts
index 5f90bf358f..e5cdb2dd33 100644
--- a/apps/web/src/features/email-compose/context/compose-capabilities.ts
+++ b/apps/web/src/features/email-compose/context/compose-capabilities.ts
@@ -3,6 +3,8 @@ import type { Accessor } from 'solid-js';
import type { EmailMessage } from '../../email-message/core/email-message';
import type { EmailDraft } from '../core/email-draft';
import type { EmailRecipient } from '../core/email-recipient';
+import type { LocalDraft } from '../core/local-draft';
+import type { DraftFormAttachment } from '../primitives/email-form-state';
export interface EmailInbox {
id: string;
@@ -87,6 +89,7 @@ export interface UploadEmailAttachments {
attachments: File[];
inboxId?: string;
onAttachmentAdded?: (file: File, id: string) => void;
+ onAttachmentUploaded?: (file: File, id: string) => void;
onAttachmentUploadFailed?: (file: File) => void;
}
export interface EmailAttachmentChange {
@@ -96,13 +99,27 @@ export interface EmailAttachmentChange {
}
export interface EmailDraftStorage {
+ /** Local acceptance is separate from remote autosave and continues after rejection. */
+ saveLocalDraft?(
+ input: SaveEmailDraft & {
+ attachments: readonly DraftFormAttachment[];
+ expectedRevision?: number;
+ expectedGeneration?: string;
+ }
+ ): Promise<LocalDraft>;
+ retryDraft?(draftId: string): Promise<void>;
/** Resolve durable local drafts before mounting an editor. */
- readDraft?(draftId: string): Promise<
+ readDraft?(
+ draftId: string,
+ options?: { attachments?: boolean }
+ ): Promise<
| {
/** Sent records retain mutation identity but never editable content. */
draft?: EmailMessage;
persistence: 'committed' | 'queued';
mutationUuid?: string;
+ local?: LocalDraft;
+ attachments?: DraftFormAttachment[];
}
| undefined
>;
diff --git a/apps/web/src/features/email-compose/core/local-draft.test.ts b/apps/web/src/features/email-compose/core/local-draft.test.ts
new file mode 100644
index 0000000000..8b2874292f
--- /dev/null
+++ b/apps/web/src/features/email-compose/core/local-draft.test.ts
@@ -0,0 +1,39 @@
+import { expect, it } from 'vitest';
+import { type LocalDraft, localDraftReadyForDelivery } from './local-draft';
+
+const draft: LocalDraft = {
+ key: 'draft',
+ accountId: 'owner',
+ generation: 'generation',
+ draftId: 'draft',
+ serverDraftId: 'server',
+ revision: 2,
+ acknowledgedRevision: 2,
+ content: { subject: 'Ready' },
+ attachments: [],
+ status: 'synced',
+ updatedAt: 1,
+};
+it('blocks both delivery paths when server identity is confirmed but newer edits or files are pending', () => {
+ expect(localDraftReadyForDelivery(draft)).toBe(true);
+ expect(localDraftReadyForDelivery({ ...draft, revision: 3 })).toBe(false);
+ expect(localDraftReadyForDelivery({ ...draft, status: 'unconfirmed' })).toBe(
+ false
+ );
+ expect(
+ localDraftReadyForDelivery({
+ ...draft,
+ attachments: [
+ {
+ type: 'local',
+ id: 'file',
+ name: 'notes.txt',
+ mimeType: 'text/plain',
+ size: 1,
+ lastModified: 0,
+ uploaded: false,
+ },
+ ],
+ })
+ ).toBe(false);
+});
diff --git a/apps/web/src/features/email-compose/core/local-draft.ts b/apps/web/src/features/email-compose/core/local-draft.ts
new file mode 100644
index 0000000000..e26a910aac
--- /dev/null
+++ b/apps/web/src/features/email-compose/core/local-draft.ts
@@ -0,0 +1,94 @@
+import type { EmailDraft } from './email-draft';
+
+/** A recoverable working copy, independent of any network mutation. */
+export type LocalDraftStatus =
+ | 'dirty'
+ | 'queued'
+ | 'synced'
+ | 'failed'
+ | 'unconfirmed'
+ | 'deleting'
+ | 'delete-failed';
+
+export type LocalDraftAttachment =
+ | {
+ type: 'local';
+ id: string;
+ name: string;
+ mimeType: string;
+ size: number;
+ lastModified: number;
+ attachmentId?: string;
+ uploaded: boolean;
+ }
+ | {
+ type: 'remote';
+ url: string;
+ fileName: string;
+ contentType: string;
+ attachmentId: string;
+ fileSize: number;
+ }
+ | {
+ type: 'forwarded';
+ attachmentId: string;
+ fileName: string;
+ mimeType: string;
+ fileSize: number;
+ };
+
+export type LocalDraft = {
+ key: string;
+ accountId: string;
+ generation: string;
+ revision: number;
+ acknowledgedRevision: number;
+ latestAttemptId?: string;
+ queuedAttemptId?: string;
+ draftId: string;
+ threadId?: string;
+ serverDraftId?: string;
+ serverThreadId?: string;
+ inboxId?: string;
+ senderEmail?: string;
+ content: EmailDraft;
+ attachments: LocalDraftAttachment[];
+ status: LocalDraftStatus;
+ errorCode?: string;
+ updatedAt: number;
+};
+
+/** Opaque to the normalized cache; only the email adapter interprets it. */
+export type DraftAttempt = {
+ kind: 'email-draft';
+ id: string;
+ draftKey: string;
+ accountId: string;
+ generation: string;
+ revision: number;
+ operation: 'save' | 'delete';
+};
+
+/** Presentation of local persistence and explicit server recovery. */
+export type DraftSyncViewState = {
+ message: string;
+ /** Identifies a saved version to acknowledge after editing pauses. */
+ savedVersion?: string;
+ detail?: string;
+ failed: boolean;
+ action?: 'retry' | 'retry-discard';
+ canKeepEditing: boolean;
+};
+
+/** Immediate and scheduled delivery must both wait for the latest local intent. */
+export function localDraftReadyForDelivery(draft: LocalDraft): boolean {
+ return (
+ draft.acknowledgedRevision >= draft.revision &&
+ !['failed', 'unconfirmed', 'delete-failed', 'deleting'].includes(
+ draft.status
+ ) &&
+ !draft.attachments.some(
+ (attachment) => attachment.type === 'local' && !attachment.uploaded
+ )
+ );
+}
diff --git a/apps/web/src/features/email-compose/core/recipient-conversion.ts b/apps/web/src/features/email-compose/core/recipient-conversion.ts
index 6225c65664..c99d68a88d 100644
--- a/apps/web/src/features/email-compose/core/recipient-conversion.ts
+++ b/apps/web/src/features/email-compose/core/recipient-conversion.ts
@@ -11,7 +11,9 @@ export const convertEmailRecipientToContactInfo = (
case 'user':
return { email: item.data.email, name: item.data.name };
case 'contact':
- return item.data;
+ // Form contacts can be Solid store proxies. Persistence needs an owned,
+ // cloneable snapshot rather than a live reference into the form.
+ return { ...item.data };
case 'custom':
return { email: item.data.email };
}
diff --git a/apps/web/src/features/email-compose/primitives/attachment-persistence.test.ts b/apps/web/src/features/email-compose/primitives/attachment-persistence.test.ts
index f207ba0345..cc47e086c9 100644
--- a/apps/web/src/features/email-compose/primitives/attachment-persistence.test.ts
+++ b/apps/web/src/features/email-compose/primitives/attachment-persistence.test.ts
@@ -8,7 +8,8 @@ const disposers: (() => void)[] = [];
afterEach(() => disposers.splice(0).forEach((dispose) => dispose()));
function setup(
- uploadAttachments: (input: UploadEmailAttachments) => Promise<void>
+ uploadAttachments: (input: UploadEmailAttachments) => Promise<void>,
+ confirmRemoval = false
) {
return createRoot((dispose) => {
disposers.push(dispose);
@@ -25,6 +26,7 @@ function setup(
const [draftId, setDraftId] = createSignal('draft');
const persistence = createAttachmentPersistence({
services,
+ confirmRemoval,
attachments: form.attachments,
draftId,
inboxId: () => 'secondary-inbox',
@@ -144,3 +146,25 @@ describe('draft attachment persistence', () => {
);
});
});
+
+it('keeps durable server attachments visible until removal succeeds, retaining them after failure', async () => {
+ const state = setup(async () => {}, true);
+ const attachment = {
+ type: 'local' as const,
+ file: new File(['keep'], 'keep.txt'),
+ attachmentId: 'server-file',
+ uploaded: true,
+ };
+ state.form.attachments.add(attachment);
+ const pending = Promise.withResolvers<void>();
+ state.services.removeAttachment.mockReturnValueOnce(pending.promise);
+ const removal = state.persistence.remove(attachment);
+ expect(state.persistence.removing()).toBe(true);
+ expect(state.form.attachments.list()).toEqual([attachment]);
+ pending.reject(new Error('Offline'));
+ await expect(removal).rejects.toThrow('Offline');
+ expect(state.form.attachments.list()).toEqual([attachment]);
+ expect(state.persistence.removing()).toBe(false);
+ await state.persistence.remove(attachment);
+ expect(state.form.attachments.list()).toEqual([]);
+});
diff --git a/apps/web/src/features/email-compose/primitives/attachment-persistence.ts b/apps/web/src/features/email-compose/primitives/attachment-persistence.ts
index 1fa3d2fbbe..7586153050 100644
--- a/apps/web/src/features/email-compose/primitives/attachment-persistence.ts
+++ b/apps/web/src/features/email-compose/primitives/attachment-persistence.ts
@@ -11,6 +11,7 @@ type AttachmentState = Pick<
EmailFormContextValue['attachments'],
| 'list'
| 'assignAttachmentId'
+ | 'markAttachmentUploaded'
| 'clearAttachmentId'
| 'removeByFile'
| 'removeById'
@@ -37,6 +38,8 @@ export async function refuseAttachmentsOffline(
/** Attachment transport and completion, independent of draft/send orchestration. */
export function createAttachmentPersistence(options: {
attachments: AttachmentState;
+ /** Durable working copies must not hide attachments still present on the server. */
+ confirmRemoval?: boolean;
draftId: Accessor<string | null | undefined>;
inboxId: Accessor<string | undefined>;
services: Pick<
@@ -52,9 +55,11 @@ export function createAttachmentPersistence(options: {
const inFlight = new Set<Promise<void>>();
const [uploading, setUploading] = createSignal(false);
let generation = 0;
+ const [removals, setRemovals] = createSignal(0);
return {
- uploading,
+ uploading: () => uploading() || removals() > 0,
+ removing: () => removals() > 0,
/** Local files can be uploaded again; remote-only draft files cannot be cloned. */
detach() {
generation += 1;
@@ -73,6 +78,21 @@ export function createAttachmentPersistence(options: {
const uploadGeneration = generation;
const stillCurrent = () =>
uploadGeneration === generation && options.draftId() === draftId;
+ for (const attachment of options.attachments.list()) {
+ if (
+ attachment.type !== 'local' ||
+ !attachment.uploadPending ||
+ !attachment.attachmentId
+ )
+ continue;
+ await options.services.removeAttachment({
+ draftId,
+ attachmentId: attachment.attachmentId,
+ inboxId: inbox.inboxId,
+ });
+ if (!stillCurrent()) return;
+ options.attachments.clearAttachmentId(attachment.file);
+ }
const attachments = options.attachments
.list()
.filter(
@@ -91,6 +111,10 @@ export function createAttachmentPersistence(options: {
if (stillCurrent())
options.attachments.assignAttachmentId(file, id);
},
+ onAttachmentUploaded: (file, id) => {
+ if (stillCurrent())
+ options.attachments.markAttachmentUploaded(file, id);
+ },
onAttachmentUploadFailed: (file) => {
if (stillCurrent()) options.attachments.clearAttachmentId(file);
},
@@ -121,26 +145,42 @@ export function createAttachmentPersistence(options: {
});
}
},
- remove(attachment: DraftFormAttachment) {
+ async remove(attachment: DraftFormAttachment) {
const state = options.attachments;
- if (attachment.type === 'local') state.removeByFile(attachment.file);
- else if (attachment.type === 'forwarded')
- state.removeForwarded(attachment.attachmentId);
- else state.removeById(attachment.attachmentId);
-
const draftId = options.draftId();
- if (!draftId || !attachment.attachmentId) return;
+ const removalGeneration = generation;
const operation =
attachment.type === 'forwarded'
? options.services.removeForwardedAttachment
: options.services.removeAttachment;
- void operation({
- draftId,
- attachmentId: attachment.attachmentId,
- inboxId: options.inboxId(),
- }).catch(() => {
- // The attachment query reports removal failures; keep optimistic removal.
- });
+ const request =
+ draftId && attachment.attachmentId
+ ? {
+ draftId,
+ attachmentId: attachment.attachmentId,
+ inboxId: options.inboxId(),
+ }
+ : undefined;
+ if (options.confirmRemoval && request) {
+ setRemovals((count) => count + 1);
+ try {
+ await operation(request);
+ } finally {
+ setRemovals((count) => count - 1);
+ }
+ if (generation !== removalGeneration || options.draftId() !== draftId)
+ return false;
+ }
+ if (attachment.type === 'local') state.removeByFile(attachment.file);
+ else if (attachment.type === 'forwarded')
+ state.removeForwarded(attachment.attachmentId);
+ else state.removeById(attachment.attachmentId);
+ if (!options.confirmRemoval && request) {
+ void operation(request).catch(() => {
+ // Preserve the existing REST composer's optimistic removal behavior.
+ });
+ }
+ return true;
},
};
}
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.ts
index 6d201c018b..f57ffb1166 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
@@ -5,7 +5,9 @@ import type {
EmailDraftStorage,
PersistedEmailIdentity,
} from '../context/compose-capabilities';
+import { DraftPersistRejected } from '../context/compose-capabilities';
import { decodeBase64Utf8 } from '../core/decode-base64';
+import type { LocalDraft } from '../core/local-draft';
import { createComposeContext } from '../tests/capabilities';
import { mountEmailComposer } from '../tests/composer';
import { mountReplyComposer } from '../tests/reply';
@@ -18,6 +20,49 @@ const response: PersistedEmailIdentity = {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
+it.each(['standalone', 'reply'] as const)(
+ 'does not acknowledge the %s pre-send save, including after failed delivery',
+ async (surface) => {
+ const context = createComposeContext();
+ context.drafts.saveLocalDraft = vi.fn(async (input) =>
+ localSnapshot(input)
+ );
+ const delivery = Promise.withResolvers<PersistedEmailIdentity>();
+ vi.mocked(context.delivery.sendMessage).mockReturnValueOnce(
+ delivery.promise
+ );
+ const root =
+ surface === 'standalone'
+ ? mountEmailComposer(context)
+ : mountReplyComposer(context);
+ const state = 'state' in root ? root.state : root;
+ try {
+ root.edit('Send without flashing Draft saved');
+ await vi.advanceTimersByTimeAsync(0);
+ if ('state' in root) root.state.context.onSend();
+ else void root.sendEmail();
+ expect(state.acknowledgeSaved()).toBe(false);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
+ expect(state.localSaveState()).toBe('saved');
+ expect(state.acknowledgeSaved()).toBe(false);
+ delivery.reject(new Error('Delivery failed'));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(state.acknowledgeSaved()).toBe(false);
+ root.edit('Keep editing after failure');
+ await vi.advanceTimersByTimeAsync(500);
+ expect(state.acknowledgeSaved()).toBe(true);
+ } finally {
+ delivery.resolve({
+ draftId: 'sent',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ });
+ root.dispose();
+ }
+ }
+);
+
it('flushes the latest pending body and envelope exactly once on disposal', async () => {
const composeContext = createComposeContext();
const root = mountEmailComposer(composeContext);
@@ -1109,3 +1154,239 @@ it.each(['standalone', 'reply'] as const)(
expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
}
);
+
+function localSnapshot(
+ input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
+): LocalDraft {
+ const id = input.clientHandles?.draftId ?? input.draft.db_id ?? 'draft';
+ return {
+ key: id,
+ accountId: 'owner',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ draftId: id,
+ threadId: input.clientHandles?.threadId,
+ content: input.draft,
+ attachments: [],
+ status: 'dirty',
+ updatedAt: Date.now(),
+ };
+}
+
+it.each(['standalone', 'reply'] as const)(
+ 'keeps one %s local-save warning until recovery or disposal',
+ async (surface) => {
+ const context = createComposeContext();
+ let diskFailed = true;
+ context.drafts.saveLocalDraft = vi.fn(async (input) => {
+ if (diskFailed) throw new Error('Disk full');
+ return localSnapshot(input);
+ });
+ vi.mocked(context.notices.feedback.failure)
+ .mockReturnValueOnce(7)
+ .mockReturnValueOnce(8);
+ const root =
+ surface === 'standalone'
+ ? mountEmailComposer(context)
+ : mountReplyComposer(context);
+ try {
+ for (const text of ['First edit', 'Second edit', 'Third edit']) {
+ root.edit(text);
+ await vi.advanceTimersByTimeAsync(600);
+ }
+ expect(context.notices.feedback.failure).toHaveBeenCalledExactlyOnceWith(
+ 'Draft could not be saved on this device',
+ { subtext: 'Error: Disk full', persistent: true }
+ );
+ expect(context.notices.feedback.dismiss).not.toHaveBeenCalled();
+ expect(context.drafts.saveDraft).not.toHaveBeenCalled();
+
+ diskFailed = false;
+ root.edit('Recovered edit');
+ await vi.advanceTimersByTimeAsync(600);
+ expect(context.notices.feedback.dismiss).toHaveBeenCalledExactlyOnceWith(
+ 7
+ );
+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
+
+ diskFailed = true;
+ root.edit('Another failure');
+ await vi.advanceTimersByTimeAsync(600);
+ expect(context.notices.feedback.failure).toHaveBeenCalledTimes(2);
+ } finally {
+ root.dispose();
+ }
+ expect(context.notices.feedback.dismiss).toHaveBeenLastCalledWith(8);
+ }
+);
+
+it.each(['standalone', 'reply'] as const)(
+ 'keeps the %s editor revision after adopting its server ID',
+ async (surface) => {
+ const context = createComposeContext();
+ let revision = 0;
+ const saveLocalDraft = vi.fn(
+ async (
+ input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
+ ) => {
+ if (
+ input.expectedRevision !== undefined &&
+ input.expectedRevision !== revision
+ )
+ throw new Error('Draft changed in another tab');
+ return { ...localSnapshot(input), revision: ++revision };
+ }
+ );
+ context.drafts.saveLocalDraft = saveLocalDraft;
+ const root =
+ surface === 'standalone'
+ ? mountEmailComposer(context)
+ : mountReplyComposer(context);
+ try {
+ root.edit('First save');
+ await vi.advanceTimersByTimeAsync(600);
+ const editorRevision = revision;
+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
+ revision += 1; // Another tab commits after the server ID is adopted.
+ root.edit('Stale editor edit');
+ await vi.advanceTimersByTimeAsync(600);
+ expect(saveLocalDraft.mock.lastCall?.[0].expectedRevision).toBe(
+ editorRevision
+ );
+ expect(saveLocalDraft.mock.lastCall?.[0].expectedGeneration).toBe(
+ 'generation'
+ );
+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
+ expect(context.notices.feedback.failure).toHaveBeenCalledWith(
+ 'Draft could not be saved on this device',
+ expect.anything()
+ );
+ } finally {
+ root.dispose();
+ }
+ }
+);
+
+it.each(['standalone', 'reply'] as const)(
+ 'waits for the first durable %s snapshot before discarding it',
+ async (surface) => {
+ const context = createComposeContext();
+ const pending = Promise.withResolvers<void>();
+ const saveLocalDraft = vi.fn(
+ async (
+ input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
+ ) => {
+ await pending.promise;
+ return localSnapshot(input);
+ }
+ );
+ context.drafts.saveLocalDraft = saveLocalDraft;
+ const root =
+ surface === 'standalone'
+ ? mountEmailComposer(context)
+ : mountReplyComposer(context);
+ try {
+ root.edit('Still copying attachment bytes');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(saveLocalDraft).toHaveBeenCalled();
+ const discard =
+ 'state' in root
+ ? root.state.deleteDraftAndReset()
+ : root.deleteDraftAndReset();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.drafts.deleteDraft).not.toHaveBeenCalled();
+ pending.resolve();
+ await discard;
+ expect(context.drafts.deleteDraft).toHaveBeenCalledOnce();
+ expect(context.drafts.saveDraft).not.toHaveBeenCalled();
+ } finally {
+ pending.resolve();
+ root.dispose();
+ }
+ }
+);
+
+it.each(['standalone', 'reply'] as const)(
+ 'persists further %s edits locally after rejection and retries the same handle',
+ async (surface) => {
+ const context = createComposeContext();
+ const saveLocalDraft = vi.fn(
+ async (
+ input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
+ ) => localSnapshot(input)
+ );
+ context.drafts.saveLocalDraft = saveLocalDraft;
+ context.drafts.retryDraft = vi.fn(async () => {});
+ vi.mocked(context.drafts.saveDraft).mockRejectedValueOnce(
+ new DraftPersistRejected('INVALID')
+ );
+ const root =
+ surface === 'standalone'
+ ? mountEmailComposer(context)
+ : mountReplyComposer(context);
+ try {
+ root.edit('Rejected text');
+ await vi.advanceTimersByTimeAsync(600);
+ const handle = vi.mocked(context.drafts.saveDraft).mock.calls[0][0]
+ .clientHandles?.draftId;
+ root.edit('New text saved only on this device');
+ await vi.advanceTimersByTimeAsync(600);
+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
+ const latest = saveLocalDraft.mock.lastCall?.[0];
+ expect(decodeBase64Utf8(latest?.draft.body_html ?? '')).toContain(
+ 'New text saved only on this device'
+ );
+ await ('state' in root ? root.state.retryDraft() : root.retryDraft());
+ expect(context.drafts.retryDraft).toHaveBeenCalledWith(handle);
+ expect(
+ vi.mocked(context.drafts.saveDraft).mock.lastCall?.[0].clientHandles
+ ?.draftId
+ ).toBe(handle);
+ } finally {
+ root.dispose();
+ }
+ }
+);
+
+it.each(['standalone', 'reply'] as const)(
+ 'refuses a stale %s retry without overwriting another tab’s durable edit',
+ async (surface) => {
+ const context = createComposeContext();
+ const saveLocalDraft = vi.fn(
+ async (
+ input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
+ ) => localSnapshot(input)
+ );
+ context.drafts.saveLocalDraft = saveLocalDraft;
+ context.drafts.retryDraft = vi.fn(async () => {});
+ vi.mocked(context.drafts.saveDraft).mockRejectedValueOnce(
+ new DraftPersistRejected('INVALID')
+ );
+ const root =
+ surface === 'standalone'
+ ? mountEmailComposer(context)
+ : mountReplyComposer(context);
+ try {
+ root.edit('This tab’s rejected text');
+ await vi.advanceTimersByTimeAsync(600);
+ const latest = localSnapshot(saveLocalDraft.mock.lastCall![0]);
+ latest.revision += 1;
+ latest.content = { subject: 'Newer edit in another tab' };
+ context.drafts.readDraft = vi.fn(async () => ({
+ local: latest,
+ persistence: 'queued' as const,
+ }));
+ const writes = saveLocalDraft.mock.calls.length;
+ await expect(
+ 'state' in root ? root.state.retryDraft() : root.retryDraft()
+ ).rejects.toThrow('changed in another tab');
+ expect(context.drafts.retryDraft).not.toHaveBeenCalled();
+ expect(saveLocalDraft).toHaveBeenCalledTimes(writes);
+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
+ expect(latest.content.subject).toBe('Newer edit in another tab');
+ } finally {
+ root.dispose();
+ }
+ }
+);
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.ts
new file mode 100644
index 0000000000..54c1735e13
--- /dev/null
+++ b/apps/web/src/features/email-compose/primitives/draft-autosave.test.ts
@@ -0,0 +1,204 @@
+import { createMemo, createRoot, createSignal, onCleanup } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { createDraftAutosave } from './draft-autosave';
+
+const disposers: (() => void)[] = [];
+afterEach(() => {
+ disposers.splice(0).forEach((dispose) => dispose());
+ vi.useRealTimers();
+});
+
+it.each([false, true])(
+ 'suppresses a delivery flush acknowledgement until another edit (failure=%s)',
+ async (fails) => {
+ vi.useFakeTimers();
+ const persist = vi.fn(async () => {
+ if (fails) throw new Error('Delivery preparation failed');
+ });
+ const local = vi.fn(async () => {});
+ const autosave = createRoot((dispose) => {
+ disposers.push(dispose);
+ return createDraftAutosave({
+ capture: () => 'draft',
+ persist,
+ saveLocalSnapshot: local,
+ paused: () => false,
+ });
+ });
+ autosave.schedule();
+ await autosave.flushLocal();
+ const flush = autosave.save(undefined, { acknowledge: false });
+ expect(autosave.acknowledgeSaved()).toBe(false);
+ if (fails)
+ await expect(flush).rejects.toThrow('Delivery preparation failed');
+ else await flush;
+ expect(local).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(autosave.acknowledgeSaved()).toBe(false);
+ fails = false;
+ autosave.schedule();
+ await autosave.flushLocal();
+ expect(autosave.acknowledgeSaved()).toBe(false);
+ await vi.advanceTimersByTimeAsync(500);
+ expect(autosave.acknowledgeSaved()).toBe(true);
+ }
+);
+
+it('keeps input active through continuous edits without delaying local saves', async () => {
+ vi.useFakeTimers();
+ const local = vi.fn(async () => {});
+ const persist = vi.fn(async () => {});
+ const autosave = createRoot((dispose) => {
+ disposers.push(dispose);
+ return createDraftAutosave({
+ capture: () => 'draft',
+ saveLocalSnapshot: local,
+ persist,
+ paused: () => false,
+ });
+ });
+ for (let edit = 0; edit < 3; edit++) {
+ autosave.schedule();
+ await autosave.flushLocal();
+ expect(autosave.localSaveState()).toBe('saved');
+ expect(autosave.acknowledgeSaved()).toBe(false);
+ expect(local).toHaveBeenCalledTimes(edit + 1);
+ await vi.advanceTimersByTimeAsync(200);
+ expect(autosave.acknowledgeSaved()).toBe(false);
+ expect(persist).not.toHaveBeenCalled();
+ }
+ await vi.advanceTimersByTimeAsync(299);
+ expect(autosave.acknowledgeSaved()).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(autosave.acknowledgeSaved()).toBe(true);
+ await autosave.settled();
+ expect(persist).toHaveBeenCalledOnce();
+
+ autosave.schedule();
+ expect(autosave.acknowledgeSaved()).toBe(false);
+ autosave.cancel();
+ expect(autosave.acknowledgeSaved()).toBe(true);
+});
+
+it('distinguishes a typing pause from a slow local save', async () => {
+ vi.useFakeTimers();
+ const write = Promise.withResolvers<void>();
+ const autosave = createRoot((dispose) => {
+ disposers.push(dispose);
+ return createDraftAutosave({
+ capture: () => 'draft',
+ saveLocalSnapshot: async () => await write.promise,
+ persist: vi.fn(async () => {}),
+ paused: () => false,
+ });
+ });
+ autosave.schedule();
+ await vi.advanceTimersByTimeAsync(500);
+ expect(autosave.acknowledgeSaved()).toBe(true);
+ expect(autosave.localSaveState()).toBe('saving');
+ write.resolve();
+ await autosave.settled();
+ expect(autosave.localSaveState()).toBe('saved');
+});
+
+it('preserves the last edit when navigation disposes the thread supplying its snapshot', async () => {
+ vi.useFakeTimers();
+ const persist = vi.fn(
+ async (_snapshot: { body: string; thread?: string }) => {}
+ );
+ const saveLocalSnapshot = vi.fn(async () => {});
+ const cleaned = vi.fn();
+ let body = 'first';
+ const root = createRoot((dispose) => {
+ disposers.push(dispose);
+ const [route, navigate] = createSignal<string>();
+ const session = createMemo(() => {
+ const id = route();
+ if (!id) return;
+ onCleanup(cleaned);
+ return {
+ id,
+ autosave: createDraftAutosave({
+ capture: () => ({ body, thread: thread() }),
+ persist,
+ saveLocalSnapshot,
+ paused: () => false,
+ }),
+ };
+ });
+ const thread = createMemo((): string | undefined => session()?.id);
+ return { navigate, session };
+ });
+ root.navigate('original-thread');
+ const autosave = root.session()!.autosave;
+ autosave.schedule();
+ body = 'last-second edit';
+ autosave.schedule();
+ await autosave.flushLocal();
+ const localWrites = saveLocalSnapshot.mock.calls.length;
+
+ expect(() => root.navigate(undefined)).not.toThrow();
+ expect(root.session()).toBeUndefined();
+ expect(cleaned).toHaveBeenCalledOnce();
+ await autosave.settled();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(persist).toHaveBeenCalledExactlyOnceWith({
+ body: 'last-second edit',
+ thread: 'original-thread',
+ });
+ expect(saveLocalSnapshot).toHaveBeenCalledTimes(localWrites);
+});
+
+it('coalesces local snapshots behind a slow write and reports durability only after the newest completes', async () => {
+ vi.useFakeTimers();
+ const first = Promise.withResolvers<void>();
+ let current = 'first';
+ const writes: string[] = [];
+ const autosave = createRoot((dispose) => {
+ disposers.push(dispose);
+ return createDraftAutosave({
+ capture: () => current,
+ persist: vi.fn(async () => {}),
+ paused: () => false,
+ saveLocalSnapshot: async (snapshot) => {
+ writes.push(snapshot);
+ if (snapshot === 'first') await first.promise;
+ },
+ });
+ });
+ autosave.schedule();
+ await vi.advanceTimersByTimeAsync(0);
+ current = 'middle';
+ autosave.schedule();
+ current = 'latest';
+ autosave.schedule();
+ expect(autosave.localSaveState()).toBe('saving');
+ first.resolve();
+ await autosave.flushLocal();
+ expect(writes).toEqual(['first', 'latest']);
+ expect(autosave.localSaveState()).toBe('saved');
+ autosave.cancel();
+});
+
+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 = vi
+ .fn<(snapshot: string) => Promise<void>>()
+ .mockRejectedValueOnce(new Error('Disk full'))
+ .mockResolvedValue(undefined);
+ const autosave = createRoot((dispose) => {
+ disposers.push(dispose);
+ return createDraftAutosave({
+ capture: () => 'draft',
+ persist,
+ paused: () => false,
+ saveLocalSnapshot: local,
+ });
+ });
+ await expect(autosave.save()).rejects.toThrow('Disk full');
+ expect(autosave.localSaveState()).toBe('failed');
+ expect(persist).not.toHaveBeenCalled();
+ await autosave.save();
+ expect(autosave.localSaveState()).toBe('saved');
+ expect(persist).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/features/email-compose/primitives/draft-autosave.ts b/apps/web/src/features/email-compose/primitives/draft-autosave.ts
index 40249ebd01..7e87e441f1 100644
--- a/apps/web/src/features/email-compose/primitives/draft-autosave.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-autosave.ts
@@ -1,41 +1,106 @@
import { debounce } from '@solid-primitives/scheduled';
-import { onCleanup } from 'solid-js';
+import { createSignal, onCleanup } from 'solid-js';
/** Capture live editor values before queuing; each write sees the preceding draft ID. */
export function createDraftAutosave<Snapshot, Result>(options: {
capture(): Snapshot;
persist(snapshot: Snapshot): Promise<Result>;
+ /** Runs immediately on edits; network debounce never delays local durability. */
+ saveLocalSnapshot?(snapshot: Snapshot): Promise<void>;
paused(): boolean;
onError?(error: unknown): void;
+ onLocalError?(error: unknown): void;
+ onLocalSaved?(): void;
}) {
- let pending = false;
+ let pending: { snapshot: Snapshot } | undefined;
let queue: Promise<Result | undefined> = Promise.resolve(undefined);
+ let localWrites: Promise<void> = Promise.resolve();
+ let newestSnapshot = 0;
+ const [inputIdle, setInputIdle] = createSignal(true);
+ const [shouldAcknowledge, setShouldAcknowledge] = createSignal(true);
+ const [localSaveState, setLocalSaveState] = createSignal<
+ 'saving' | 'saved' | 'failed'
+ >('saved');
+ const flushLocal = async () => {
+ for (;;) {
+ const pending = localWrites;
+ await pending;
+ if (pending === localWrites) return;
+ }
+ };
+ const saveLocally = (snapshot: Snapshot) => {
+ const revision = ++newestSnapshot;
+ setLocalSaveState('saving');
+ const writeNewestSnapshot = async () => {
+ // Coalesce snapshots waiting behind a slow file write. An already
+ // running write finishes before the newest snapshot can replace it.
+ if (revision !== newestSnapshot) return;
+ try {
+ await options.saveLocalSnapshot?.(snapshot);
+ if (revision === newestSnapshot) {
+ setLocalSaveState('saved');
+ options.onLocalSaved?.();
+ }
+ } catch (error) {
+ if (revision === newestSnapshot) setLocalSaveState('failed');
+ options.onLocalError?.(error);
+ throw error;
+ }
+ };
+ // A failed disk write must not prevent the next edit from trying again.
+ localWrites = localWrites.then(writeNewestSnapshot, writeNewestSnapshot);
+ return flushLocal();
+ };
const cancel = () => {
scheduled.clear();
- pending = false;
+ pending = undefined;
+ setInputIdle(true);
};
- const save = (snapshot = options.capture()) => {
- cancel();
- const write = () => options.persist(snapshot);
+ const enqueue = (snapshot: Snapshot, local: Promise<void>) => {
+ const write = async () => {
+ await local;
+ return await options.persist(snapshot);
+ };
queue = queue.then(write, write);
return queue;
};
+ const save = (
+ snapshot = options.capture(),
+ saveOptions: { acknowledge?: boolean } = {}
+ ) => {
+ setShouldAcknowledge(saveOptions.acknowledge !== false);
+ cancel();
+ return enqueue(snapshot, saveLocally(snapshot));
+ };
const scheduled = debounce(() => {
+ setInputIdle(true);
if (options.paused()) return;
void save().catch((error) => options.onError?.(error));
}, 500);
onCleanup(() => {
- const flush = pending && !options.paused();
+ const flush = pending;
cancel();
- if (flush) void save().catch((error) => options.onError?.(error));
+ // 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.
+ if (flush && !options.paused())
+ void enqueue(flush.snapshot, flushLocal()).catch((error) =>
+ options.onError?.(error)
+ );
});
return {
save,
cancel,
settled: () => queue,
+ flushLocal,
+ localSaveState,
+ acknowledgeSaved: () => inputIdle() && shouldAcknowledge(),
schedule() {
if (options.paused()) return;
- pending = true;
+ setShouldAcknowledge(true);
+ setInputIdle(false);
+ const snapshot = options.capture();
+ pending = { snapshot };
+ void saveLocally(snapshot).catch((error) => options.onError?.(error));
scheduled();
},
};
diff --git a/apps/web/src/features/email-compose/primitives/draft-identity.test.ts b/apps/web/src/features/email-compose/primitives/draft-identity.test.ts
index ddd0bb0bde..efcb86671f 100644
--- a/apps/web/src/features/email-compose/primitives/draft-identity.test.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-identity.test.ts
@@ -19,7 +19,8 @@ function mount(
draftId: 'local',
threadId: 'local-thread',
persistence: 'queued',
- }
+ },
+ durableRecovery = false
) {
let changed!: (settlement?: Settlement) => void;
const unsubscribe = vi.fn();
@@ -33,6 +34,7 @@ function mount(
{
...createComposeContext().drafts,
readDraft,
+ retryDraft: durableRecovery ? vi.fn() : undefined,
watchDrafts: (callback) => {
changed = callback;
return unsubscribe;
@@ -256,6 +258,26 @@ it('offers one explicit recovery and dismisses it when the session resets', asyn
}
});
+it('leaves durable draft recovery in the toolbar without a duplicate retry toast', async () => {
+ const root = mount(
+ async () => ({
+ draft: message('local'),
+ persistence: 'queued',
+ mutationUuid: 'local',
+ }),
+ undefined,
+ true
+ );
+ try {
+ root.changed({ mutationUuid: 'local', failed: true });
+ await vi.waitFor(() => expect(root.session.autosaveAllowed()).toBe(false));
+ expect(root.notices.feedback.failure).not.toHaveBeenCalled();
+ expect(root.report).toHaveBeenCalledOnce();
+ } finally {
+ root.dispose();
+ }
+});
+
it('dismisses recovery on disposal and ignores its stale action', async () => {
const root = mount(async () => ({
draft: message('local'),
diff --git a/apps/web/src/features/email-compose/primitives/draft-identity.ts b/apps/web/src/features/email-compose/primitives/draft-identity.ts
index c3165dbdb4..f4a419d39d 100644
--- a/apps/web/src/features/email-compose/primitives/draft-identity.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-identity.ts
@@ -24,7 +24,8 @@ export function observeDraftIdentity(
session,
notices,
recover,
- onAlreadySent
+ onAlreadySent,
+ !!storage.retryDraft
);
}
)
@@ -37,7 +38,8 @@ function observeAvailableDraftIdentity(
session: DraftSession,
notices: Pick<EmailComposeFeedback, 'feedback' | 'reportError'>,
recover: () => void,
- onAlreadySent: () => void
+ onAlreadySent: () => void,
+ durableRecovery: boolean
) {
let generation = 0;
let mutationUuid: string | undefined;
@@ -56,7 +58,7 @@ function observeAvailableDraftIdentity(
const epoch = session.epoch();
const request = ++generation;
try {
- const result = await read(draftId);
+ const result = await read(draftId, { attachments: false });
if (
!result ||
disposed ||
@@ -66,6 +68,12 @@ function observeAvailableDraftIdentity(
)
return;
mutationUuid = result.mutationUuid ?? mutationUuid;
+ if (
+ result.local &&
+ ['failed', 'unconfirmed', 'delete-failed'].includes(result.local.status)
+ ) {
+ session.dispatch({ type: 'rejected', epoch, code: 'INTERNAL' });
+ }
if (!result.draft) return;
const current = session.identity();
if (
@@ -126,6 +134,8 @@ function observeAvailableDraftIdentity(
notices.reportError(
new Error('The server rejected the queued draft save')
);
+ // Durable drafts expose recovery beside the composer actions.
+ if (durableRecovery) return;
rejectionNotice = notices.feedback.failure('Draft could not be saved', {
subtext:
'Your edits are still in this editor. Save them as a new draft before closing.',
diff --git a/apps/web/src/features/email-compose/primitives/draft-persistence.ts b/apps/web/src/features/email-compose/primitives/draft-persistence.ts
index 9c9cdbed51..d6b7310b08 100644
--- a/apps/web/src/features/email-compose/primitives/draft-persistence.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-persistence.ts
@@ -7,7 +7,9 @@ import {
type EmailDraftStorage,
} from '../context/compose-capabilities';
import type { EmailDraft } from '../core/email-draft';
+import type { LocalDraft } from '../core/local-draft';
import type { DraftSession } from './draft-session';
+import type { DraftFormAttachment } from './email-form-state';
/** Sent from another device: the server outcome supersedes the local draft. */
export const isAlreadySentRejection = (error: unknown) =>
@@ -48,7 +50,10 @@ export async function deleteDraftForDiscard(
*/
export function createDraftPersistence(options: {
session: DraftSession;
- drafts: Pick<EmailDraftStorage, 'saveDraft' | 'deleteDraft'>;
+ drafts: Pick<
+ EmailDraftStorage,
+ 'saveDraft' | 'deleteDraft' | 'saveLocalDraft' | 'retryDraft' | 'readDraft'
+ >;
attachments: {
upload(
draftId: string,
@@ -57,9 +62,24 @@ export function createDraftPersistence(options: {
};
/** A standalone compose mints its thread handle too; a reply saves into a known thread. */
mintThreadHandle: boolean;
+ localDraft?: Pick<LocalDraft, 'revision' | 'generation'>;
onAlreadySent(): void;
}) {
const { session } = options;
+ let localRevision = options.localDraft?.revision;
+ let localGeneration = options.localDraft?.generation;
+ const mint = (draft: EmailDraft) => {
+ if (session.draftId()) return;
+ localRevision = undefined;
+ localGeneration = undefined;
+ session.dispatch({
+ type: 'minted',
+ draftId: uuidv7(),
+ threadId: options.mintThreadHandle
+ ? uuidv7()
+ : (draft.thread_db_id ?? undefined),
+ });
+ };
// The session records deterministic rejections (latch, or drop on
// already-sent); transport failures just reject and the next save may retry.
@@ -71,6 +91,63 @@ export function createDraftPersistence(options: {
};
return {
+ async saveLocally(input: {
+ draft: EmailDraft | null;
+ inboxId?: string;
+ attachments: readonly DraftFormAttachment[];
+ }) {
+ if (!options.drafts.saveLocalDraft) return;
+ // Preserve an emptied working copy too; a failed delete must not restore
+ // the earlier body on reload. An untouched composer has no identity.
+ if (!input.draft && !session.draftId()) return;
+ const draft = input.draft ?? {
+ subject: '',
+ to: [],
+ cc: [],
+ bcc: [],
+ body_html: '',
+ };
+ mint(draft);
+ const identity = session.identity();
+ if (identity.kind === 'none') return;
+ const epoch = session.epoch();
+ const local = await options.drafts.saveLocalDraft({
+ expectedRevision: localRevision,
+ expectedGeneration: localGeneration,
+ draft: {
+ ...draft,
+ db_id: identity.kind === 'server' ? identity.draftId : undefined,
+ },
+ clientHandles:
+ identity.kind === 'handle'
+ ? { draftId: identity.draftId, threadId: identity.threadId }
+ : undefined,
+ inboxId: input.inboxId,
+ attachments: input.attachments,
+ });
+ if (!session.isStale(epoch)) {
+ localRevision = local.revision;
+ localGeneration = local.generation;
+ }
+ },
+ async retry() {
+ const id = session.draftId();
+ if (!id || !options.drafts.retryDraft) return;
+ const latest = await options.drafts.readDraft?.(id, {
+ attachments: false,
+ });
+ if (
+ latest?.local &&
+ (latest.local.revision !== localRevision ||
+ latest.local.generation !== localGeneration)
+ ) {
+ throw new Error(
+ 'This draft changed in another tab. Reopen it to retry the latest version.'
+ );
+ }
+ await options.drafts.retryDraft(id);
+ session.dispatch({ type: 'retry' });
+ },
/** The draft has no content left: delete its row and drop its identity. */
async remove(input: { inboxId?: string; completingThread?: boolean }) {
const draftId = session.draftId();
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.ts
new file mode 100644
index 0000000000..6749a84720
--- /dev/null
+++ b/apps/web/src/features/email-compose/primitives/draft-save-notice.ts
@@ -0,0 +1,31 @@
+import { onCleanup } from 'solid-js';
+import type { EmailComposeFeedback } from '../context/compose-capabilities';
+
+/** One warning per local-save failure episode, shared by both composers. */
+export function createDraftSaveNotice(
+ feedback: EmailComposeFeedback['feedback']
+) {
+ let failed = false;
+ let notice: number | undefined;
+ let disposed = false;
+ const clear = () => {
+ if (notice !== undefined) feedback.dismiss(notice);
+ notice = undefined;
+ failed = false;
+ };
+ onCleanup(() => {
+ disposed = true;
+ clear();
+ });
+ return {
+ onLocalError(error: unknown) {
+ if (disposed || failed) return;
+ failed = true;
+ notice = feedback.failure('Draft could not be saved on this device', {
+ subtext: String(error),
+ persistent: true,
+ });
+ },
+ onLocalSaved: clear,
+ };
+}
diff --git a/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts b/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts
index 8887a08a5f..1df820dbb1 100644
--- a/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts
@@ -40,7 +40,9 @@ describe('draft session: reply composer', () => {
try {
await vi.advanceTimersByTimeAsync(0);
await state.sendEmail();
- expect(context.drafts.readDraft).toHaveBeenCalledWith('existing');
+ expect(context.drafts.readDraft).toHaveBeenCalledWith('existing', {
+ attachments: false,
+ });
expect(context.drafts.saveDraft).toHaveBeenCalledWith(
expect.objectContaining({
clientHandles: expect.objectContaining({ draftId: 'existing' }),
@@ -100,7 +102,9 @@ describe('draft session: reply composer', () => {
const state = mountReplyComposer(context, undefined, { draft });
try {
await vi.advanceTimersByTimeAsync(0);
- expect(context.drafts.readDraft).toHaveBeenCalledWith('existing');
+ expect(context.drafts.readDraft).toHaveBeenCalledWith('existing', {
+ attachments: false,
+ });
await state.sendEmail();
expect(context.delivery.sendMessage).not.toHaveBeenCalled();
expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(
diff --git a/apps/web/src/features/email-compose/primitives/draft-session.ts b/apps/web/src/features/email-compose/primitives/draft-session.ts
index b6d853b122..510ad3084c 100644
--- a/apps/web/src/features/email-compose/primitives/draft-session.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-session.ts
@@ -76,6 +76,7 @@ export type DraftSessionEvent =
| { type: 'rejected'; epoch: number; code: DraftPersistFailureCode }
/** An authoritative cancellation makes a schedule-locked draft editable. */
| { type: 'schedule-cancelled' }
+ | { type: 'retry' }
/** The draft has no content left; its row was (or is being) deleted. */
| { type: 'emptied' }
/** The composer dropped its draft: sent, discarded, or superseded. */
@@ -171,6 +172,10 @@ export function reduceDraftSession(
}
return { ...state, policy: { kind: 'latched', code: event.code } };
})
+ .with({ type: 'retry' }, () => ({
+ ...state,
+ policy: { kind: 'autosaving' as const },
+ }))
.with({ type: 'schedule-cancelled' }, () => {
if (state.policy.kind !== 'latched' || state.policy.code !== 'INVALID')
return state;
diff --git a/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts b/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts
new file mode 100644
index 0000000000..dedc823968
--- /dev/null
+++ b/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts
@@ -0,0 +1,162 @@
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import type { LocalDraft } from '../core/local-draft';
+import { createComposeContext } from '../tests/capabilities';
+import { createDraftSyncStatus } from './draft-sync-status';
+
+const disposers: (() => void)[] = [];
+afterEach(() => disposers.splice(0).forEach((dispose) => dispose()));
+const draft: LocalDraft = {
+ key: 'draft',
+ accountId: 'owner',
+ generation: 'generation',
+ draftId: 'draft',
+ revision: 1,
+ acknowledgedRevision: 0,
+ content: { subject: 'Keep this' },
+ attachments: [],
+ status: 'deleting',
+ updatedAt: 1,
+ latestAttemptId: 'delete',
+ queuedAttemptId: 'old-save',
+};
+
+it('offers retry discard when a crash interrupted deletion before admission', async () => {
+ const context = createComposeContext();
+ context.drafts.saveLocalDraft = vi.fn();
+ context.drafts.readDraft = vi.fn(async () => ({
+ local: draft,
+ persistence: 'queued' as const,
+ }));
+ const discard = vi.fn(async () => {});
+ const status = createRoot((dispose) => {
+ disposers.push(dispose);
+ return createDraftSyncStatus({
+ drafts: context.drafts,
+ draftId: () => 'draft',
+ localSaveState: () => 'saved',
+ acknowledgeSaved: () => true,
+ retry: vi.fn(),
+ discard,
+ });
+ });
+ expect(status.state()).toBeUndefined();
+ await vi.waitFor(() => expect(status.state()?.action).toBe('retry-discard'));
+ expect(context.drafts.readDraft).toHaveBeenCalledWith('draft', {
+ attachments: false,
+ });
+ status.retry();
+ await vi.waitFor(() => expect(discard).toHaveBeenCalledOnce());
+});
+
+it('shows a failed status read without throwing into the composer error boundary', async () => {
+ const context = createComposeContext();
+ context.drafts.saveLocalDraft = vi.fn();
+ context.drafts.readDraft = vi.fn(async () => {
+ throw new Error('Disk unavailable');
+ });
+ const status = createRoot((dispose) => {
+ disposers.push(dispose);
+ return createDraftSyncStatus({
+ drafts: context.drafts,
+ draftId: () => 'draft',
+ localSaveState: () => 'saved',
+ acknowledgeSaved: () => true,
+ retry: vi.fn(),
+ discard: vi.fn(),
+ });
+ });
+ await vi.waitFor(() =>
+ expect(status.state()?.message).toBe('Unable to read local draft status.')
+ );
+ expect(status.state()?.failed).toBe(true);
+});
+
+it('acknowledges saved edits only after input pauses and stays stable through background sync', async () => {
+ const context = createComposeContext();
+ const [local, setLocal] = createSignal<LocalDraft | undefined>();
+ const [disk, setDisk] = createSignal<'saving' | 'saved' | 'failed'>('saving');
+ const [inputIdle, setInputIdle] = createSignal(false);
+ let changed = () => {};
+ context.drafts.saveLocalDraft = vi.fn();
+ context.drafts.readDraft = vi.fn(async () => ({
+ local: local(),
+ persistence: 'queued' as const,
+ }));
+ context.drafts.watchDrafts = (callback) => {
+ changed = callback;
+ return () => {};
+ };
+ const retry = vi.fn(async () => {});
+ const status = createRoot((dispose) => {
+ disposers.push(dispose);
+ return createDraftSyncStatus({
+ drafts: context.drafts,
+ draftId: () => 'draft',
+ localSaveState: disk,
+ acknowledgeSaved: inputIdle,
+ retry,
+ discard: vi.fn(),
+ });
+ });
+ await vi.waitFor(() => expect(context.drafts.readDraft).toHaveBeenCalled());
+ expect(status.state()).toBeUndefined();
+ for (const phase of [
+ 'dirty',
+ 'queued',
+ 'synced',
+ 'dirty',
+ 'queued',
+ 'synced',
+ ] as const) {
+ setLocal({ ...draft, status: phase });
+ changed();
+ setDisk('saved');
+ await vi.waitFor(() => expect(status.state()?.message).toBe('Draft saved'));
+ expect(status.state()?.savedVersion).toBeUndefined();
+ setInputIdle(true);
+ const version = status.state()?.savedVersion;
+ expect(version).toBe('generation:1');
+ changed();
+ await vi.waitFor(() => expect(status.state()?.savedVersion).toBe(version));
+ setDisk('saving');
+ expect(status.state()?.savedVersion).toBeUndefined();
+ setDisk('saved');
+ expect(status.state()?.savedVersion).toBe(version);
+ setInputIdle(false);
+ expect(status.state()?.savedVersion).toBeUndefined();
+ setDisk('saving');
+ expect(status.state()).toMatchObject({
+ message: 'Draft saved',
+ failed: false,
+ });
+ expect(status.state()?.action).toBeUndefined();
+ }
+ setDisk('failed');
+ expect(status.state()).toMatchObject({ failed: true, action: 'retry' });
+ status.retry();
+ await vi.waitFor(() => expect(retry).toHaveBeenCalledOnce());
+});
+
+it('offers retry for server failures while newer edits remain saved locally', async () => {
+ const context = createComposeContext();
+ context.drafts.saveLocalDraft = vi.fn();
+ context.drafts.readDraft = vi.fn(async () => ({
+ local: { ...draft, status: 'failed' as const },
+ persistence: 'queued' as const,
+ }));
+ const status = createRoot((dispose) => {
+ disposers.push(dispose);
+ return createDraftSyncStatus({
+ drafts: context.drafts,
+ draftId: () => 'draft',
+ localSaveState: () => 'saving',
+ acknowledgeSaved: () => false,
+ retry: vi.fn(),
+ discard: vi.fn(),
+ });
+ });
+ await vi.waitFor(() =>
+ expect(status.state()).toMatchObject({ failed: true, action: 'retry' })
+ );
+});
diff --git a/apps/web/src/features/email-compose/primitives/draft-sync-status.ts b/apps/web/src/features/email-compose/primitives/draft-sync-status.ts
new file mode 100644
index 0000000000..885af92abe
--- /dev/null
+++ b/apps/web/src/features/email-compose/primitives/draft-sync-status.ts
@@ -0,0 +1,134 @@
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createResource,
+ createSignal,
+ onCleanup,
+} from 'solid-js';
+import type { EmailDraftStorage } from '../context/compose-capabilities';
+import type { DraftSyncViewState } from '../core/local-draft';
+
+/** Recovery reads only metadata; file blobs are restored once when opening a draft. */
+export function createDraftSyncStatus(options: {
+ drafts: EmailDraftStorage;
+ draftId: Accessor<string | undefined>;
+ localSaveState: Accessor<'saving' | 'saved' | 'failed'>;
+ acknowledgeSaved: Accessor<boolean>;
+ retry(): Promise<unknown>;
+ discard(): Promise<unknown>;
+}) {
+ const [busy, setBusy] = createSignal(false);
+ const [actionError, setActionError] = createSignal<string>();
+ const [saved, { refetch }] = createResource(
+ () => options.drafts.readDraft && options.draftId(),
+ async (id) => await options.drafts.readDraft!(id, { attachments: false })
+ );
+ createEffect(() => {
+ const unsubscribe = options.drafts.watchDrafts?.(() => {
+ void refetch();
+ });
+ onCleanup(() => unsubscribe?.());
+ });
+ const local = () =>
+ saved.state === 'ready' || saved.state === 'refreshing'
+ ? saved.latest?.local
+ : undefined;
+ const deletePending = () =>
+ local()?.status === 'delete-failed' ||
+ (local()?.status === 'deleting' &&
+ (!local()?.queuedAttemptId ||
+ local()?.queuedAttemptId !== local()?.latestAttemptId));
+ const state = createMemo<DraftSyncViewState | undefined>((previous) => {
+ if (!options.drafts.saveLocalDraft || !options.draftId()) return;
+ const disk = options.localSaveState();
+ const draft = local();
+ if (saved.error)
+ return {
+ message: 'Unable to read local draft status.',
+ detail: 'Retry to check the saved draft.',
+ failed: true,
+ action: 'retry',
+ canKeepEditing: false,
+ };
+ const failed =
+ disk === 'failed' ||
+ ['failed', 'unconfirmed', 'delete-failed'].includes(
+ draft?.status ?? ''
+ ) ||
+ deletePending();
+ // Only a newly persisted version restarts the brief acknowledgement.
+ // Queue notifications and identity adoption do not count as another save.
+ if (!failed) {
+ if (!draft && (disk === 'saving' || saved.loading))
+ return previous && { ...previous, savedVersion: undefined };
+ if (!draft && !saved.latest?.draft) return;
+ return {
+ message: 'Draft saved',
+ savedVersion:
+ disk === 'saved' && options.acknowledgeSaved()
+ ? draft
+ ? `${draft.generation}:${draft.revision}`
+ : saved.latest?.draft?.updated_at
+ : undefined,
+ failed: false,
+ canKeepEditing: false,
+ };
+ }
+ return {
+ message:
+ disk === 'failed'
+ ? 'Changes could not be saved on this device'
+ : 'Draft could not be synced',
+ detail:
+ disk === 'failed'
+ ? 'Keep this editor open until saving succeeds.'
+ : deletePending()
+ ? 'Discard could not be confirmed.'
+ : draft?.status === 'unconfirmed'
+ ? 'The last save could not be confirmed.'
+ : draft?.status === 'failed'
+ ? 'The server could not save this draft.'
+ : undefined,
+ failed,
+ action: deletePending() ? 'retry-discard' : 'retry',
+ canKeepEditing: deletePending(),
+ };
+ });
+ const run = async (action: () => Promise<unknown>) => {
+ if (busy()) return;
+ setBusy(true);
+ setActionError(undefined);
+ try {
+ await action();
+ await refetch();
+ } catch (error) {
+ setActionError(error instanceof Error ? error.message : String(error));
+ } finally {
+ setBusy(false);
+ }
+ };
+ return {
+ state,
+ busy,
+ error: () =>
+ actionError() ??
+ (saved.error
+ ? 'Unable to read local draft status. Retry to check the saved draft.'
+ : undefined),
+ retry: () => {
+ void run(
+ saved.error
+ ? async () => {
+ await refetch();
+ }
+ : deletePending()
+ ? options.discard
+ : options.retry
+ );
+ },
+ keepEditing: () => {
+ void run(options.retry);
+ },
+ };
+}
diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.ts
index 761d0f7ff1..65a8cc390c 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts
@@ -58,6 +58,7 @@ import {
createDraftPersistence,
deleteDraftForDiscard,
} from './draft-persistence';
+import { createDraftSaveNotice } from './draft-save-notice';
import { createDraftSession } from './draft-session';
import { createEmailSendSchedule } from './email-send-schedule';
import {
@@ -99,6 +100,8 @@ export type EmailComposerOptions = {
recipientName(id: string): string;
host?: EmailComposeHost;
draft?: EmailMessage;
+ localDraft?: import('../core/local-draft').LocalDraft;
+ localAttachments?: DraftFormAttachment[];
/** Identity for a composer reopened from a local undo snapshot. */
draftId?: string;
draftPersistence?: 'committed' | 'queued';
@@ -140,6 +143,11 @@ export function createEmailComposer(props: EmailComposerOptions) {
form.setSelectedInbox(props.initialInboxId);
}
+ if (props.localAttachments) {
+ form.attachments.clear();
+ for (const attachment of props.localAttachments)
+ form.attachments.add(attachment);
+ }
const primaryInboxId = props.accounts.primaryId;
const link = createMemo(() => {
const inboxes = props.accounts.inboxes();
@@ -183,6 +191,15 @@ export function createEmailComposer(props: EmailComposerOptions) {
}
: undefined
);
+ if (
+ props.localDraft &&
+ ['failed', 'unconfirmed', 'delete-failed'].includes(props.localDraft.status)
+ )
+ session.dispatch({
+ type: 'rejected',
+ epoch: session.epoch(),
+ code: 'INTERNAL',
+ });
const currentDraftId = session.draftId;
const currentThreadId = session.threadId;
observeDraftIdentity(
@@ -191,7 +208,9 @@ export function createEmailComposer(props: EmailComposerOptions) {
props.notices,
() => {
if (persistencePaused()) return;
- detachFromObsoleteDraft('Saving your edits as a new draft.');
+ if (props.drafts.retryDraft) {
+ void retryDraft().catch(props.notices.reportError);
+ } else detachFromObsoleteDraft('Saving your edits as a new draft.');
},
handleAlreadySent
);
@@ -207,9 +226,11 @@ export function createEmailComposer(props: EmailComposerOptions) {
});
const attachmentPersistence = createAttachmentPersistence({
+ confirmRemoval: !!props.drafts.saveLocalDraft,
services: props.attachmentStorage,
attachments: form.attachments,
- draftId: () => (session.serverConfirmed() ? currentDraftId() : undefined),
+ draftId: () =>
+ session.identity().kind === 'server' ? currentDraftId() : undefined,
inboxId: persistedInboxId,
});
@@ -331,6 +352,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
session,
drafts: props.drafts,
attachments: attachmentPersistence,
+ localDraft: props.localDraft,
mintThreadHandle: true,
onAlreadySent: handleAlreadySent,
});
@@ -345,6 +367,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
inboxId: string | undefined;
generation: number;
revision: number;
+ attachments: readonly DraftFormAttachment[];
}) {
if (generation !== identityVersion) return;
try {
@@ -389,13 +412,23 @@ export function createEmailComposer(props: EmailComposerOptions) {
schedule?.state().type === 'scheduled';
const autosave = createDraftAutosave({
+ ...createDraftSaveNotice(props.notices.feedback),
capture: () => ({
draft: collectDraft(),
inboxId: activeInboxId(),
generation: identityVersion,
revision: editVersion,
+ attachments: [...form.attachments.list()],
}),
persist: persistDraft,
+ saveLocalSnapshot: async (snapshot) => {
+ if (snapshot.generation !== identityVersion) return;
+ await persistence.saveLocally({
+ draft: snapshot.draft,
+ inboxId: snapshot.inboxId,
+ attachments: snapshot.attachments,
+ });
+ },
paused: persistencePaused,
});
@@ -407,12 +440,16 @@ export function createEmailComposer(props: EmailComposerOptions) {
);
try {
return persistence.confirmed(
- await autosave.save({
- draft: collectDraft(true),
- inboxId: activeInboxId(),
- generation: identityVersion,
- revision: editVersion,
- })
+ await autosave.save(
+ {
+ draft: collectDraft(true),
+ inboxId: activeInboxId(),
+ generation: identityVersion,
+ revision: editVersion,
+ attachments: [...form.attachments.list()],
+ },
+ { acknowledge: false }
+ )
);
} finally {
cleanupWatermark();
@@ -464,7 +501,10 @@ export function createEmailComposer(props: EmailComposerOptions) {
const handleAddAttachments = async (attachments: DraftFormAttachment[]) => {
if (persistencePaused()) return;
- if (await refuseAttachmentsOffline(props.connectivity, props.notices))
+ if (
+ !props.drafts.saveLocalDraft &&
+ (await refuseAttachmentsOffline(props.connectivity, props.notices))
+ )
return;
for (const attachment of attachments) {
form.attachments.add(attachment);
@@ -472,11 +512,14 @@ export function createEmailComposer(props: EmailComposerOptions) {
markDirtyAndScheduleSave();
};
- const handleRemoveAttachment = (attachment: DraftFormAttachment) => {
+ const handleRemoveAttachment = async (attachment: DraftFormAttachment) => {
if (persistencePaused()) return;
- editVersion += 1;
- setDraftDirty(true);
- attachmentPersistence.remove(attachment);
+ try {
+ if (!(await attachmentPersistence.remove(attachment))) return;
+ markDirtyAndScheduleSave();
+ } catch (error) {
+ props.notices.reportError(error);
+ }
};
// --- Content change ---
@@ -591,6 +634,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
const onSubmit = async () => {
if (
+ attachmentPersistence.removing() ||
schedule.pending() ||
submitting() ||
discarding() ||
@@ -667,10 +711,9 @@ export function createEmailComposer(props: EmailComposerOptions) {
try {
// Ensure the draft is saved before sending so undo-send always has a
// draft id to snapshot and restore (the send reuses the draft's db_id).
- autosave.cancel();
const epochBeforeSave = session.epoch();
try {
- await autosave.save();
+ await autosave.save(undefined, { acknowledge: false });
} catch {
// Draft save is best-effort; the send still works without one.
}
@@ -755,7 +798,11 @@ export function createEmailComposer(props: EmailComposerOptions) {
const scheduling = schedule.pending;
const scheduleBlocked = () =>
- submitting() || discarding() || movingInbox() || completed();
+ attachmentPersistence.removing() ||
+ submitting() ||
+ discarding() ||
+ movingInbox() ||
+ completed();
const handleSendTimeChange = (date: Date | null) => {
if (scheduleBlocked()) return false;
return schedule.select(date);
@@ -786,6 +833,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
// A first save may still be creating the draft. Delete its returned ID
// after it settles so discard cannot leave an orphan behind.
await autosave.settled().catch(() => {});
+ await autosave.flushLocal().catch(props.notices.reportError);
const draftId = currentDraftId();
if (draftId) {
try {
@@ -1108,7 +1156,20 @@ export function createEmailComposer(props: EmailComposerOptions) {
},
hasPaidAccess,
};
+ async function retryDraft() {
+ if (persistencePaused()) return;
+ // Finish this editor's last write before checking the shared revision.
+ await autosave.flushLocal().catch(props.notices.reportError);
+ await persistence.retry();
+ await autosave.save();
+ }
+
return {
+ draftId: currentDraftId,
+ retryDraft,
+ flushLocal: autosave.flushLocal,
+ localSaveState: autosave.localSaveState,
+ acknowledgeSaved: autosave.acknowledgeSaved,
context: ctxValue,
editor,
previewName,
diff --git a/apps/web/src/features/email-compose/primitives/email-form-state.ts b/apps/web/src/features/email-compose/primitives/email-form-state.ts
index 8dd93817b5..7cb272d6c1 100644
--- a/apps/web/src/features/email-compose/primitives/email-form-state.ts
+++ b/apps/web/src/features/email-compose/primitives/email-form-state.ts
@@ -22,6 +22,9 @@ export type DraftFormAttachment =
type: 'local';
file: File;
attachmentId?: string;
+ /** Restored after interruption: remove the uncertain record before re-uploading. */
+ uploadPending?: boolean;
+ uploaded?: boolean;
}
| {
type: 'remote';
@@ -280,6 +283,7 @@ export function createEmailFormState(
reset: () => reset(getInitialState()),
clear: () => reset({ ...EMPTY_FORM_STATE }),
attachments: {
+ clear: () => setAttachments([]),
list: attachments,
add: (attachment: DraftFormAttachment) => {
setAttachments((p) => [...p, attachment]);
@@ -291,11 +295,30 @@ export function createEmailFormState(
)
);
},
+ markAttachmentUploaded: (file: File, attachmentId: string) => {
+ setAttachments((previous) =>
+ previous.map((attachment) =>
+ attachment.type === 'local' && attachment.file === file
+ ? {
+ ...attachment,
+ attachmentId,
+ uploadPending: false,
+ uploaded: true,
+ }
+ : attachment
+ )
+ );
+ },
clearAttachmentId: (file: File) => {
setAttachments((p) =>
p.map((a) =>
a.type === 'local' && a.file === file
- ? { ...a, attachmentId: undefined }
+ ? {
+ ...a,
+ attachmentId: undefined,
+ uploadPending: false,
+ uploaded: false,
+ }
: a
)
);
diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.ts
index 05d86658a4..80668503f5 100644
--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts
@@ -52,6 +52,7 @@ import {
createDraftPersistence,
deleteDraftForDiscard,
} from './draft-persistence';
+import { createDraftSaveNotice } from './draft-save-notice';
import { createDraftSession } from './draft-session';
import type { DraftFormAttachment } from './email-form-state';
import type { EmailFormContextValue, FormAccessKey } from './email-form-types';
@@ -110,6 +111,8 @@ export type ReplyComposerOptions = {
replyingTo: Accessor<EmailMessage | undefined>;
isEditingExisting?: boolean;
draft?: EmailMessage;
+ localDraft?: import('../core/local-draft').LocalDraft;
+ localAttachments?: DraftFormAttachment[];
preloadedHtml?: string;
/** Seed identity of the draft this composer mounted from — becomes part of
* the form-state cache key so a remount on a newer draft version gets a
@@ -263,6 +266,20 @@ export function createReplyComposer(
}
: undefined
);
+ if (props.localAttachments) {
+ form.attachments.clear();
+ for (const attachment of props.localAttachments)
+ form.attachments.add(attachment);
+ }
+ if (
+ props.localDraft &&
+ ['failed', 'unconfirmed', 'delete-failed'].includes(props.localDraft.status)
+ )
+ session.dispatch({
+ type: 'rejected',
+ epoch: session.epoch(),
+ code: 'INTERNAL',
+ });
const savedDraftId = session.draftId;
const savedDraftThreadId = session.threadId;
observeDraftIdentity(
@@ -271,7 +288,9 @@ export function createReplyComposer(
props.notices,
() => {
if (scheduleBlocked() || schedule.state().type === 'scheduled') return;
- detachFromObsoleteDraft('Saving your edits as a new draft.');
+ if (props.drafts.retryDraft) {
+ void retryDraft().catch(props.notices.reportError);
+ } else detachFromObsoleteDraft('Saving your edits as a new draft.');
},
handleAlreadySent
);
@@ -408,9 +427,11 @@ export function createReplyComposer(
};
const attachmentPersistence = createAttachmentPersistence({
+ confirmRemoval: !!props.drafts.saveLocalDraft,
services: props.attachmentStorage,
attachments: form.attachments,
- draftId: () => (session.serverConfirmed() ? savedDraftId() : undefined),
+ draftId: () =>
+ session.identity().kind === 'server' ? savedDraftId() : undefined,
inboxId: persistedInboxId,
});
@@ -505,6 +526,7 @@ export function createReplyComposer(
completingThread,
generation: identityVersion,
revision: editVersion,
+ attachments: [...form.attachments.list()],
});
async function reportPersistenceFailure(
@@ -566,6 +588,7 @@ export function createReplyComposer(
session,
drafts: props.drafts,
attachments: attachmentPersistence,
+ localDraft: props.localDraft,
mintThreadHandle: false,
onAlreadySent: handleAlreadySent,
});
@@ -613,8 +636,23 @@ export function createReplyComposer(
}
const autosave = createDraftAutosave({
+ ...createDraftSaveNotice(props.notices.feedback),
capture: captureSave,
persist: persistDraft,
+ saveLocalSnapshot: async (snapshot) => {
+ if (snapshot.generation !== identityVersion) return;
+ await persistence.saveLocally({
+ draft: snapshot.draft
+ ? {
+ ...snapshot.draft,
+ thread_db_id: snapshot.thread?.db_id,
+ provider_thread_id: snapshot.thread?.provider_id,
+ }
+ : null,
+ inboxId: snapshot.inboxId,
+ attachments: snapshot.attachments,
+ });
+ },
paused: () =>
submitting() ||
pendingDeletion() ||
@@ -681,7 +719,7 @@ export function createReplyComposer(
);
try {
return persistence.confirmed(
- await autosave.save(captureSave(false, true))
+ await autosave.save(captureSave(false, true), { acknowledge: false })
);
} finally {
cleanupWatermark();
@@ -872,10 +910,9 @@ export function createReplyComposer(
const sendGeneration = identityVersion;
try {
// Ensure draft is saved before sending so undo-send always has a draft to restore
- autosave.cancel();
const epochBeforeSave = session.epoch();
try {
- await executeSaveDraft(willMarkDone);
+ await autosave.save(captureSave(willMarkDone), { acknowledge: false });
} catch (error) {
props.notices.reportError(error);
if (session.isStale(epochBeforeSave)) return;
@@ -1085,6 +1122,7 @@ export function createReplyComposer(
autosave.cancel();
try {
await autosave.settled().catch(() => {});
+ await autosave.flushLocal().catch(props.notices.reportError);
const draftId = savedDraftId();
if (draftId) {
try {
@@ -1142,7 +1180,10 @@ export function createReplyComposer(
terminalState()
)
return;
- if (await refuseAttachmentsOffline(props.connectivity, props.notices))
+ if (
+ !props.drafts.saveLocalDraft &&
+ (await refuseAttachmentsOffline(props.connectivity, props.notices))
+ )
return;
const currentAttachments = form.attachments.list();
@@ -1184,7 +1225,7 @@ export function createReplyComposer(
scheduleDraftSave();
};
- const handleRemoveAttachment = (attachment: DraftFormAttachment) => {
+ const handleRemoveAttachment = async (attachment: DraftFormAttachment) => {
if (
submitting() ||
pendingDeletion() ||
@@ -1194,13 +1235,17 @@ export function createReplyComposer(
terminalState()
)
return;
- hasLocalChanges = true;
- editVersion += 1;
- attachmentPersistence.remove(attachment);
+ try {
+ if (!(await attachmentPersistence.remove(attachment))) return;
+ scheduleDraftSave();
+ } catch (error) {
+ props.notices.reportError(error);
+ }
};
const scheduling = schedule.pending;
const scheduleBlocked = () =>
+ attachmentPersistence.removing() ||
pendingDeletion() ||
movingInbox() ||
submitting() ||
@@ -1355,7 +1400,19 @@ export function createReplyComposer(
});
};
+ async function retryDraft() {
+ if (scheduleBlocked() || schedule.state().type === 'scheduled') return;
+ // Finish this editor's last write before checking the shared revision.
+ await autosave.flushLocal().catch(props.notices.reportError);
+ await persistence.retry();
+ await autosave.save();
+ }
+
return {
+ retryDraft,
+ flushLocal: autosave.flushLocal,
+ localSaveState: autosave.localSaveState,
+ acknowledgeSaved: autosave.acknowledgeSaved,
onContentChange: handleChange,
handleUserMention,
scrollContainer,
diff --git a/apps/web/src/features/email-compose/views/compose-toolbar.tsx b/apps/web/src/features/email-compose/views/compose-toolbar.tsx
index a0fd265b44..26866188e1 100644
--- a/apps/web/src/features/email-compose/views/compose-toolbar.tsx
+++ b/apps/web/src/features/email-compose/views/compose-toolbar.tsx
@@ -18,13 +18,14 @@ import TextAa from '@phosphor/text-aa.svg';
import Trash from '@phosphor/trash.svg';
import { Button, SendButton } from '@ui';
import { FORMAT_TEXT_COMMAND, type LexicalEditor } from 'lexical';
-import { createSignal, Show } from 'solid-js';
+import { createSignal, type JSX, Show } from 'solid-js';
import { EmailDateSelector } from '../components/email-date-selector';
import { EmailScheduleSummary } from '../components/email-schedule-summary';
import { useCompose } from '../context/compose-context';
export function EmailComposeToolbar(props: {
editor?: () => LexicalEditor | undefined;
+ status?: JSX.Element;
}) {
const ctx = useCompose();
const [showFormatRibbon, setShowFormatRibbon] = createSignal(false);
@@ -70,7 +71,12 @@ export function EmailComposeToolbar(props: {
return (
<Show
when={!ctx.isMobile()}
- fallback={<MobileToolbar handleAddAttachments={handleAddAttachments} />}
+ fallback={
+ <MobileToolbar
+ handleAddAttachments={handleAddAttachments}
+ status={props.status}
+ />
+ }
>
<Show when={showFormatRibbon()}>
<div class="flex flex-row w-full gap-2 items-center p-2 -ml-3">
@@ -87,6 +93,7 @@ export function EmailComposeToolbar(props: {
</Show>
<div class="mt-2 flex min-w-0 justify-end">
<div class="flex shrink-0 items-center gap-1">
+ {props.status}
<Show when={ctx.hasDraft()}>
<Button
onClick={ctx.onDelete}
@@ -153,6 +160,7 @@ export function EmailComposeToolbar(props: {
function MobileToolbar(props: {
handleAddAttachments: (files: File[]) => void;
+ status?: JSX.Element;
}) {
const ctx = useCompose();
const hasScheduleSummary = () => {
@@ -176,6 +184,7 @@ function MobileToolbar(props: {
</SplitHeaderLeft>
<SplitHeaderRight>
<HeaderIsland class="h-(--mobile-chrome-button-size) p-[5px]">
+ {props.status}
<Show when={!ctx.hideAttachments}>
<div class="relative">
<Button
diff --git a/apps/web/src/features/email-compose/views/email-compose.test.tsx b/apps/web/src/features/email-compose/views/email-compose.test.tsx
new file mode 100644
index 0000000000..209d759c9e
--- /dev/null
+++ b/apps/web/src/features/email-compose/views/email-compose.test.tsx
@@ -0,0 +1,157 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { type ParentProps, Show } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import type { EmailDraftStorage } from '../context/compose-capabilities';
+import { useCompose } from '../context/compose-context';
+import { createComposeContext } from '../tests/capabilities';
+import { createEmailEditor, setEmailEditorText } from '../tests/editor';
+import { EmailComposeView } from './email-compose';
+
+vi.mock('@components/app/split-layout/components/SplitHeader', () => ({
+ SplitHeaderLeft: () => null,
+}));
+vi.mock('@components/app/split-layout/components/SplitLabel', () => ({
+ SplitHeaderBadge: () => null,
+ StaticSplitLabel: () => null,
+}));
+vi.mock('@core/component/EmailPermissionsBanner', () => ({
+ EmailPermissionsBanner: () => null,
+}));
+vi.mock('@core/mobile/WrapUnlessMobile', () => ({
+ WrapUnlessMobile: (props: ParentProps) => props.children,
+}));
+vi.mock('@ui', () => ({
+ ComposerSurface: (props: ParentProps) => props.children,
+}));
+vi.mock('../components/signature-preview', () => ({
+ SignaturePreview: () => null,
+}));
+vi.mock('../components/email-schedule-summary', () => ({
+ EmailScheduleBar: () => null,
+}));
+vi.mock('../components/draft-sync-status', () => ({
+ DraftSyncStatus: () => null,
+}));
+vi.mock('./compose-toolbar', () => ({ EmailComposeToolbar: () => null }));
+vi.mock('@components/app/mobile/MobileDrawer', () => {
+ const passthrough = (props: ParentProps) => props.children;
+ return {
+ MobileDrawer: Object.assign(
+ (props: ParentProps<{ open: boolean }>) => (
+ <Show when={props.open}>{props.children}</Show>
+ ),
+ {
+ Portal: passthrough,
+ Overlay: () => null,
+ Content: passthrough,
+ Handle: () => null,
+ Section: passthrough,
+ }
+ ),
+ };
+});
+vi.mock('./compose-layout', () => ({
+ ComposeLayout: () => {
+ const state = useCompose();
+ const editor = createEmailEditor();
+ state.captureEditor(editor);
+ state.onContentChange('');
+ return (
+ <input
+ aria-label="Message"
+ onInput={(event) => {
+ setEmailEditorText(editor, event.currentTarget.value);
+ state.onContentChange(event.currentTarget.value);
+ }}
+ />
+ );
+ },
+}));
+afterEach(cleanup);
+
+it.each([false, true])(
+ 'leaves only after local saving succeeds (failure=%s)',
+ async (fails) => {
+ const context = createComposeContext();
+ context.presentation.isMobile = () => true;
+ let finish!: () => void;
+ const diskError = new Error('Disk full');
+ context.drafts.saveLocalDraft = vi.fn<
+ NonNullable<EmailDraftStorage['saveLocalDraft']>
+ >(async (input) => {
+ await new Promise<void>((resolve, reject) => {
+ finish = () => (fails ? reject(diskError) : resolve());
+ });
+ return {
+ key: 'draft',
+ accountId: 'owner',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ draftId: 'draft',
+ threadId: 'thread',
+ content: input.draft,
+ attachments: [],
+ status: 'dirty',
+ updatedAt: Date.now(),
+ };
+ });
+ const goBack = vi.fn();
+ let back!: () => boolean;
+ render(() => (
+ <EmailComposeView
+ context={context}
+ initialTo={['[email protected]']}
+ host={{
+ goBack,
+ registerBack: (handler) => {
+ back = handler;
+ },
+ }}
+ />
+ ));
+ fireEvent.input(screen.getByRole('textbox', { name: 'Message' }), {
+ target: { value: 'Keep my edits' },
+ });
+ await waitFor(() =>
+ expect(context.drafts.saveLocalDraft).toHaveBeenCalled()
+ );
+ expect(back()).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'Save Draft' }));
+ expect(goBack).not.toHaveBeenCalled();
+ finish();
+ if (!fails) {
+ await waitFor(() => expect(goBack).toHaveBeenCalledOnce());
+ expect(screen.queryByRole('button', { name: 'Save Draft' })).toBeNull();
+ return;
+ }
+ await waitFor(() =>
+ expect(context.notices.reportError).toHaveBeenCalledWith(diskError)
+ );
+ expect(goBack).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: 'Save Draft' })).toBeDefined();
+ expect(screen.getByRole('textbox', { name: 'Message' })).toHaveProperty(
+ 'value',
+ 'Keep my edits'
+ );
+
+ // A subsequent edit retries the local write without losing the editor.
+ fireEvent.input(screen.getByRole('textbox', { name: 'Message' }), {
+ target: { value: 'Keep my corrected edits' },
+ });
+ await waitFor(() =>
+ expect(context.drafts.saveLocalDraft).toHaveBeenCalledTimes(2)
+ );
+ fails = false;
+ fireEvent.click(screen.getByRole('button', { name: 'Save Draft' }));
+ finish();
+ await waitFor(() => expect(goBack).toHaveBeenCalledOnce());
+ expect(screen.queryByRole('button', { name: 'Save Draft' })).toBeNull();
+ }
+);
diff --git a/apps/web/src/features/email-compose/views/email-compose.tsx b/apps/web/src/features/email-compose/views/email-compose.tsx
index 1626adc8ce..e3e70d4dba 100644
--- a/apps/web/src/features/email-compose/views/email-compose.tsx
+++ b/apps/web/src/features/email-compose/views/email-compose.tsx
@@ -6,15 +6,15 @@ import {
} from '@components/app/split-layout/components/SplitLabel';
import { EmailPermissionsBanner } from '@core/component/EmailPermissionsBanner';
import { WrapUnlessMobile } from '@core/mobile/WrapUnlessMobile';
-
import { ComposerSurface } from '@ui';
-
import { createResource, createSignal, Show } from 'solid-js';
+import { DraftSyncStatus } from '../components/draft-sync-status';
import { EmailScheduleBar } from '../components/email-schedule-summary';
import { SignaturePreview } from '../components/signature-preview';
import type { EmailComposeContext } from '../context/compose-capabilities';
import { ComposeProvider } from '../context/compose-context';
import type { ComposeContextValue } from '../primitives/compose-view-state';
+import { createDraftSyncStatus } from '../primitives/draft-sync-status';
import {
createEmailComposer,
type EmailComposerOptions,
@@ -65,6 +65,8 @@ export function EmailComposeView(props: EmailComposeViewProps) {
{...props}
draft={saved()?.draft ?? props.draft}
draftPersistence={saved()?.persistence}
+ localDraft={saved()?.local}
+ localAttachments={saved()?.attachments}
/>
</Show>
</Show>
@@ -72,7 +74,11 @@ export function EmailComposeView(props: EmailComposeViewProps) {
}
function LoadedEmailComposeView(
- props: EmailComposeViewProps & { draftPersistence?: 'committed' | 'queued' }
+ props: EmailComposeViewProps &
+ Pick<
+ EmailComposerOptions,
+ 'draftPersistence' | 'localDraft' | 'localAttachments'
+ >
) {
const composeContext = props.context;
const state = createEmailComposer({
@@ -91,11 +97,21 @@ function LoadedEmailComposeView(
draft: props.draft,
draftId: props.draftId,
draftPersistence: props.draftPersistence,
+ localDraft: props.localDraft,
+ localAttachments: props.localAttachments,
recipientOptions: props.recipientOptions,
onRecipientsChange: props.onRecipientsChange,
initialTo: props.initialTo,
initialInboxId: props.initialInboxId,
});
+ const sync = createDraftSyncStatus({
+ drafts: composeContext.drafts,
+ draftId: state.draftId,
+ localSaveState: state.localSaveState,
+ acknowledgeSaved: state.acknowledgeSaved,
+ retry: state.retryDraft,
+ discard: state.deleteDraftAndReset,
+ });
const {
editor,
previewName,
@@ -167,11 +183,27 @@ function LoadedEmailComposeView(
});
}
- const leaveCompose = () => {
+ const leaveCompose = async () => {
+ try {
+ await state.flushLocal();
+ } catch (error) {
+ composeContext.notices.reportError(error);
+ return;
+ }
setDraftBackMenuOpen(false);
props.host?.goBack?.();
};
+ const SyncStatus = () => (
+ <DraftSyncStatus
+ state={sync.state()}
+ busy={sync.busy()}
+ error={sync.error()}
+ onRetry={sync.retry}
+ onKeepEditing={sync.keepEditing}
+ />
+ );
+
return (
<ComposeProvider value={ctxValue}>
<Show when={!composeContext.presentation.isMobile()}>
@@ -218,7 +250,9 @@ function LoadedEmailComposeView(
)}
>
<ComposeLayout
- toolbar={<EmailComposeToolbar editor={editor} />}
+ toolbar={
+ <EmailComposeToolbar editor={editor} status={<SyncStatus />} />
+ }
notice={hasInboxError() ? <EmailPermissionsBanner /> : undefined}
class="size-full p-4 touch:bg-surface max-h-full touch:max-h-none overflow-hidden flex flex-col min-h-0 touch:min-h-full"
/>
diff --git a/apps/web/src/features/email-compose/views/reply-input.test.tsx b/apps/web/src/features/email-compose/views/reply-input.test.tsx
new file mode 100644
index 0000000000..5c8f10db38
--- /dev/null
+++ b/apps/web/src/features/email-compose/views/reply-input.test.tsx
@@ -0,0 +1,103 @@
+import { cleanup, render, waitFor } from '@solidjs/testing-library';
+import { ErrorBoundary } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { message } from '../../email-message/tests/messages';
+import { createComposeContext } from '../tests/capabilities';
+import { ReplyInputView } from './reply-input';
+
+const capture = vi.hoisted(() => vi.fn());
+// Stop at the controller boundary: this suite verifies which restored content
+// the view supplies, without mounting app-owned editor plugins and toolbars.
+vi.mock('../primitives/reply-composer', () => ({
+ createReplyComposer: (options: unknown) => {
+ capture(options);
+ throw new Error('Controller boundary reached');
+ },
+}));
+vi.mock('@ui', () => ({}));
+vi.mock(
+ '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder',
+ () => ({})
+);
+vi.mock('@core/component/LexicalMarkdown/builder/MarkdownShell', () => ({}));
+vi.mock('@components/app/split-layout/split-router/mention-links', () => ({}));
+vi.mock('@core/hotkey/hotkeys', () => ({}));
+vi.mock('../components/attachment-viewer', () => ({}));
+vi.mock('./reply-envelope', () => ({}));
+
+afterEach(() => {
+ cleanup();
+ capture.mockClear();
+});
+it.each([
+ { body: '', expected: '' },
+ { body: '', text: 'Stale plain text', expected: '' },
+ {
+ body: undefined,
+ text: 'Plain & simple',
+ expected:
+ '<div><span style="white-space: pre-wrap;">Plain &amp; simple</span></div>',
+ },
+ { body: undefined, expected: '' },
+ { body: null, expected: '' },
+ { body: btoa('<p>Saved reply</p>'), expected: '<p>Saved reply</p>' },
+ { body: undefined, missing: true, expected: '<p>Seed quote</p>' },
+])(
+ 'restores authoritative reply HTML ($body, missing=$missing)',
+ async ({ body, text, missing, expected }) => {
+ const context = createComposeContext();
+ context.drafts.readDraft = async () =>
+ missing
+ ? undefined
+ : {
+ draft: message('draft', {
+ is_draft: true,
+ body_html_sanitized: body,
+ body_text: text,
+ }),
+ persistence: 'queued',
+ };
+ render(() => (
+ <ErrorBoundary fallback={<div>Controller captured</div>}>
+ <ReplyInputView
+ context={context}
+ draft={message('draft', { is_draft: true })}
+ preloadedHtml="<p>Seed quote</p>"
+ sourceEntityId="thread"
+ replyingTo={() => message('parent')}
+ session={{
+ thread: () => undefined,
+ recipientOptions: () => [],
+ isPersonalReply: () => false,
+ onDraftRemoved() {},
+ exitToThread: () => false,
+ replyRequest: { replyType: () => undefined, clear() {} },
+ }}
+ />
+ </ErrorBoundary>
+ ));
+ await waitFor(() =>
+ expect(capture).toHaveBeenCalledWith(
+ expect.objectContaining({ preloadedHtml: expected })
+ )
+ );
+ }
+);
+
+vi.mock('@app/features/email-message/components/attachment-pill', () => ({}));
+vi.mock('@core/component/FileDropOverlay', () => ({}));
+vi.mock(
+ '@core/component/LexicalMarkdown/plugins/ios-cursor-scroll',
+ () => ({})
+);
+vi.mock('@core/directive/fileFolderDrop', () => ({}));
+vi.mock('@core/directive/fileSelector', () => ({}));
+vi.mock('@core/hotkey/tokens', () => ({}));
+vi.mock('@core/mobile/useTouchOutsideToDismissKeyboard', () => ({}));
+vi.mock('../components/draft-sync-status', () => ({}));
+vi.mock('../components/email-date-selector', () => ({}));
+vi.mock('../components/email-schedule-summary', () => ({}));
+vi.mock('../components/macro-signature-button', () => ({}));
+vi.mock('../components/mobile-reply-toolbar', () => ({}));
+vi.mock('../components/signature-preview', () => ({}));
+vi.mock('../primitives/prepare-email-body', () => ({}));
diff --git a/apps/web/src/features/email-compose/views/reply-input.tsx b/apps/web/src/features/email-compose/views/reply-input.tsx
index e40e900755..938cf27098 100644
--- a/apps/web/src/features/email-compose/views/reply-input.tsx
+++ b/apps/web/src/features/email-compose/views/reply-input.tsx
@@ -18,8 +18,9 @@ import { isIOS } from '@solid-primitives/platform';
import { Button, cn, SendButton, Surface, Tooltip } from '@ui';
import type { LexicalEditor } from 'lexical';
import { $getRoot } from 'lexical';
-import { createSignal, For, onMount, Show } from 'solid-js';
+import { createResource, createSignal, For, onMount, Show } from 'solid-js';
import { createAttachmentViewer } from '../components/attachment-viewer';
+import { DraftSyncStatus } from '../components/draft-sync-status';
import { EmailDateSelector } from '../components/email-date-selector';
import {
EmailScheduleBar,
@@ -30,6 +31,9 @@ import { MobileReplyToolbar } from '../components/mobile-reply-toolbar';
import { SignaturePreview } from '../components/signature-preview';
import type { EmailComposeContext } from '../context/compose-capabilities';
import { getOrInitEmailFormContext } from '../context/email-form-context';
+import { decodeBase64Utf8 } from '../core/decode-base64';
+import { plainTextToHtml } from '../core/plain-text-to-html';
+import { createDraftSyncStatus } from '../primitives/draft-sync-status';
import { registerToggleAppendedThread } from '../primitives/prepare-email-body';
import { ReplyEnvelope } from './reply-envelope';
@@ -61,6 +65,46 @@ type ReplyInputViewProps = Omit<
mobileDrawer?: { onClose: () => void };
};
export function ReplyInputView(props: ReplyInputViewProps) {
+ const initialId = props.draft?.db_id;
+ const read = props.context.drafts.readDraft;
+ const [saved, { refetch }] = createResource(
+ () => read && initialId,
+ async (id) => await read!(id)
+ );
+ const restoredHtml = () => {
+ const draft = saved()?.draft;
+ if (!draft) return props.preloadedHtml;
+ if (draft.body_html_sanitized != null)
+ return decodeBase64Utf8(draft.body_html_sanitized);
+ return draft.body_text ? plainTextToHtml(draft.body_text) : '';
+ };
+ return (
+ <Show
+ when={!saved.loading}
+ fallback={<div role="status">Loading draft…</div>}
+ >
+ <Show
+ when={!saved.error}
+ fallback={
+ <div role="alert">
+ Unable to load local draft.{' '}
+ <button onClick={() => void refetch()}>Retry</button>
+ </div>
+ }
+ >
+ <LoadedReplyInputView
+ {...props}
+ draft={saved()?.draft ?? props.draft}
+ localDraft={saved()?.local}
+ localAttachments={saved()?.attachments}
+ preloadedHtml={restoredHtml()}
+ />
+ </Show>
+ </Show>
+ );
+}
+
+function LoadedReplyInputView(props: ReplyInputViewProps) {
const composeContext = props.context;
const ctx = props.session;
const [isDragging, setIsDragging] = createSignal<boolean>();
@@ -85,6 +129,8 @@ export function ReplyInputView(props: ReplyInputViewProps) {
replyingTo: props.replyingTo,
isEditingExisting: props.isEditingExisting,
draft: props.draft,
+ localDraft: props.localDraft,
+ localAttachments: props.localAttachments,
preloadedHtml: props.preloadedHtml,
formSeed: props.formSeed,
onEngaged: props.onEngaged,
@@ -97,6 +143,14 @@ export function ReplyInputView(props: ReplyInputViewProps) {
{ container: () => composeContainerRef, footer: () => bottomBarRef },
getOrInitEmailFormContext
);
+ const sync = createDraftSyncStatus({
+ drafts: composeContext.drafts,
+ draftId: state.savedDraftId,
+ localSaveState: state.localSaveState,
+ acknowledgeSaved: state.acknowledgeSaved,
+ retry: state.retryDraft,
+ discard: state.deleteDraftAndReset,
+ });
const {
form,
activeInboxId,
@@ -326,6 +380,16 @@ export function ReplyInputView(props: ReplyInputViewProps) {
</Button>
);
+ const SyncStatus = () => (
+ <DraftSyncStatus
+ state={sync.state()}
+ busy={sync.busy()}
+ error={sync.error()}
+ onRetry={sync.retry}
+ onKeepEditing={sync.keepEditing}
+ />
+ );
+
return (
<>
<Surface
@@ -346,6 +410,7 @@ export function ReplyInputView(props: ReplyInputViewProps) {
>
<Show when={isMobileDrawer()}>
<MobileReplyToolbar
+ status={<SyncStatus />}
discardLabel={savedDraftId() ? 'Delete draft' : 'Discard draft'}
onDiscard={deleteDraftAndReset}
attachRef={(element) =>
@@ -598,6 +663,7 @@ export function ReplyInputView(props: ReplyInputViewProps) {
class="shrink-0 flex min-w-0 justify-end pt-1.5"
>
<div class="flex shrink-0 items-center gap-1">
+ <SyncStatus />
<Button
onClick={deleteDraftAndReset}
tooltip={savedDraftId() ? 'Delete draft' : 'Discard'}
diff --git a/apps/web/src/features/email-thread/core/thread-messages.test.ts b/apps/web/src/features/email-thread/core/thread-messages.test.ts
index 45ade1fe02..48933598dc 100644
--- a/apps/web/src/features/email-thread/core/thread-messages.test.ts
+++ b/apps/web/src/features/email-thread/core/thread-messages.test.ts
@@ -3,6 +3,29 @@ import { message, thread } from '../tests/fixtures';
import { selectThreadMessages, selectThreadSender } from './thread-messages';
describe('thread message selection', () => {
+ it.each([false, true])(
+ 'selects the most recently edited reply draft independently of transport order (reverse=%s)',
+ (reverse) => {
+ const older = message('older-draft', {
+ is_draft: true,
+ replying_to_id: 'parent',
+ updated_at: '2026-09-01T10:00:00Z',
+ internal_date_ts: '2026-09-03T10:00:00Z',
+ });
+ const newer = message('newer-draft', {
+ is_draft: true,
+ replying_to_id: 'parent',
+ updated_at: '2026-09-02T10:00:00Z',
+ internal_date_ts: '2026-09-01T10:00:00Z',
+ });
+ const drafts = reverse ? [newer, older] : [older, newer];
+ expect(selectThreadMessages(thread(drafts)).draftMap.parent).toBe(newer);
+ // Local replies do not have received/sent timestamps.
+ older.internal_date_ts = undefined;
+ newer.internal_date_ts = undefined;
+ expect(selectThreadMessages(thread(drafts)).draftMap.parent).toBe(newer);
+ }
+ );
it('targets the original external sender for sender actions regardless of transport order', () => {
const original = message('original', {
from: { email: '[email protected]' },
diff --git a/apps/web/src/features/email-thread/core/thread-messages.ts b/apps/web/src/features/email-thread/core/thread-messages.ts
index ae3a8e60c4..f75da93243 100644
--- a/apps/web/src/features/email-thread/core/thread-messages.ts
+++ b/apps/web/src/features/email-thread/core/thread-messages.ts
@@ -45,7 +45,13 @@ export function selectThreadMessages(thread: EmailThread) {
if (!replyingToId) continue;
- messageDraftMap[replyingToId] = message;
+ const previous = messageDraftMap[replyingToId];
+ if (
+ !previous ||
+ Date.parse(message.updated_at) > Date.parse(previous.updated_at)
+ ) {
+ messageDraftMap[replyingToId] = message;
+ }
}
return {
diff --git a/apps/web/src/features/email-thread/email-thread.test.tsx b/apps/web/src/features/email-thread/email-thread.test.tsx
index 78b83f17d9..8deb1728be 100644
--- a/apps/web/src/features/email-thread/email-thread.test.tsx
+++ b/apps/web/src/features/email-thread/email-thread.test.tsx
@@ -101,7 +101,11 @@ describe('email thread query ownership', () => {
/>
));
expect(screen.getByTestId('body').textContent).toBe('Cached body');
- expect(mocks.source).toHaveBeenCalledWith(source);
+ expect(mocks.source.mock.calls[0][0]).toMatchObject({
+ id: source.id,
+ fetchOlder,
+ refresh,
+ });
expect(mocks.query).not.toHaveBeenCalled();
const options = mocks.composeOptions.mock.calls[0][0];
expect(options.threadTransport?.()).toBe('graphql');
diff --git a/apps/web/src/features/email-thread/email-thread.tsx b/apps/web/src/features/email-thread/email-thread.tsx
index 9226da79c6..23770b9637 100644
--- a/apps/web/src/features/email-thread/email-thread.tsx
+++ b/apps/web/src/features/email-thread/email-thread.tsx
@@ -31,6 +31,7 @@ import type {
EmailThreadContext,
EmailThreadSource,
} from './context/email-thread-context';
+import { createOptimisticThreadSend } from './primitives/optimistic-send';
import { createThreadActionAdapter } from './thread-action-adapter';
import {
EmailThreadSurface,
@@ -50,14 +51,18 @@ export type EmailThreadProps = Omit<
export function EmailThread(props: EmailThreadProps) {
// The host's load gate already owns the live query. Reuse its source so
// mounting the body does not start a second disk read/network request.
- const source = props.source;
const [calendarPreferences] = useCalendarPreferences();
const contacts = useContacts();
const viewerEmail = useEmail();
const user = useUserContext();
- const compose = createEmailComposeContext({
+ const composeContext = createEmailComposeContext({
threadTransport: props.threadTransport,
});
+ const { source, delivery } = createOptimisticThreadSend(
+ props.source,
+ composeContext
+ );
+ const compose = { ...composeContext, delivery };
const threadContext: EmailThreadContext = {
source,
viewerEmail,
diff --git a/apps/web/src/features/email-thread/primitives/email-thread-state.test.ts b/apps/web/src/features/email-thread/primitives/email-thread-state.test.ts
index 2e823aad7d..c2dfd608a6 100644
--- a/apps/web/src/features/email-thread/primitives/email-thread-state.test.ts
+++ b/apps/web/src/features/email-thread/primitives/email-thread-state.test.ts
@@ -5,6 +5,30 @@ import { createThreadContext, message, thread } from '../tests/fixtures';
import { createEmailThreadState } from './email-thread-state';
describe('thread state with an injected source', () => {
+ it('does not move an open bottom reply to a newly sent message', () =>
+ createRoot((dispose) => {
+ try {
+ const parent = message('parent');
+ const [snapshot, setSnapshot] = createSignal(thread([parent]));
+ const state = createEmailThreadState(
+ createThreadContext({ thread: snapshot })
+ );
+ state.messages.setBottomReplyOpen(true);
+ expect(state.messages.bottomReplyOpen()).toBe(true);
+ setSnapshot(thread([{ ...parent, body_text: 'Refreshed' }]));
+ expect(state.messages.bottomReplyOpen()).toBe(true);
+ setSnapshot(thread([parent, message('sent')]));
+ expect(state.messages.bottomReplyOpen()).toBe(false);
+ // Replying to the new message still requires a deliberate action.
+ state.messages.setBottomReplyOpen(true);
+ expect(state.messages.bottomReplyOpen()).toBe(true);
+ setSnapshot(thread([message('sent')], { db_id: 'another-thread' }));
+ expect(state.messages.bottomReplyOpen()).toBe(false);
+ } finally {
+ dispose();
+ }
+ }));
+
it('retains newer drafts through stale snapshots and does not resurrect discarded replies', () =>
createRoot((dispose) => {
try {
diff --git a/apps/web/src/features/email-thread/primitives/email-thread-state.ts b/apps/web/src/features/email-thread/primitives/email-thread-state.ts
index b441d3533e..26c088aa60 100644
--- a/apps/web/src/features/email-thread/primitives/email-thread-state.ts
+++ b/apps/web/src/features/email-thread/primitives/email-thread-state.ts
@@ -125,7 +125,30 @@ export function createEmailThreadState(
const [hiddenChipFocused, setHiddenChipFocused] = createSignal(false);
const [hoveredStop, setHoveredStop] = createSignal<HoveredThreadStop>();
const [replyingToMessageId, setReplyingToMessageId] = createSignal<string>();
- const [bottomReplyOpen, setBottomReplyOpen] = createSignal(false);
+ const [bottomReplyTarget, setBottomReplyTarget] = createSignal<{
+ threadId: string;
+ messageId: string;
+ }>();
+ // An open reply belongs to the selected message, even when sending adds
+ // a new last message to the thread.
+ const bottomReplyOpen = () => {
+ const target = bottomReplyTarget();
+ const thread = selected();
+ return (
+ !!target &&
+ target.threadId === thread?.db_id &&
+ target.messageId === thread.filtered.at(-1)?.db_id
+ );
+ };
+ const setBottomReplyOpen = (open: boolean) => {
+ const thread = selected();
+ const messageId = thread?.filtered.at(-1)?.db_id;
+ setBottomReplyTarget(
+ open && thread && messageId
+ ? { threadId: thread.db_id, messageId }
+ : undefined
+ );
+ };
const [mobileReplyComposerOpen, setMobileReplyComposerOpen] =
createSignal(false);
const [mobileReplyComposerMessageId, setMobileReplyComposerMessageId] =
diff --git a/apps/web/src/features/email-thread/primitives/optimistic-send.test.ts b/apps/web/src/features/email-thread/primitives/optimistic-send.test.ts
new file mode 100644
index 0000000000..bace113cfd
--- /dev/null
+++ b/apps/web/src/features/email-thread/primitives/optimistic-send.test.ts
@@ -0,0 +1,221 @@
+import { createRoot, createSignal } from 'solid-js';
+import { expect, it, vi } from 'vitest';
+import type {
+ PersistedEmailIdentity,
+ SendEmailDraft,
+} from '../../email-compose/context/compose-capabilities';
+import { createComposeContext } from '../../email-compose/tests/capabilities';
+import { createThreadContext, message, thread } from '../tests/fixtures';
+import { createOptimisticThreadSend } from './optimistic-send';
+
+const input: SendEmailDraft = {
+ inboxId: 'inbox',
+ message: {
+ db_id: 'draft',
+ thread_db_id: 'thread',
+ subject: 'Final subject',
+ body_text: 'café',
+ body_html: 'PHA+Y2Fmw6k8L3A+',
+ to: [{ email: '[email protected]' }],
+ },
+};
+const identity: PersistedEmailIdentity = {
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+};
+
+function setup() {
+ return createRoot((dispose) => {
+ const draft = message('draft', {
+ is_draft: true,
+ body_text: 'Older body',
+ body_replyless: 'Older reply',
+ labels: [{ provider_label_id: 'DRAFT' }],
+ attachments_draft: [
+ {
+ id: 'file',
+ s3_key: 'file',
+ file_name: 'Notes.txt',
+ content_type: 'text/plain',
+ size: 20,
+ },
+ ],
+ });
+ const [snapshot, setSnapshot] = createSignal(
+ thread([message('received'), draft])
+ );
+ const compose = createComposeContext();
+ const request = Promise.withResolvers<PersistedEmailIdentity>();
+ vi.mocked(compose.delivery.sendMessage).mockReturnValue(request.promise);
+ const optimistic = createOptimisticThreadSend(
+ createThreadContext({ thread: snapshot }).source,
+ compose
+ );
+ return { ...optimistic, compose, request, snapshot, setSnapshot, dispose };
+ });
+}
+
+it.each(['reply', 'standalone'] as const)(
+ 'shows a %s before send settles and retains it until the thread refreshes',
+ async (kind) => {
+ const state = setup();
+ try {
+ const sendInput =
+ kind === 'standalone'
+ ? { ...input, message: { ...input.message, thread_db_id: undefined } }
+ : input;
+ const send = state.delivery.sendMessage(sendInput);
+ expect(state.compose.delivery.sendMessage).toHaveBeenCalledWith(
+ sendInput
+ );
+ expect(
+ state.source.thread()?.messages.map((message) => message.db_id)
+ ).toEqual(['received', 'draft']);
+ expect(state.source.thread()?.messages[1]).toMatchObject({
+ is_draft: false,
+ subject: 'Final subject',
+ body_text: 'café',
+ body_html_sanitized: '<p>café</p>',
+ body_replyless: null,
+ from: { email: '[email protected]' },
+ to: [{ email: '[email protected]' }],
+ labels: [],
+ attachments_draft: [{ id: 'file' }],
+ sent_at: expect.any(String),
+ });
+ // The optimistic projection never changes the underlying draft snapshot.
+ expect(state.snapshot().messages[1].is_draft).toBe(true);
+ state.request.resolve(identity);
+ await expect(send).resolves.toEqual(identity);
+ expect(state.source.thread()?.messages[1].is_draft).toBe(false);
+ state.setSnapshot(
+ thread([
+ message('received'),
+ message('draft', { body_text: 'Server body' }),
+ ])
+ );
+ expect(
+ state.source.thread()?.messages.map((message) => message.body_text)
+ ).toEqual([undefined, 'Server body']);
+ state.setSnapshot(thread([message('received')]));
+ expect(state.source.thread()?.messages).toHaveLength(1);
+ } finally {
+ state.dispose();
+ }
+ }
+);
+
+it('removes a failed optimistic send while preserving a newer draft edit', async () => {
+ const state = setup();
+ try {
+ const send = state.delivery.sendMessage(input);
+ const rejected = expect(send).rejects.toThrow('Delivery failed');
+ state.setSnapshot(
+ thread([
+ message('received'),
+ message('draft', { is_draft: true, body_text: 'Newer edit' }),
+ ])
+ );
+ state.request.reject(new Error('Delivery failed'));
+ await rejected;
+ expect(state.source.thread()?.messages[1]).toMatchObject({
+ is_draft: true,
+ body_text: 'Newer edit',
+ });
+ } finally {
+ state.dispose();
+ }
+});
+
+it('adopts the server identity without duplicating the draft or the sent message', async () => {
+ const state = setup();
+ try {
+ const send = state.delivery.sendMessage(input);
+ state.request.resolve({ ...identity, draftId: 'server-message' });
+ await send;
+ expect(
+ state.source.thread()?.messages.map((message) => message.db_id)
+ ).toEqual(['received', 'server-message']);
+ state.setSnapshot(
+ thread([
+ message('received'),
+ message('server-message', { body_text: 'Confirmed' }),
+ ])
+ );
+ expect(state.source.thread()?.messages).toHaveLength(2);
+ expect(state.source.thread()?.messages[1].body_text).toBe('Confirmed');
+ } finally {
+ state.dispose();
+ }
+});
+
+it('rolls back only the failed send when multiple sends are in flight', async () => {
+ const state = setup();
+ try {
+ const second = Promise.withResolvers<PersistedEmailIdentity>();
+ vi.mocked(state.compose.delivery.sendMessage)
+ .mockReturnValueOnce(state.request.promise)
+ .mockReturnValueOnce(second.promise);
+ const firstSend = state.delivery.sendMessage(input);
+ const failed = expect(firstSend).rejects.toThrow();
+ const secondSend = state.delivery.sendMessage({
+ ...input,
+ message: { ...input.message, db_id: 'second', body_text: 'Second reply' },
+ });
+ state.request.reject(new Error('Failed'));
+ await failed;
+ expect(state.source.thread()?.messages.at(-1)).toMatchObject({
+ db_id: 'second',
+ is_draft: false,
+ body_text: 'Second reply',
+ });
+ expect(state.source.thread()?.messages[1].is_draft).toBe(true);
+ second.resolve({ ...identity, draftId: 'second' });
+ await secondSend;
+ } finally {
+ state.dispose();
+ }
+});
+
+it('removes the optimistic message only after Undo Send succeeds', async () => {
+ const state = setup();
+ try {
+ const send = state.delivery.sendMessage(input);
+ state.request.resolve(identity);
+ await send;
+ const onUndone = vi.fn();
+ const undo = { draftId: 'draft', inboxId: 'inbox', onUndone };
+ vi.mocked(state.compose.delivery.undoSend).mockRejectedValueOnce(
+ new Error('Undo failed')
+ );
+ await expect(state.delivery.undoSend(undo)).rejects.toThrow('Undo failed');
+ expect(state.source.thread()?.messages[1].is_draft).toBe(false);
+ vi.mocked(state.compose.delivery.undoSend).mockImplementation(
+ async ({ onUndone }) => {
+ await onUndone();
+ }
+ );
+ await state.delivery.undoSend(undo);
+ expect(state.source.thread()?.messages[1].is_draft).toBe(true);
+ expect(onUndone).toHaveBeenCalledOnce();
+ } finally {
+ state.dispose();
+ }
+});
+
+it('keeps optimistic sends scoped to their thread when the source navigates', async () => {
+ const state = setup();
+ try {
+ const send = state.delivery.sendMessage(input);
+ state.setSnapshot(thread([message('other')], { db_id: 'other-thread' }));
+ expect(
+ state.source.thread()?.messages.map((message) => message.db_id)
+ ).toEqual(['other']);
+ state.request.resolve(identity);
+ await send;
+ expect(state.source.thread()?.messages).toHaveLength(1);
+ } finally {
+ state.dispose();
+ }
+});
diff --git a/apps/web/src/features/email-thread/primitives/optimistic-send.ts b/apps/web/src/features/email-thread/primitives/optimistic-send.ts
new file mode 100644
index 0000000000..a923f65e85
--- /dev/null
+++ b/apps/web/src/features/email-thread/primitives/optimistic-send.ts
@@ -0,0 +1,175 @@
+import { createMemo, createSignal } from 'solid-js';
+import type {
+ EmailComposeContext,
+ SendEmailDraft,
+} from '../../email-compose/context/compose-capabilities';
+import { decodeBase64Utf8 } from '../../email-compose/core/decode-base64';
+import type { EmailMessage } from '../../email-message/core/email-message';
+import type { EmailThreadSource } from '../context/email-thread-context';
+
+type PendingMessage = {
+ token: symbol;
+ originalId: string;
+ message: EmailMessage;
+};
+
+/** Keep REST sends visible in this surface until the thread read catches up. */
+export function createOptimisticThreadSend(
+ source: EmailThreadSource,
+ compose: Pick<EmailComposeContext, 'delivery' | 'accounts' | 'viewerEmail'>
+) {
+ const [pending, setPending] = createSignal<PendingMessage[]>([]);
+ // Remember server acknowledgement so a later deletion or undo cannot
+ // resurrect a message from an older optimistic snapshot.
+ const confirmed = createMemo<Set<symbol>>((previous) => {
+ const messages = source.thread()?.messages ?? [];
+ return new Set(
+ pending()
+ .filter(
+ (entry) =>
+ previous?.has(entry.token) ||
+ messages.some(
+ (message) =>
+ !message.is_draft && message.db_id === entry.message.db_id
+ )
+ )
+ .map((entry) => entry.token)
+ );
+ });
+ const remove = (token: symbol) =>
+ setPending((entries) => entries.filter((entry) => entry.token !== token));
+
+ function prepare(input: SendEmailDraft): PendingMessage | undefined {
+ const current = source.thread();
+ const draft = input.message;
+ if (
+ !current ||
+ !draft.db_id ||
+ (draft.thread_db_id && draft.thread_db_id !== current.db_id)
+ )
+ return;
+ const existing = current.messages.find(
+ (message) => message.db_id === draft.db_id
+ );
+ // Standalone composers send only the draft ID; replies also carry a thread ID.
+ if (!existing && !draft.thread_db_id) return;
+ const inbox = compose.accounts
+ .inboxes()
+ .find((inbox) => inbox.id === (input.inboxId ?? current.link_id));
+ const now = new Date().toISOString();
+ return {
+ token: Symbol('send'),
+ originalId: draft.db_id,
+ message: {
+ ...existing,
+ db_id: draft.db_id,
+ thread_db_id: current.db_id,
+ link_id: inbox?.id ?? current.link_id,
+ from: inbox
+ ? {
+ email: inbox.email_address,
+ name: inbox.displayName,
+ photo_url: inbox.photo_url,
+ }
+ : (existing?.from ?? { email: compose.viewerEmail() ?? '' }),
+ to: draft.to ?? [],
+ cc: draft.cc ?? [],
+ bcc: draft.bcc ?? [],
+ subject: draft.subject,
+ body_text: draft.body_text,
+ body_macro: draft.body_macro,
+ body_html_sanitized: draft.body_html
+ ? decodeBase64Utf8(draft.body_html)
+ : null,
+ body_replyless: null,
+ replying_to_id: draft.replying_to_id,
+ is_draft: false,
+ scheduled_send_time: null,
+ created_at: existing?.created_at ?? now,
+ updated_at: now,
+ internal_date_ts: now,
+ sent_at: now,
+ attachments: existing?.attachments ?? [],
+ attachments_draft: existing?.attachments_draft ?? [],
+ attachments_forwarded: existing?.attachments_forwarded ?? [],
+ labels:
+ existing?.labels.filter(
+ (label) => label.provider_label_id !== 'DRAFT'
+ ) ?? [],
+ },
+ };
+ }
+
+ const thread = () => {
+ const current = source.thread();
+ if (!current) return;
+ const messages = pending().filter(
+ (entry) =>
+ !confirmed().has(entry.token) &&
+ entry.message.thread_db_id === current.db_id
+ );
+ if (!messages.length) return current;
+ const ids = new Set(
+ messages.flatMap((entry) => [entry.originalId, entry.message.db_id])
+ );
+ return {
+ ...current,
+ messages: [
+ ...current.messages.filter((message) => !ids.has(message.db_id)),
+ ...messages.map((entry) => entry.message),
+ ],
+ };
+ };
+
+ const delivery: EmailComposeContext['delivery'] = {
+ ...compose.delivery,
+ async sendMessage(input) {
+ const entry = prepare(input);
+ if (!entry) return await compose.delivery.sendMessage(input);
+ const acknowledged = confirmed();
+ setPending((entries) => [
+ ...entries.filter((entry) => !acknowledged.has(entry.token)),
+ entry,
+ ]);
+ try {
+ const result = await compose.delivery.sendMessage(input);
+ setPending((entries) =>
+ entries.map((pending) =>
+ pending.token === entry.token
+ ? {
+ ...pending,
+ message: {
+ ...pending.message,
+ db_id: result.draftId ?? pending.message.db_id,
+ thread_db_id:
+ result.threadId ?? pending.message.thread_db_id,
+ link_id: result.inboxId,
+ },
+ }
+ : pending
+ )
+ );
+ return result;
+ } catch (error) {
+ remove(entry.token);
+ throw error;
+ }
+ },
+ async undoSend(input) {
+ await compose.delivery.undoSend({
+ ...input,
+ onUndone: async () => {
+ setPending((entries) =>
+ entries.filter(
+ (entry) =>
+ entry.originalId !== input.draftId &&
+ entry.message.db_id !== input.draftId
+ )
+ );
+ await input.onUndone();
+ },
+ });
+ },
+ };
+ return { source: { ...source, thread }, delivery };
+}
diff --git a/apps/web/src/features/email-thread/queries/offline-reply.test.ts b/apps/web/src/features/email-thread/queries/offline-reply.test.ts
new file mode 100644
index 0000000000..febd33900a
--- /dev/null
+++ b/apps/web/src/features/email-thread/queries/offline-reply.test.ts
@@ -0,0 +1,106 @@
+import 'fake-indexeddb/auto';
+import {
+ listLocalDrafts,
+ localDraftStore,
+ saveLocalDraft,
+} from '@queries/email/local-drafts';
+import type { ThreadQueryData, ThreadQueryResult } from '@queries/email/thread';
+import { createMemo, createRoot } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { decodeBase64Utf8 } from '../../email-compose/core/decode-base64';
+import { createComposeContext } from '../../email-compose/tests/capabilities';
+import { mountReplyComposer } from '../../email-compose/tests/reply';
+import { message } from '../../email-message/tests/messages';
+import { selectThreadMessages } from '../core/thread-messages';
+import { createThreadDrafts } from '../primitives/thread-drafts';
+import { createEmailThreadSource } from './thread-source';
+
+vi.mock('@queries/client', () => ({
+ queryClient: {
+ getQueryData: () => ({ authenticated: true, id: 'owner' }),
+ getQueryCache: () => ({ subscribe: () => () => {} }),
+ },
+}));
+vi.mock('@queries/calendar/invitations', () => ({
+ invalidateInvitationScheduling: vi.fn(),
+}));
+vi.mock('@core/mobile/nativeStagedUpload', () => ({
+ getNativeStagedUpload: () => undefined,
+}));
+afterEach(async () => {
+ await localDraftStore.clear();
+ await localDraftStore.close();
+});
+
+it.each([false, true])(
+ 'reopens an offline reply after leaving the thread (debounce finished=%s)',
+ async (waitForQueue) => {
+ const context = createComposeContext();
+ context.connectivity.looksOffline = () => true;
+ context.drafts.saveLocalDraft = saveLocalDraft;
+ context.drafts.saveDraft = vi.fn(async (input) => ({
+ ...input.clientHandles,
+ inboxId: 'inbox',
+ persistence: 'queued',
+ }));
+ const parent = message('parent');
+ const reply = mountReplyComposer(context, () => parent);
+ reply.edit('My offline reply');
+ await reply.flushLocal();
+ expect(context.notices.feedback.failure).not.toHaveBeenCalled();
+ if (waitForQueue)
+ await vi.waitFor(() =>
+ expect(context.drafts.saveDraft).toHaveBeenCalled()
+ );
+ reply.dispose();
+ await reply.flushLocal();
+ await vi.waitFor(() => expect(context.drafts.saveDraft).toHaveBeenCalled());
+ const stored = await listLocalDrafts();
+ expect(stored).toHaveLength(1);
+ expect(decodeBase64Utf8(stored[0].content.body_html ?? '')).toContain(
+ 'My offline reply'
+ );
+ expect(stored[0]).toMatchObject({
+ threadId: 'thread',
+ content: {
+ replying_to_id: 'parent',
+ to: [expect.objectContaining({ email: '[email protected]' })],
+ },
+ });
+ const reopened = createRoot((dispose) => {
+ const source = createEmailThreadSource(() => 'thread', {
+ transport: 'graphql',
+ isSuccess: true,
+ isError: false,
+ resolvedThreadId: 'thread',
+ data: {
+ thread: {
+ db_id: 'thread',
+ link_id: 'inbox',
+ access_level: 'owner',
+ messages: [parent],
+ },
+ hasMore: false,
+ },
+ } as unknown as ThreadQueryResult<ThreadQueryData>);
+ const selected = createMemo(() => {
+ const thread = source.thread();
+ return thread && selectThreadMessages(thread);
+ });
+ return { dispose, drafts: createThreadDrafts(selected) };
+ });
+ try {
+ await vi.waitFor(() =>
+ expect(reopened.drafts.getDraftForMessage('parent')).toBeDefined()
+ );
+ expect(
+ decodeBase64Utf8(
+ reopened.drafts.getDraftForMessage('parent')!.body_html_sanitized ??
+ ''
+ )
+ ).toContain('My offline reply');
+ } finally {
+ reopened.dispose();
+ }
+ }
+);
diff --git a/apps/web/src/features/email-thread/queries/thread-source.ts b/apps/web/src/features/email-thread/queries/thread-source.ts
index 77326ba677..81f832d00c 100644
--- a/apps/web/src/features/email-thread/queries/thread-source.ts
+++ b/apps/web/src/features/email-thread/queries/thread-source.ts
@@ -1,4 +1,6 @@
import { invalidateInvitationScheduling } from '@queries/calendar/invitations';
+import { createLocalDraftSource } from '@queries/email/local-draft-source';
+import { localDraftMessage } from '@queries/email/local-drafts';
import type { ThreadQueryData, ThreadQueryResult } from '@queries/email/thread';
import type { ApiThread } from '@service-email/generated/schemas';
import { type Accessor, createEffect, createMemo, on } from 'solid-js';
@@ -122,7 +124,66 @@ export function createEmailThreadSource(
};
}
);
- const thread = () => snapshot().thread;
+ const local = createLocalDraftSource(() => query.transport === 'graphql');
+ const discoveringDrafts = () =>
+ query.transport === 'graphql' && !local.ready();
+ const thread = () => {
+ const base = snapshot().thread;
+ if (query.transport !== 'graphql') return base;
+ // Establish the recovered draft before a reply editor can latch its seed.
+ if (discoveringDrafts()) return undefined;
+ const requested = threadId();
+ const copies = local
+ .drafts()
+ .filter(
+ (draft) =>
+ [draft.threadId, draft.serverThreadId].includes(requested) ||
+ (base && [draft.threadId, draft.serverThreadId].includes(base.db_id))
+ );
+ const edits = copies.filter(
+ (draft) =>
+ draft.status !== 'synced' &&
+ !(
+ draft.status === 'deleting' &&
+ draft.queuedAttemptId &&
+ draft.queuedAttemptId === draft.latestAttemptId
+ )
+ );
+ const messages = edits.map(localDraftMessage);
+ if (!base) {
+ const draft = edits.find((draft) => !draft.content.replying_to_id);
+ if (!draft) return undefined;
+ return {
+ access_level: 'owner' as const,
+ db_id: draft.serverThreadId ?? draft.threadId ?? requested,
+ inbox_visible: true,
+ is_read: true,
+ link_id: draft.inboxId ?? '',
+ messages,
+ };
+ }
+ const ids = new Set(
+ copies
+ .filter((draft) => draft.status !== 'synced')
+ .flatMap((draft) => [draft.draftId, draft.serverDraftId])
+ );
+ return copies.length
+ ? {
+ ...base,
+ messages: [
+ ...base.messages.filter(
+ (message) => !message.is_draft || !ids.has(message.db_id)
+ ),
+ ...messages.filter(
+ (message) =>
+ !base.messages.some(
+ (saved) => saved.db_id === message.db_id && !saved.is_draft
+ )
+ ),
+ ],
+ }
+ : base;
+ };
// Memo equality prevents ordinary email refreshes from revalidating calendar state.
const scheduling = createMemo(
() => {
@@ -154,8 +215,11 @@ export function createEmailThreadSource(
return {
id: () => thread()?.db_id ?? query.resolvedThreadId ?? threadId(),
thread,
- isError: () => query.isError,
- isLoading: () => query.isLoading,
+ isError: () =>
+ query.isError && (query.transport !== 'graphql' || !thread()),
+ isLoading: () =>
+ discoveringDrafts() ||
+ (query.isLoading && (query.transport !== 'graphql' || !thread())),
isFetching: () => query.isFetching,
isFetchingOlder: () => query.isFetchingNextPage,
hasMore: () => query.hasNextPage,
diff --git a/apps/web/src/features/email-thread/views/thread-reply-input.test.tsx b/apps/web/src/features/email-thread/views/thread-reply-input.test.tsx
index 39a0336402..aa32c59462 100644
--- a/apps/web/src/features/email-thread/views/thread-reply-input.test.tsx
+++ b/apps/web/src/features/email-thread/views/thread-reply-input.test.tsx
@@ -1,7 +1,9 @@
-import { render } from '@solidjs/testing-library';
+import type { ThreadQueryData, ThreadQueryResult } from '@queries/email/thread';
+import { render, waitFor } from '@solidjs/testing-library';
import { createSignal, type JSX, onCleanup } from 'solid-js';
import { beforeEach, expect, it, vi } from 'vitest';
import type { EmailReplySession } from '../../email-compose/context/email-form-inputs';
+import type { LocalDraft } from '../../email-compose/core/local-draft';
import { createComposeContext } from '../../email-compose/tests/capabilities';
import type { EmailMessage } from '../../email-message/core/email-message';
import { EmailThreadStateProvider } from '../context/email-thread-state-context';
@@ -10,6 +12,7 @@ import {
createEmailThreadState,
type EmailThreadState,
} from '../primitives/email-thread-state';
+import { createEmailThreadSource } from '../queries/thread-source';
import { createThreadContext, message, thread } from '../tests/fixtures';
import { ThreadReplyInput } from './thread-reply-input';
@@ -17,9 +20,28 @@ const lifecycle = vi.hoisted(() => ({
mounted: [] as string[],
disposed: [] as string[],
}));
+const discovery = vi.hoisted(() => ({
+ list: vi.fn<() => Promise<LocalDraft[]>>(async () => []),
+ subscribe: vi.fn<(listener: () => void) => () => void>(() => () => {}),
+}));
+vi.mock('@queries/email/local-drafts', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@queries/email/local-drafts')>()),
+ listLocalDrafts: discovery.list,
+ localDraftStore: { subscribe: discovery.subscribe },
+}));
+vi.mock('@queries/client', () => ({
+ queryClient: {
+ getQueryCache: () => ({ subscribe: () => () => {} }),
+ },
+}));
+vi.mock('@queries/calendar/invitations', () => ({
+ invalidateInvitationScheduling: vi.fn(),
+}));
beforeEach(() => {
lifecycle.mounted.length = 0;
lifecycle.disposed.length = 0;
+ discovery.list.mockReset().mockResolvedValue([]);
+ discovery.subscribe.mockClear();
});
// Probe the wrapper's editor lifetime and focus handoff. This does not verify
// the real rich editor, which still depends on shared application providers.
@@ -28,26 +50,115 @@ vi.mock('../../email-compose/views/reply-input', () => ({
replyingTo: () => { db_id: string };
onEngaged: () => void;
session: EmailReplySession;
+ preloadedHtml: string;
+ sideEffectOnSend?: (id: string) => Promise<void>;
}) => {
const id = props.replyingTo().db_id;
lifecycle.mounted.push(id);
onCleanup(() => lifecycle.disposed.push(id));
return (
<>
- <button onClick={props.onEngaged}>{id}</button>
+ <button onClick={props.onEngaged}>
+ {id}
+ <span>{props.preloadedHtml}</span>
+ </button>
<button onClick={() => props.session.exitToThread('last')}>
Exit reply
</button>
+ <button onClick={() => void props.sideEffectOnSend?.('sent')}>
+ Complete send
+ </button>
</>
);
},
}));
+it('waits for local reply discovery before mounting an editor and preserves it during refresh', async () => {
+ const pending = Promise.withResolvers<LocalDraft[]>();
+ discovery.list.mockReturnValueOnce(pending.promise);
+ const parent = message('parent');
+ let source!: ReturnType<typeof createEmailThreadSource>;
+ const view = render(() => {
+ source = createEmailThreadSource(() => 'thread', {
+ transport: 'graphql',
+ isSuccess: true,
+ isLoading: false,
+ isError: false,
+ resolvedThreadId: 'thread',
+ data: { thread: thread([parent]), hasMore: false },
+ } as ThreadQueryResult<ThreadQueryData>);
+ const context = createThreadContext(source);
+ const state = createEmailThreadState(context);
+ return (
+ <EmailThreadViewProvider
+ value={{
+ thread: context,
+ compose: createComposeContext(),
+ rendering: {},
+ }}
+ >
+ <EmailThreadStateProvider value={state}>
+ <ThreadReplyInput
+ replyingTo={() => parent}
+ draft={state.drafts.getDraftForMessage(parent.db_id)}
+ />
+ </EmailThreadStateProvider>
+ </EmailThreadViewProvider>
+ );
+ });
+ try {
+ expect(source.isLoading()).toBe(true);
+ expect(lifecycle.mounted).toEqual([]);
+ await waitFor(() => expect(discovery.list).toHaveBeenCalledOnce());
+ pending.resolve([
+ {
+ key: 'local-reply',
+ accountId: 'owner',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ draftId: 'local-reply',
+ threadId: 'thread',
+ content: {
+ subject: 'Reply',
+ replying_to_id: 'parent',
+ body_html: btoa('<p>Recovered reply</p>'),
+ },
+ attachments: [],
+ status: 'dirty',
+ updatedAt: Date.now(),
+ },
+ ]);
+ await waitFor(() =>
+ expect(view.getByText('<p>Recovered reply</p>')).toBeDefined()
+ );
+ expect(source.isLoading()).toBe(false);
+ expect(lifecycle.mounted).toEqual(['parent']);
+ view.getByText('parent').click();
+ const refresh = Promise.withResolvers<LocalDraft[]>();
+ discovery.list.mockReturnValueOnce(refresh.promise);
+ discovery.subscribe.mock.calls[0][0]();
+ expect(source.isLoading()).toBe(false);
+ expect(view.getByText('<p>Recovered reply</p>')).toBeDefined();
+ refresh.resolve([]);
+ await waitFor(() => expect(discovery.list).toHaveBeenCalledTimes(2));
+ expect(lifecycle.mounted).toEqual(['parent']);
+ expect(lifecycle.disposed).toEqual([]);
+ } finally {
+ pending.resolve([]);
+ view.unmount();
+ }
+});
+
function ThreadTestProvider(props: {
messages: EmailMessage[];
+ refresh?: () => Promise<void>;
children: (state: EmailThreadState) => JSX.Element;
}) {
- const context = createThreadContext({ thread: () => thread(props.messages) });
+ const context = createThreadContext({
+ thread: () => thread(props.messages),
+ ...(props.refresh && { refresh: props.refresh }),
+ });
const state = createEmailThreadState(context);
return (
<EmailThreadViewProvider
@@ -85,6 +196,44 @@ it('preserves an engaged composer through a same-message update but resets it fo
}
});
+it('focuses the sent card in its own pane before the thread refresh finishes', async () => {
+ vi.stubGlobal('CSS', { escape: (value: string) => value });
+ const refresh = Promise.withResolvers<void>();
+ const parent = message('parent');
+ const Pane = () => (
+ <ThreadTestProvider
+ messages={[parent, message('sent')]}
+ refresh={() => refresh.promise}
+ >
+ {(state) => (
+ <div ref={state.registerMessagesContainer}>
+ <div tabIndex={0} data-testid="sent-card">
+ <div data-message-body-id="sent" />
+ </div>
+ <ThreadReplyInput replyingTo={() => parent} />
+ </div>
+ )}
+ </ThreadTestProvider>
+ );
+ const view = render(() => (
+ <>
+ <Pane />
+ <Pane />
+ </>
+ ));
+ try {
+ view.getAllByText('Complete send')[1].click();
+ expect(document.activeElement).toBe(view.getAllByTestId('sent-card')[1]);
+ refresh.resolve();
+ await refresh.promise;
+ expect(document.activeElement).toBe(view.getAllByTestId('sent-card')[1]);
+ } finally {
+ refresh.resolve();
+ view.unmount();
+ vi.unstubAllGlobals();
+ }
+});
+
it('returns focus to the owning thread when split panes contain the same message', () => {
vi.stubGlobal('CSS', { escape: (value: string) => value });
const parent = message('shared-message');
diff --git a/apps/web/src/features/email-thread/views/thread-reply-input.tsx b/apps/web/src/features/email-thread/views/thread-reply-input.tsx
index 831581a17b..132e4fb98e 100644
--- a/apps/web/src/features/email-thread/views/thread-reply-input.tsx
+++ b/apps/web/src/features/email-thread/views/thread-reply-input.tsx
@@ -67,13 +67,25 @@ function ThreadReplyInputSession(props: ThreadReplyInputProps) {
return decodedHtml;
});
+ function focusMessage(id: string) {
+ ctx.messages.setFocused(id);
+ const message = ctx
+ .messagesContainerRef()
+ ?.querySelector<HTMLElement>(
+ `[data-message-body-id="${CSS.escape(id)}"]`
+ );
+ const card = message?.closest<HTMLElement>('[tabindex="0"]');
+ card?.focus({ preventScroll: true });
+ return !!card;
+ }
+
async function afterSend(newMessageId: string | null) {
// Collapse the input after sending (Gmail-style).
props.setShowReply?.(false);
if (!newMessageId) return;
- ctx.messages.setFocused(newMessageId);
+ focusMessage(newMessageId);
await ctx.query.refetch();
revealMessageAfterLayout(
newMessageId,
@@ -121,15 +133,7 @@ function ThreadReplyInputSession(props: ThreadReplyInputProps) {
? ctx.messages.list().at(-1)?.db_id
: ctx.messages.focusedId();
if (!id) return false;
- ctx.messages.setFocused(id);
- const message = ctx
- .messagesContainerRef()
- ?.querySelector<HTMLElement>(
- `[data-message-body-id="${CSS.escape(id)}"]`
- );
- const card = message?.closest<HTMLElement>('[tabindex="0"]');
- card?.focus();
- return !!card;
+ return focusMessage(id);
},
}}
sourceEntityId={
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
index 0b5e415aa9..47cfbfef94 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
@@ -65,6 +65,11 @@ import {
unreadFilterFn,
} from '@entity';
import { useQueryClient } from '@queries/client';
+import {
+ createLocalDraftSource,
+ localDraftEntities,
+ localDraftMatchesFilters,
+} from '@queries/email/local-draft-source';
import { invalidateUserNotifications } from '@queries/notification/user-notifications';
import { createGroupedSoupQueries } from '@queries/soup/grouped/create-grouped-soup-queries';
import type {
@@ -991,13 +996,28 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
const itemsSource = () => soupItemsSource;
+ const localDrafts = createLocalDraftSource(
+ () => itemsQuery.transport === 'graphql'
+ );
+ const localDraftRows = () => {
+ const filters = applyViewFilters(queryFilters.state);
+ if (!search.isSearching() && filters.emailView !== 'drafts') return [];
+ return localDraftEntities(
+ localDrafts
+ .drafts()
+ .filter((draft) => localDraftMatchesFilters(draft, filters))
+ ).map((entity) => attachNotifications(entity)) as SoupEntity[];
+ };
const items = createMemo<SoupEntity[]>(
(prev) => {
const searching = search.isSearching();
if (!searching) {
const data = itemsSource().data();
- const extras = config().additionalEntities?.() ?? [];
+ const extras = [
+ ...(config().additionalEntities?.() ?? []),
+ ...localDraftRows(),
+ ];
const extraEntities = extras.map((e) =>
isWithNotification(e) ? e : attachNotifications(e)
) as SoupEntity[];
@@ -1008,9 +1028,11 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
// navigation. Once the active query fails, those rows belong to
// the previous query and must go so the load-error state can
// render — only client-local rows remain valid.
- return itemsSource().error() ? extraEntities : prev;
+ return itemsSource().error()
+ ? extraEntities
+ : deduplicateEntities([...extraEntities, ...prev]);
}
- if (data.groups) return prev;
+ if (data.groups) return localDraftRows();
const base = data.entities.map((e) =>
isWithNotification(e) ? e : attachNotifications(e)
@@ -1018,13 +1040,25 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
if (extraEntities.length === 0) return base;
- return [...extraEntities, ...base];
+ const extraIds = new Set(
+ extraEntities.map((entity) => `${entity.type}:${entity.id}`)
+ );
+ return [
+ ...extraEntities,
+ ...base.filter(
+ (entity) => !extraIds.has(`${entity.type}:${entity.id}`)
+ ),
+ ];
}
const local = search.localFuzzyResults();
const service = search.serviceSearchResults();
- const merged: SoupEntity[] = [...service, ...local];
+ const needle = search.searchText().toLowerCase();
+ const recovery = localDraftRows().filter((entity) =>
+ entity.name.toLowerCase().includes(needle)
+ );
+ const merged: SoupEntity[] = [...recovery, ...service, ...local];
if (
merged.length === 0 &&
@@ -1377,17 +1411,56 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
const result: SoupRow[] = [];
let globalIndex = 0;
+ // Local working copies have no server group membership yet. Keep them
+ // discoverable, subject to the same filters as the flat Drafts view.
+ const recovery = entities();
+ const recoveryIds = new Set(
+ recovery.map((entity) => `${entity.type}:${entity.id}`)
+ );
+ if (recovery.length) {
+ const key = 'local-email-drafts';
+ const group: GroupMeta = {
+ key,
+ value: key,
+ label: 'Saved on this device',
+ count: recovery.length,
+ isExpanded: () => soup.grouping.isExpanded(key),
+ toggle: () => soup.grouping.toggle(key),
+ };
+ result.push(
+ soup.buildRow({
+ id: `header:${key}`,
+ index: globalIndex++,
+ original: recovery[0],
+ group,
+ isGrouped: true,
+ })
+ );
+ for (const entity of recovery)
+ result.push(
+ soup.buildRow({
+ id: entity.id,
+ index: globalIndex++,
+ original: entity,
+ group,
+ })
+ );
+ }
for (const apiGroup of groups) {
const groupMeta = buildGroupMeta(apiGroup);
const groupData = groupQueryFor(apiGroup.key)?.data();
const groupEntities =
- groupData?.entities?.map(
- (entity) =>
- (isWithNotification(entity)
- ? entity
- : attachNotifications(entity)) as SoupEntity
- ) ?? [];
+ groupData?.entities
+ ?.map(
+ (entity) =>
+ (isWithNotification(entity)
+ ? entity
+ : attachNotifications(entity)) as SoupEntity
+ )
+ .filter(
+ (entity) => !recoveryIds.has(`${entity.type}:${entity.id}`)
+ ) ?? [];
const firstEntity = groupEntities[0];
if (!firstEntity) continue;
@@ -1437,6 +1510,12 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
const searchSourceError = () =>
(searchQuery.error as Error | null) ??
nativeOfflineLoadError(searchSourceHasData);
+ const hasLocalRecoveryRows = () => {
+ const ids = new Set(localDraftRows().map((entity) => entity.id));
+ return entities().some(
+ (entity) => entity.type === 'email' && ids.has(entity.id)
+ );
+ };
const context = {
extensions: props.extensions,
@@ -1454,6 +1533,7 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
search.isSearching()
? searchSourceHasData()
: itemsSource().hasData() ||
+ hasLocalRecoveryRows() ||
// Rows retained across a query rebind count as data so the view
// doesn't flash, but once the query errors only client-local
// rows remain and must not suppress the load-error state.
diff --git a/apps/web/src/lib/core/auth/logout.test.ts b/apps/web/src/lib/core/auth/logout.test.ts
index ae12fd83c0..e12ad89fba 100644
--- a/apps/web/src/lib/core/auth/logout.test.ts
+++ b/apps/web/src/lib/core/auth/logout.test.ts
@@ -1,10 +1,12 @@
import { notificationKeys } from '@queries/notification/keys';
import { graphqlSoupKeys } from '@queries/soup/graphql/keys';
import { isCancelledError, QueryClient } from '@tanstack/solid-query';
+import { createRoot } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
-const { client } = vi.hoisted(() => ({
+const { client, navigate } = vi.hoisted(() => ({
client: { current: undefined as QueryClient | undefined },
+ navigate: vi.fn(),
}));
vi.mock('@queries/client', () => ({
get queryClient() {
@@ -12,11 +14,18 @@ vi.mock('@queries/client', () => ({
},
}));
vi.mock('@app/lib/analytics/analytics-context', () => ({
- useAnalytics: vi.fn(),
+ useAnalytics: () => ({ track: vi.fn(), reset: vi.fn() }),
+}));
+vi.mock('@solidjs/router', () => ({ useNavigate: () => navigate }));
+vi.mock('@ui', () => ({ confirmDialog: vi.fn(async () => false) }));
+vi.mock('@queries/email/local-drafts', () => ({
+ clearLocalDrafts: vi.fn(async () => {}),
+ flushLocalDrafts: vi.fn(async () => {}),
+ listLocalDrafts: vi.fn(async () => []),
}));
vi.mock('@core/constant/servers', () => ({ SERVER_HOSTS: {} }));
vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
- isNativeMobilePlatform: () => false,
+ isNativeMobilePlatform: vi.fn(() => false),
}));
vi.mock('@core/util/cookies', () => ({ syncLoginStorage: vi.fn() }));
vi.mock('@graphql-cache/lifecycle', () => ({
@@ -35,10 +44,18 @@ vi.mock('@service-auth/client', () => ({
authServiceClient: { logout: vi.fn() },
}));
vi.mock('./push-registration-lifecycle', () => ({
- unregisterPushRegistrationsForLogout: vi.fn(),
+ unregisterPushRegistrationsForLogout: vi.fn(async () => {}),
}));
-import { clearLocalAuthSession } from './logout';
+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
+import {
+ clearLocalDrafts,
+ flushLocalDrafts,
+ listLocalDrafts,
+} from '@queries/email/local-drafts';
+import { authServiceClient } from '@service-auth/client';
+import { confirmDialog } from '@ui';
+import { clearLocalAuthSession, useLogout } from './logout';
describe('logout notification cache isolation', () => {
it('retires pending Done buckets and rotates the display-intent session', async () => {
@@ -53,6 +70,7 @@ describe('logout notification cache isolation', () => {
'old-session'
);
await clearLocalAuthSession();
+ expect(clearLocalDrafts).toHaveBeenCalled();
expect(queryClient.getQueryData(first)).toBeUndefined();
expect(queryClient.getQueryData(second)).toBeUndefined();
expect(
@@ -105,3 +123,84 @@ describe('logout notification cache isolation', () => {
queryClient.clear();
});
});
+
+describe('local draft logout warning', () => {
+ it('reloads the native login document only after local cleanup and navigation', async () => {
+ const order: string[] = [];
+ client.current = new QueryClient();
+ vi.mocked(isNativeMobilePlatform).mockReturnValue(true);
+ vi.mocked(clearLocalDrafts).mockImplementationOnce(async () => {
+ order.push('clear');
+ });
+ navigate.mockImplementationOnce(() => {
+ order.push('navigate');
+ });
+ const reload = vi.fn(() => {
+ order.push('reload');
+ });
+ vi.stubGlobal('window', { location: { reload } });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response())
+ );
+ const { logout, dispose } = createRoot((dispose) => ({
+ logout: useLogout(),
+ dispose,
+ }));
+ try {
+ await logout();
+ expect(order).toEqual(['clear', 'navigate', 'reload']);
+ expect(navigate).toHaveBeenLastCalledWith('/login');
+ expect(reload).toHaveBeenCalledOnce();
+ } finally {
+ dispose();
+ vi.mocked(isNativeMobilePlatform).mockReturnValue(false);
+ vi.mocked(authServiceClient.logout).mockClear();
+ vi.unstubAllGlobals();
+ client.current.clear();
+ }
+ });
+ it('allows cancelling logout when drafts have unsynced changes', async () => {
+ vi.mocked(listLocalDrafts).mockResolvedValueOnce([
+ { status: 'failed' },
+ ] as Awaited<ReturnType<typeof listLocalDrafts>>);
+ const { logout, dispose } = createRoot((dispose) => ({
+ logout: useLogout(),
+ dispose,
+ }));
+ try {
+ await logout();
+ expect(confirmDialog).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ body: expect.stringContaining('1 draft(s)'),
+ }),
+ expect.anything()
+ );
+ expect(authServiceClient.logout).not.toHaveBeenCalled();
+ } finally {
+ dispose();
+ }
+ });
+
+ it('offers a warning and cancellation when local storage cannot be checked', async () => {
+ vi.mocked(flushLocalDrafts).mockRejectedValueOnce(
+ new Error('Disk unavailable')
+ );
+ const { logout, dispose } = createRoot((dispose) => ({
+ logout: useLogout(),
+ dispose,
+ }));
+ try {
+ await logout();
+ expect(confirmDialog).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ body: expect.stringContaining('could not be checked'),
+ }),
+ expect.anything()
+ );
+ expect(authServiceClient.logout).not.toHaveBeenCalled();
+ } finally {
+ dispose();
+ }
+ });
+});
diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.ts
index 5dc38f3929..a3e92a1563 100644
--- a/apps/web/src/lib/core/auth/logout.ts
+++ b/apps/web/src/lib/core/auth/logout.ts
@@ -8,6 +8,11 @@ import { clearRegisteredCaches } from '@graphql-cache/lifecycle';
import { authKeys, type UserInfoData } from '@queries/auth/user-info';
import { queryClient } from '@queries/client';
import { emailKeys } from '@queries/email/keys';
+import {
+ clearLocalDrafts,
+ flushLocalDrafts,
+ listLocalDrafts,
+} from '@queries/email/local-drafts';
import { notificationKeys } from '@queries/notification/keys';
import { propertiesKeys } from '@queries/properties/keys';
import { resetGraphqlSoupDoneSession } from '@queries/soup/graphql/done-session';
@@ -17,6 +22,8 @@ import { authServiceClient } from '@service-auth/client';
import { raceTimeout } from '@solid-primitives/promise';
import { createCallback } from '@solid-primitives/rootless';
import { useNavigate } from '@solidjs/router';
+import { confirmDialog } from '@ui';
+import { getOwner } from 'solid-js';
import { unregisterPushRegistrationsForLogout } from './push-registration-lifecycle';
const unauthenticatedUserInfo: UserInfoData = {
@@ -53,15 +60,57 @@ export async function clearLocalAuthSession() {
// Queued mutations are user intent; never allow them to replay under a
// subsequent account sharing this anonymous device cache scope.
- await Promise.all([documentContextsCleared, clearRegisteredCaches()]);
+ await Promise.all([
+ documentContextsCleared,
+ clearRegisteredCaches(),
+ clearLocalDrafts(),
+ ]);
clearMcpAuthAttempts();
}
export function useLogout() {
const analytics = useAnalytics();
const navigate = useNavigate();
+ const owner = getOwner();
return createCallback(async () => {
+ let warning: string | undefined;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const inspectDrafts = async () => {
+ await flushLocalDrafts();
+ return await listLocalDrafts();
+ };
+ const drafts = await Promise.race([
+ inspectDrafts(),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('Draft storage timed out')),
+ 3000
+ );
+ }),
+ ]);
+ const unsynced = drafts.filter((draft) => draft.status !== 'synced');
+ if (unsynced.length)
+ warning = `${unsynced.length} draft(s) have changes saved only on this device. Signing out removes those changes and their pending attachments.`;
+ } catch {
+ warning =
+ 'Draft storage could not be checked. Signing out removes drafts and attachments saved only on this device, including any changes that have not synced.';
+ } finally {
+ clearTimeout(timer);
+ }
+ if (
+ warning &&
+ !(await confirmDialog(
+ {
+ title: 'Sign out and remove local drafts?',
+ body: warning,
+ confirmLabel: 'Sign out',
+ },
+ { owner }
+ ))
+ )
+ return;
clearPostLoginRedirect();
// Must run before the session is torn down — the unregister call is
// authenticated. Time-boxed so a hung request can't block logout.
@@ -78,6 +127,9 @@ export function useLogout() {
redirect: 'manual',
}).catch(() => {});
navigate('/login');
+ // Native login reuses this WebView. End the document lifetime so queued
+ // editor callbacks can never adopt the next account's draft session.
+ window.location.reload();
} else {
window.location.href = SERVER_HOSTS['auth-logout'];
}
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
index b2a02bc03b..2165df6d05 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
@@ -246,6 +246,7 @@ function makeFakeHost(): FakeHost {
return {
transactionId: head.transactionId,
uuid: head.args.uuid,
+ clientMetadata: head.args.clientMetadata,
superseded: false,
requiresConfirmation: false,
leaseGeneration: String(head.attemptCount),
@@ -2420,6 +2421,50 @@ describe('normalizedCacheExchange', () => {
describe('mutations', () => {
const optimistic = { setEntityProperty: { id: 'prop-1' } };
+ it('carries submitted client metadata through queue admission and settlement', async () => {
+ const enqueue = vi.spyOn(host, 'enqueueOptimisticMutation');
+ const metadata = {
+ kind: 'email-draft',
+ id: 'discard-attempt',
+ revision: 7,
+ };
+ const beforeMutationAttempt = vi.fn(
+ async (mutation: ClaimedMutation) =>
+ mutation.clientMetadata?.id === metadata.id
+ );
+ const onMutationAttemptResult = vi.fn(async () => {});
+ const { client, forwarded } = harness(host, undefined, {
+ beforeMutationAttempt,
+ onMutationAttemptResult,
+ });
+ await executeOptimisticMutation(
+ client,
+ MUTATION,
+ { input: {} },
+ optimistic,
+ {
+ uuid: crypto.randomUUID(),
+ clientMetadata: metadata,
+ }
+ ).toPromise();
+ await tick();
+ expect(enqueue).toHaveBeenCalledWith(
+ expect.objectContaining({ clientMetadata: metadata }),
+ expect.anything()
+ );
+ expect(beforeMutationAttempt).toHaveBeenCalledWith(
+ expect.objectContaining({ clientMetadata: metadata })
+ );
+ expect(forwarded).toHaveLength(1);
+ expect(forwarded[0].variables).toEqual({ input: {} });
+ expect(onMutationAttemptResult).toHaveBeenCalledWith(
+ expect.objectContaining({ clientMetadata: metadata }),
+ expect.anything(),
+ false
+ );
+ expect(host.commits).toHaveLength(1);
+ });
+
it.each([false, true])(
'rolls back rejected favorites rather than committing list patches (replay=%s)',
async (replay) => {
@@ -2576,8 +2621,183 @@ describe('normalizedCacheExchange', () => {
expect(host.commits[0]?.transactionId).toBe('restored-1');
});
+ it.each(['rejects', 'hangs'] as const)(
+ 'advances after a terminal draft error even when recovery bookkeeping %s',
+ async (failure) => {
+ vi.useFakeTimers();
+ try {
+ const metadata = { kind: 'email-draft', revision: 7 };
+ host.seedQueued({
+ uuid: 'draft-handle',
+ query: stringifyDocument(SaveEmailDraftDocument),
+ operationName: 'SaveEmailDraft',
+ variables: { input: { draftId: 'draft-handle' } },
+ data: optimistic,
+ clientMetadata: metadata,
+ });
+ host.seedQueued({
+ uuid: 'unrelated',
+ query: stringifyDocument(MUTATION),
+ operationName: 'SetEntityProperty',
+ variables: { input: {} },
+ data: optimistic,
+ });
+ const onMutationAttemptResult = vi.fn(
+ async (mutation: ClaimedMutation) => {
+ if (mutation.operationName !== 'SaveEmailDraft') return;
+ if (failure === 'rejects')
+ throw new Error('Recovery disk unavailable');
+ await new Promise<void>(() => {});
+ }
+ );
+ const { forwarded } = harness(
+ host,
+ (op) =>
+ 'draftId' in op.variables!.input
+ ? {
+ data: undefined,
+ error: new CombinedError({
+ graphQLErrors: [
+ {
+ message: 'Draft rejected',
+ extensions: { retryable: true },
+ },
+ ],
+ }),
+ }
+ : { data: { saved: true } },
+ {
+ shouldRetryMutation: shouldRetryGraphqlMutation,
+ onMutationAttemptResult,
+ onCacheError: () => {
+ throw new Error('Diagnostics unavailable');
+ },
+ }
+ );
+ await vi.advanceTimersByTimeAsync(2_010);
+ expect(onMutationAttemptResult).toHaveBeenCalledWith(
+ expect.objectContaining({ clientMetadata: metadata }),
+ expect.anything(),
+ false
+ );
+ expect(host.rollbacks).toEqual(['restored-1']);
+ expect(host.defers).toHaveLength(0);
+ expect(host.commits).toMatchObject([{ transactionId: 'restored-2' }]);
+ expect(forwarded).toHaveLength(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ }
+ );
+
+ it.each(['rejects', 'hangs'] as const)(
+ 'replays unrelated mutations when recovery initialization %s',
+ async (failure) => {
+ vi.useFakeTimers();
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ host.seedQueued({
+ uuid: 'unrelated',
+ query: stringifyDocument(MUTATION),
+ operationName: 'SetEntityProperty',
+ variables: { input: {} },
+ data: optimistic,
+ });
+ const { forwarded } = harness(host, undefined, {
+ prepareMutationQueue: async () => {
+ if (failure === 'rejects')
+ throw new Error('IndexedDB unavailable');
+ await new Promise<void>(() => {});
+ },
+ });
+ await vi.advanceTimersByTimeAsync(4_010);
+ expect(forwarded).toHaveLength(1);
+ expect(host.commits).toMatchObject([{ transactionId: 'restored-1' }]);
+ expect(warning).toHaveBeenCalled();
+ } finally {
+ warning.mockRestore();
+ vi.useRealTimers();
+ }
+ }
+ );
+
+ it.each([
+ { failure: 'rejects', legacy: false },
+ { failure: 'hangs', legacy: false },
+ { failure: 'rejects', legacy: true },
+ { failure: 'hangs', legacy: true },
+ ])(
+ 'releases a draft when admission $failure (legacy=$legacy)',
+ async ({ failure, legacy }) => {
+ vi.useFakeTimers();
+ try {
+ host.seedQueued({
+ uuid: 'draft',
+ query: stringifyDocument(SaveEmailDraftDocument),
+ operationName: 'SaveEmailDraft',
+ variables: { input: { draftId: 'draft' } },
+ data: optimistic,
+ clientMetadata: legacy ? undefined : { kind: 'email-draft' },
+ });
+ host.seedQueued({
+ uuid: 'other',
+ query: stringifyDocument(MUTATION),
+ operationName: 'SetEntityProperty',
+ variables: { input: {} },
+ data: optimistic,
+ });
+ const onMutationAttemptResult = vi.fn(async () => {});
+ const { forwarded } = harness(host, undefined, {
+ beforeMutationAttempt: async (mutation) => {
+ if (mutation.operationName !== 'SaveEmailDraft') return true;
+ if (failure === 'rejects')
+ throw new Error('Recovery storage unavailable');
+ return await new Promise<boolean>(() => {});
+ },
+ onMutationAttemptResult,
+ });
+ await vi.advanceTimersByTimeAsync(2_010);
+ expect(host.rollbacks).toEqual(['restored-1']);
+ expect(host.defers).toHaveLength(0);
+ expect(host.commits).toMatchObject([{ transactionId: 'restored-2' }]);
+ expect(forwarded).toHaveLength(1);
+ expect(onMutationAttemptResult).toHaveBeenCalledWith(
+ expect.objectContaining({ transactionId: 'restored-1' }),
+ expect.objectContaining({
+ error: expect.objectContaining({
+ message: expect.stringContaining('Unable to prepare'),
+ }),
+ }),
+ false
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ }
+ );
+
+ it('returns a terminal recovery failure to a live caller without sending it', async () => {
+ const { ops, results, forwarded } = harness(host, undefined, {
+ beforeMutationAttempt: async () => {
+ throw new Error('Local storage unavailable');
+ },
+ });
+ ops.next(makeMutationOp(1, optimistic));
+ await vi.waitFor(() => expect(results).toHaveLength(1));
+ expect(forwarded).toHaveLength(0);
+ expect(host.defers).toHaveLength(0);
+ expect(host.rollbacks).toEqual(['txn-1']);
+ expect(optimisticMutationDispositionOf(results[0])).toMatchObject({
+ kind: 'permanently-failed',
+ error: results[0]?.error,
+ });
+ expect(results[0]?.error?.graphQLErrors[0]?.extensions.code).toBe(
+ 'LOCAL_RECOVERY_FAILED'
+ );
+ });
+
it.each([true, false])(
- 'only advances past an unavailable archived thread when its error is terminal (retryable=%s)',
+ 'advances past an unavailable archived thread regardless of legacy metadata (retryable=%s)',
async (retryable) => {
vi.useFakeTimers();
try {
@@ -2642,17 +2862,12 @@ describe('normalizedCacheExchange', () => {
{ shouldRetryMutation: shouldRetryGraphqlMutation }
);
await vi.advanceTimersByTimeAsync(10);
- if (retryable) {
- expect(forwarded).toHaveLength(1);
- expect(host.defers).toHaveLength(1);
- expect(host.commits).toHaveLength(0);
- } else {
- expect(forwarded).toHaveLength(2);
- expect(host.rollbacks).toEqual(['restored-1']);
- expect(host.commits).toMatchObject([
- { transactionId: 'restored-2', data: readResult },
- ]);
- }
+ expect(forwarded).toHaveLength(2);
+ expect(host.defers).toHaveLength(0);
+ expect(host.rollbacks).toEqual(['restored-1']);
+ expect(host.commits).toMatchObject([
+ { transactionId: 'restored-2', data: readResult },
+ ]);
} finally {
vi.useRealTimers();
}
@@ -2691,17 +2906,18 @@ describe('normalizedCacheExchange', () => {
replacementTransactionId: 'newer-intent',
});
}
- const error = new CombinedError({
- graphQLErrors: [
- {
- message: 'Draft rejected',
- extensions:
- outcome === 'retryable'
- ? { code: 'INTERNAL', retryable: true }
- : { code: 'DRAFT_ALREADY_SENT' },
- },
- ],
- });
+ const error = new CombinedError(
+ outcome === 'retryable'
+ ? { networkError: new Error('Connection lost') }
+ : {
+ graphQLErrors: [
+ {
+ message: 'Draft rejected',
+ extensions: { code: 'DRAFT_ALREADY_SENT' },
+ },
+ ],
+ }
+ );
const { client, forwarded } = harness(
host,
() => ({ error, data: undefined }),
@@ -2767,15 +2983,16 @@ describe('normalizedCacheExchange', () => {
};
const onCacheError = vi.fn();
const { forwarded } = harness(host, undefined, { onCacheError });
- await tick();
+ await vi.waitFor(() =>
+ expect(host.commits.map((commit) => commit.transactionId)).toEqual([
+ 'restored-1',
+ 'restored-2',
+ ])
+ );
expect(forwarded.map((op) => op.variables?.input.version)).toEqual([
'create',
'edit',
]);
- expect(host.commits.map((commit) => commit.transactionId)).toEqual([
- 'restored-1',
- 'restored-2',
- ]);
expect(host.defers).toEqual([]);
expect(onCacheError).not.toHaveBeenCalled();
}
@@ -4181,7 +4398,7 @@ describe('normalizedCacheExchange', () => {
++attempts <= 10
? { error, data: undefined }
: { data: optimistic },
- { shouldRetryMutation: shouldRetryGraphqlMutation }
+ { shouldRetryMutation: () => true }
);
ops.next(makeMutationOp(1, optimistic));
ops.next(makeMutationOp(2, optimistic));
@@ -4245,7 +4462,7 @@ describe('normalizedCacheExchange', () => {
data: undefined,
};
},
- { shouldRetryMutation: shouldRetryGraphqlMutation }
+ { shouldRetryMutation: () => true }
);
ops.next(makeMutationOp(1, optimistic));
await vi.advanceTimersByTimeAsync(0);
@@ -4264,7 +4481,7 @@ describe('normalizedCacheExchange', () => {
}
});
- it('uses the persisted budget on replay and revalidates after exhaustion', async () => {
+ it('uses the persisted budget on replay, records exhaustion and revalidates', async () => {
host.seedQueued(
{
uuid: crypto.randomUUID(),
@@ -4277,13 +4494,15 @@ describe('normalizedCacheExchange', () => {
9
);
const rollback = vi.spyOn(host, 'rollbackOptimisticWrite');
+ const onMutationAttemptResult = vi.fn(async () => {});
const error = new CombinedError({
graphQLErrors: [
{ message: 'still failing', extensions: { retryable: true } },
],
});
const { client } = harness(host, () => ({ error, data: undefined }), {
- shouldRetryMutation: shouldRetryGraphqlMutation,
+ shouldRetryMutation: () => true,
+ onMutationAttemptResult,
});
await tick();
expect(host.defers).toHaveLength(0);
@@ -4293,10 +4512,26 @@ describe('normalizedCacheExchange', () => {
expect.stringContaining('10 server failures'),
'MUTATION_RETRY_EXHAUSTED'
);
+ expect(onMutationAttemptResult).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ transactionId: 'restored-1',
+ serverFailureCount: 9,
+ }),
+ expect.objectContaining({
+ error: expect.objectContaining({
+ graphQLErrors: [
+ expect.objectContaining({
+ extensions: { code: 'MUTATION_RETRY_EXHAUSTED' },
+ }),
+ ],
+ }),
+ }),
+ false
+ );
expect(client.query).toHaveBeenCalledOnce();
});
- it('retries a draft response failure with the same handles and commits after recovery', async () => {
+ it('requires explicit retry after a draft application failure and preserves its handles', async () => {
vi.useFakeTimers();
try {
const variables = {
@@ -4348,30 +4583,37 @@ describe('normalizedCacheExchange', () => {
await vi.advanceTimersByTimeAsync(0);
expect(attempts).toBe(1);
- expect(host.rollbacks).toHaveLength(0);
- expect(host.defers).toEqual([
- { transactionId: 'txn-1', error: error.message },
- ]);
- expect(results[0]?.error).toBeUndefined();
+ expect(host.rollbacks).toEqual(['txn-1']);
+ expect(host.defers).toHaveLength(0);
+ expect(results[0]?.error).toBe(error);
expect(optimisticMutationDispositionOf(results[0])).toEqual({
- kind: 'queued',
- transactionId: 'txn-1',
+ kind: 'permanently-failed',
+ error,
});
await vi.advanceTimersByTimeAsync(1_000);
+ expect(attempts).toBe(1);
+ ops.next(
+ makeOperation(
+ 'mutation',
+ createRequest(SaveEmailDraftDocument, variables),
+ makeMutationOp(2, saved).context
+ )
+ );
+ await vi.advanceTimersByTimeAsync(0);
expect(attempts).toBe(2);
expect(forwarded.map((op) => op.variables)).toEqual([
variables,
variables,
]);
- expect(host.begins).toHaveLength(1);
+ expect(host.begins).toHaveLength(2);
expect(host.commits).toEqual([
expect.objectContaining({
- transactionId: 'txn-1',
+ transactionId: 'txn-2',
data: saved,
}),
]);
- expect(host.rollbacks).toHaveLength(0);
+ expect(host.rollbacks).toEqual(['txn-1']);
} finally {
vi.useRealTimers();
}
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
index cd20d27015..37538356ad 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
@@ -38,6 +38,7 @@
import {
type Client,
CombinedError,
+ createRequest,
type Exchange,
makeOperation,
type Operation,
@@ -109,6 +110,24 @@ const QUEUE_REQUEST_TIMEOUT_MS = 60_000;
const QUEUE_LEASE_MS = 5 * 60_000;
const EMPTY_QUEUE_POLL_MS = 30_000;
const MAX_MUTATION_SERVER_FAILURES = 10;
+const MUTATION_LIFECYCLE_TIMEOUT_MS = 2_000;
+
+async function boundedMutationLifecycle<T>(work: () => Promise<T>): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ work(),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('Mutation recovery timed out')),
+ MUTATION_LIFECYCLE_TIMEOUT_MS
+ );
+ }),
+ ]);
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+}
const NORMALIZED_CACHE_RESULT_METADATA_KEY = '__macroNormalizedCache';
@@ -167,6 +186,7 @@ function withResultMetadata(
}
type QueueAttemptContext = {
+ mutation?: ClaimedMutation;
transactionId: string;
leaseOwner: string;
leaseGeneration: string;
@@ -445,6 +465,16 @@ function mutationErrorCode(
}
export interface NormalizedCacheExchangeOptions {
+ /** Best-effort startup recovery before per-mutation admission. */
+ prepareMutationQueue?: () => Promise<void>;
+ /** False discards obsolete client intent without sending it to the server. */
+ beforeMutationAttempt?: (mutation: ClaimedMutation) => Promise<boolean>;
+ /** Persist domain recovery state for a replayed result, including when its UI is closed. */
+ onMutationAttemptResult?: (
+ mutation: ClaimedMutation,
+ result: OperationResult,
+ retry: boolean
+ ) => Promise<void>;
/** Domain-specific deletions inferred from a successful server response. */
deletedRecordKeys?: (result: OperationResult) => string[];
/** Return true to transfer a committed query refresh to an active reader's queue.
@@ -803,6 +833,7 @@ export function normalizedCacheExchange(
// is immediately resubscribed after a back/forward-cache restore.
const subscriptionGenerations = new Map<number, object>();
let attemptInFlight = false;
+ let queuePreparation: Promise<void> | undefined;
let drainRunning = false;
let drainRequested = false;
let deferredUntil: number | undefined;
@@ -839,12 +870,95 @@ export function normalizedCacheExchange(
async function routeClaimedMutation(
claimed: ClaimedMutation
): Promise<void> {
+ attemptInFlight = true;
+ try {
+ if (options.prepareMutationQueue) await prepareQueueRecovery();
+ if (
+ options.beforeMutationAttempt &&
+ !(await boundedMutationLifecycle(() =>
+ options.beforeMutationAttempt!(claimed)
+ ))
+ ) {
+ await host.rollbackOptimisticWrite(
+ claimed.transactionId,
+ { owner: queueOwner, generation: claimed.leaseGeneration },
+ 'Obsolete local intent',
+ 'LOCAL_SUPERSEDED'
+ );
+ attemptInFlight = false;
+ resolveLiveOperationsAsQueued();
+ scheduleDrain();
+ return;
+ }
+ } catch {
+ queuePreparation = undefined;
+ try {
+ const live = liveQueuedOps.get(claimed.transactionId);
+ const operation =
+ live?.operation ??
+ makeOperation(
+ 'mutation',
+ createRequest(
+ replayDocument(claimed.query, claimed.operationName),
+ claimed.variables
+ ),
+ { url: '', requestPolicy: 'network-only' }
+ );
+ const failure = new CombinedError({
+ graphQLErrors: [
+ {
+ message: 'Unable to prepare the saved mutation for replay',
+ extensions: { code: 'LOCAL_RECOVERY_FAILED' },
+ },
+ ],
+ });
+ const result: OperationResult = {
+ operation,
+ data: undefined,
+ error: failure,
+ stale: false,
+ hasNext: false,
+ };
+ await recordAttemptResult(
+ {
+ mutation: claimed,
+ transactionId: claimed.transactionId,
+ leaseOwner: queueOwner,
+ leaseGeneration: claimed.leaseGeneration,
+ attemptCount: claimed.attemptCount,
+ serverFailureCount: claimed.serverFailureCount ?? 0,
+ },
+ result,
+ false
+ );
+ await host.rollbackOptimisticWrite(
+ claimed.transactionId,
+ { owner: queueOwner, generation: claimed.leaseGeneration },
+ failure.message,
+ 'LOCAL_RECOVERY_FAILED'
+ );
+ liveQueuedOps.delete(claimed.transactionId);
+ live?.resolveRoute(
+ withOptimisticMutationDisposition(result, {
+ kind: 'permanently-failed',
+ transactionId: claimed.transactionId,
+ })
+ );
+ deferredUntil = undefined;
+ } finally {
+ attemptInFlight = false;
+ resolveLiveOperationsAsQueued();
+ scheduleDrain();
+ }
+ return;
+ }
deferredUntil = undefined;
// A superseded create can already exist on the server. Replay it to
// recover its identity before sending the newer edit or discard.
// Older hosts omit this flag: conservatively replay rather than loop
// forever asking the engine to discard a write it must retain.
if (claimed.superseded && claimed.requiresConfirmation === false) {
+ attemptInFlight = false;
const discarded = await host.deferOptimisticWrite(
claimed.transactionId,
{ owner: queueOwner, generation: claimed.leaseGeneration },
@@ -867,6 +981,7 @@ export function normalizedCacheExchange(
}
attemptInFlight = true;
const attempt: QueueAttemptContext = {
+ mutation: claimed,
transactionId: claimed.transactionId,
leaseOwner: queueOwner,
leaseGeneration: claimed.leaseGeneration,
@@ -944,6 +1059,7 @@ export function normalizedCacheExchange(
drainRunning = true;
drainRequested = false;
try {
+ if (options.prepareMutationQueue) await prepareQueueRecovery();
const now = Date.now();
// A wakeup probes immediately, but must retain a future retry
// deadline if the durable head is not eligible yet. Consume expired
@@ -983,6 +1099,40 @@ export function normalizedCacheExchange(
}
}
+ async function prepareQueueRecovery(): Promise<void> {
+ try {
+ queuePreparation ??= boundedMutationLifecycle(() =>
+ options.prepareMutationQueue!()
+ );
+ await queuePreparation;
+ } catch (error) {
+ queuePreparation = undefined;
+ console.warn(
+ '[graphql-cache] Unable to prepare mutation recovery',
+ error
+ );
+ }
+ }
+
+ async function recordAttemptResult(
+ attempt: QueueAttemptContext,
+ result: OperationResult,
+ retry: boolean
+ ): Promise<void> {
+ if (!attempt.mutation || !options.onMutationAttemptResult) return;
+ try {
+ await boundedMutationLifecycle(() =>
+ options.onMutationAttemptResult!(attempt.mutation!, result, retry)
+ );
+ } catch (error) {
+ try {
+ options.onCacheError?.(error, result.operation);
+ } catch {
+ /* Diagnostics cannot retain a failed queue head. */
+ }
+ }
+ }
+
function revalidateAfterSettlement(
revalidations: QueryRevalidationWire[],
mutation?: Operation
@@ -1131,6 +1281,7 @@ export function normalizedCacheExchange(
linkPatches: optimistic.linkPatches,
revalidations: optimistic.revalidations,
identityBindings: optimistic.identityBindings,
+ clientMetadata: optimistic.clientMetadata,
};
const now = Date.now();
const claim = {
@@ -1529,6 +1680,7 @@ export function normalizedCacheExchange(
}),
};
}
+ await recordAttemptResult(attempt, result, retry);
if (retry) {
retryAt = Date.now() + retryDelayMs(attempt.attemptCount);
const deferred = await host.deferOptimisticWrite(
@@ -1566,6 +1718,7 @@ export function normalizedCacheExchange(
}
}
} else {
+ await recordAttemptResult(attempt, result, false);
const committed = await host.commitOptimisticWrite(
attempt.transactionId,
claim,
diff --git a/apps/web/src/lib/graphql-cache/exchange/optimistic.ts b/apps/web/src/lib/graphql-cache/exchange/optimistic.ts
index 474b500ab9..967026856a 100644
--- a/apps/web/src/lib/graphql-cache/exchange/optimistic.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/optimistic.ts
@@ -116,6 +116,8 @@ export type QueryRevalidation = {
export type OptimisticMutationOptions = {
/** Required RFC UUID; reuse only when the newer intent safely replaces the older one. */
uuid: string;
+ /** Opaque durable client correlation; never included in GraphQL variables. */
+ clientMetadata?: Record<string, unknown>;
identityBindings?: readonly IdentityBindingWire[];
/** Runs after durable layer installation, independently of HTTP settlement. */
onEnqueued?: () => void;
@@ -134,6 +136,8 @@ export type OptimisticResponse<T> = T extends readonly (infer Item)[]
export type OptimisticMutationContext<TData = unknown> = {
uuid: string;
optimisticResponse: TData;
+ /** Opaque durable client correlation; never included in GraphQL variables. */
+ clientMetadata?: Record<string, unknown>;
identityBindings?: IdentityBindingWire[];
linkPatches: OptimisticLinkPatchWire[];
revalidations: QueryRevalidationWire[];
@@ -470,6 +474,7 @@ export function executeOptimisticMutation<
}
const context: OptimisticMutationContext<OptimisticResponse<TData>> = {
uuid: options.uuid,
+ clientMetadata: options.clientMetadata,
optimisticResponse: optimisticData,
identityBindings: options.identityBindings
? [...options.identityBindings]
@@ -516,6 +521,7 @@ export function optimisticContextOf(
}
return {
uuid: context.uuid,
+ clientMetadata: context.clientMetadata,
optimisticResponse: context.optimisticResponse,
identityBindings: context.identityBindings,
linkPatches: Array.isArray(context.linkPatches)
diff --git a/apps/web/src/lib/graphql-cache/host/retirable-host.ts b/apps/web/src/lib/graphql-cache/host/retirable-host.ts
index 7b7ea957fb..ee01320254 100644
--- a/apps/web/src/lib/graphql-cache/host/retirable-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/retirable-host.ts
@@ -28,6 +28,9 @@ export function createRetirableCacheHost(inner: CacheHost): CacheHost {
current.enqueueOptimisticMutation(args, claim),
inspectQueryVariants: (args) => current.inspectQueryVariants(args),
inspectQuery: (args) => current.inspectQuery(args),
+ inspectMutations: () =>
+ current.inspectMutations?.() ??
+ Promise.reject(new Error('Queue inspection is unavailable')),
claimNextMutation: (owner, nowMs, leaseExpiresAtMs) =>
current.claimNextMutation(owner, nowMs, leaseExpiresAtMs),
deferOptimisticWrite: (
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index bc7c238c44..06f629f82d 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -15,7 +15,10 @@ import {
type EntityFilterCacheResult,
INITIAL_CACHE_REVISION,
} from '../protocol';
-import { createTauriCacheHost } from './tauri-host';
+import {
+ createTauriCacheHost,
+ NativeCacheUpgradeRequiredError,
+} from './tauri-host';
type EventCallback = (event: { payload: Record<string, unknown> }) => void;
@@ -60,6 +63,7 @@ describe('createTauriCacheHost', () => {
await expect(host.currentStorageGeneration()).resolves.toBe(generation);
expect(invokeMock.mock.calls.map(([command]) => command)).toEqual([
'graphql_cache_init',
+ 'graphql_cache_inspect_mutations',
'graphql_cache_current_storage_generation',
]);
host.dispose();
@@ -135,6 +139,42 @@ describe('createTauriCacheHost', () => {
host.dispose();
});
+ it('preserves the old queue and refuses writes when an OTA outpaces the native runtime', async () => {
+ const onInitializationError = vi.fn();
+ invokeMock.mockImplementation(async (command: string) => {
+ if (command === 'graphql_cache_inspect_mutations')
+ throw 'Command graphql_cache_inspect_mutations not found';
+ return null;
+ });
+ const host = createTauriCacheHost({
+ scope: 'old-native',
+ onInitializationError,
+ });
+ await expect(
+ host.claimNextMutation('runner', 10, 100)
+ ).rejects.toBeInstanceOf(NativeCacheUpgradeRequiredError);
+ await expect(
+ host.enqueueOptimisticMutation(
+ {
+ uuid: '00000000-0000-4000-8000-000000000001',
+ query: 'mutation Save { save { id } }',
+ data: {},
+ },
+ { owner: 'runner', nowMs: 10, leaseExpiresAtMs: 100 }
+ )
+ ).rejects.toBeInstanceOf(NativeCacheUpgradeRequiredError);
+ expect(onInitializationError).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: expect.stringContaining('Update Macro'),
+ })
+ );
+ expect(invokeMock.mock.calls.map(([command]) => command)).toEqual([
+ 'graphql_cache_init',
+ 'graphql_cache_inspect_mutations',
+ ]);
+ host.dispose();
+ });
+
it('projects selected records by explicit key', async () => {
const records = [
{
@@ -856,7 +896,8 @@ describe('createTauriCacheHost', () => {
requestTimeoutMs: 50,
});
invokeMock.mockImplementation((command: string) =>
- command === 'graphql_cache_init'
+ command === 'graphql_cache_init' ||
+ command === 'graphql_cache_inspect_mutations'
? Promise.resolve(null)
: new Promise(() => {})
);
@@ -876,7 +917,8 @@ describe('createTauriCacheHost', () => {
vi.useFakeTimers();
try {
invokeMock.mockImplementation((command: string) =>
- command === 'graphql_cache_init'
+ command === 'graphql_cache_init' ||
+ command === 'graphql_cache_inspect_mutations'
? Promise.resolve(null)
: new Promise(() => {})
);
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
index 9941b529cf..e5f9dfd86d 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -1,3 +1,4 @@
+import type { MutationInspection } from '../protocol';
/**
* Tauri CacheHost: talks to the native cache engine living in the Tauri
* host process (graphql_cache_plugin) over invoke commands. The host
@@ -89,6 +90,17 @@ export interface TauriHostOptions {
const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
const ENTITY_FILTER_COMMAND = 'graphql_cache_entity_filter';
+const INSPECT_MUTATIONS_COMMAND = 'graphql_cache_inspect_mutations';
+
+/** An OTA bundle cannot safely replay drafts using an older native queue API. */
+export class NativeCacheUpgradeRequiredError extends Error {
+ constructor() {
+ super(
+ 'Update Macro to sync drafts saved on this device. Your queued drafts are preserved until the app is updated.'
+ );
+ this.name = 'NativeCacheUpgradeRequiredError';
+ }
+}
export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
const clientId = crypto.randomUUID();
@@ -220,10 +232,25 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
unlisten?.();
}
- const ready = request<void>('graphql_cache_init', {
- scope: options.scope,
- hotCapacity: options.hotCapacity,
- });
+ const ready = (async () => {
+ await request<void>('graphql_cache_init', {
+ scope: options.scope,
+ hotCapacity: options.hotCapacity,
+ });
+ // Probe before any enqueue/claim. Older binaries silently ignore new
+ // metadata arguments, so waiting until a draft fails would lose correlation.
+ try {
+ await request<MutationInspection[]>(INSPECT_MUTATIONS_COMMAND, {});
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ error.message === `Command ${INSPECT_MUTATIONS_COMMAND} not found`
+ ) {
+ throw new NativeCacheUpgradeRequiredError();
+ }
+ throw error;
+ }
+ })();
void (async () => {
try {
await ready;
@@ -379,6 +406,7 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
linkPatches: args.linkPatches,
revalidations: args.revalidations,
identityBindings: args.identityBindings,
+ clientMetadata: args.clientMetadata,
createdAtMs: claim.nowMs,
owner: claim.owner,
nowMs: claim.nowMs,
@@ -417,6 +445,10 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
);
},
+ async inspectMutations() {
+ await ready;
+ return await request<MutationInspection[]>(INSPECT_MUTATIONS_COMMAND, {});
+ },
async claimNextMutation(
owner: string,
nowMs: number,
diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.ts
index 08545b0799..0e0d725d3d 100644
--- a/apps/web/src/lib/graphql-cache/host/types.ts
+++ b/apps/web/src/lib/graphql-cache/host/types.ts
@@ -1,4 +1,4 @@
-import type { IdentityBindingWire } from '../protocol';
+import type { IdentityBindingWire, MutationInspection } from '../protocol';
/**
* Transport-agnostic cache host interface consumed by the urql exchange and
* imperative writers (websocket handlers). Implementations:
@@ -74,6 +74,8 @@ export interface CacheWriteArgs extends Omit<CacheReadArgs, 'priority'> {
export interface EnqueueOptimisticMutationArgs extends CacheWriteArgs {
/** Caller-supplied RFC UUID used for explicit safe coalescing. */
uuid: string;
+ /** Opaque durable client correlation; never included in GraphQL variables. */
+ clientMetadata?: Record<string, unknown>;
identityBindings?: IdentityBindingWire[];
linkPatches?: OptimisticLinkPatchWire[];
/** Revalidations for relevant cached fields that could not be patched. */
@@ -142,6 +144,8 @@ export interface CacheHost {
): Promise<CachedQueryVariantWire[]>;
/** Enumerates and materializes cached query field variants. */
inspectQuery(args: InspectQueryArgs): Promise<CachedQueryInstanceWire[]>;
+ /** Read-only queue snapshots; their lease values do not authorize settlement. */
+ inspectMutations?(): Promise<MutationInspection[]>;
/** Claims the oldest runnable mutation; later entries are never skipped. */
claimNextMutation(
owner: string,
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
index 211e967f72..ee262bff4d 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
@@ -67,6 +67,7 @@ function responseFor(request: CacheRequest): unknown {
transactionId: '1',
initialClaim: { kind: 'not-runnable' },
};
+ case 'inspect-mutations':
case 'inspect-query':
case 'inspect-query-variants':
return [];
@@ -784,28 +785,34 @@ describe('createWorkerCacheHost', () => {
expect(vi.getTimerCount()).toBe(0);
});
- it('times out a hung current-revision request', async () => {
- vi.useFakeTimers();
- configureAdapter = (fake) => fake.ignoredKinds.add('current-revision');
- const host = createWorkerCacheHost({
- scope: 'scope-1',
- requestTimeoutMs: 10,
- });
+ it.each(['current-revision', 'inspect-mutations'] as const)(
+ 'times out a hung %s request',
+ async (kind) => {
+ vi.useFakeTimers();
+ configureAdapter = (fake) => fake.ignoredKinds.add(kind);
+ const host = createWorkerCacheHost({
+ scope: 'scope-1',
+ requestTimeoutMs: 10,
+ });
- const revision = host.currentRevision();
- const revisionRejected = expect(revision).rejects.toThrow(
- 'cache worker timeout: current-revision'
- );
+ const revision =
+ kind === 'inspect-mutations'
+ ? host.inspectMutations!()
+ : host.currentRevision();
+ const revisionRejected = expect(revision).rejects.toThrow(
+ `cache worker timeout: ${kind}`
+ );
- await vi.advanceTimersByTimeAsync(11);
- await revisionRejected;
- expect(requireAdapter().requests.map(({ kind }) => kind)).toEqual([
- 'init',
- 'current-revision',
- ]);
- host.dispose();
- expect(vi.getTimerCount()).toBe(0);
- });
+ await vi.advanceTimersByTimeAsync(11);
+ await revisionRejected;
+ expect(requireAdapter().requests.map(({ kind }) => kind)).toEqual([
+ 'init',
+ kind,
+ ]);
+ host.dispose();
+ expect(vi.getTimerCount()).toBe(0);
+ }
+ );
it('recovers typed initial epoch loss with fresh init handshakes only', async () => {
configureAdapter = (fake) => fake.ignoredKinds.add('init');
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.ts
index 0d358ae2fa..9d923b7992 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts
@@ -1,3 +1,4 @@
+import type { MutationInspection } from '../protocol';
/**
* Browser CacheHost: routes cache RPC through the SharedWorker coordinator to
* the currently elected dedicated cache engine. Unsupported browsers receive
@@ -950,6 +951,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
msg.kind === 'read-records-by-keys' ||
msg.kind === 'search' ||
msg.kind === 'entity-filter' ||
+ msg.kind === 'inspect-mutations' ||
msg.kind === 'inspect-query' ||
msg.kind === 'inspect-query-variants'
? requestTimeoutMs
@@ -1267,6 +1269,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
linkPatches: args.linkPatches,
revalidations: args.revalidations,
identityBindings: args.identityBindings,
+ clientMetadata: args.clientMetadata,
createdAtMs: claim.nowMs,
owner: claim.owner,
nowMs: claim.nowMs,
@@ -1297,6 +1300,11 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
})) as CachedQueryInstanceWire[];
},
+ async inspectMutations() {
+ return (await initializedRequest({
+ kind: 'inspect-mutations',
+ })) as MutationInspection[];
+ },
async claimNextMutation(
owner: string,
nowMs: number,
diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.ts
index deb4eb9de2..cf5d9771e8 100644
--- a/apps/web/src/lib/graphql-cache/protocol.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.ts
@@ -403,8 +403,21 @@ export type MutationUpsertKind =
| { kind: 'replaced-pending'; removedTransactionId: string }
| { kind: 'appended-after-active'; activeTransactionId: string };
+/** Read-only request snapshot; never contains a settlement lease token. */
+export type MutationInspection = Pick<
+ ClaimedMutation,
+ | 'transactionId'
+ | 'uuid'
+ | 'superseded'
+ | 'query'
+ | 'operationName'
+ | 'variables'
+ | 'clientMetadata'
+> & { optimisticData: unknown };
+
/** Claimed strict queue head, ready to be forwarded through urql. */
export type ClaimedMutation = {
+ clientMetadata?: Record<string, unknown> | null;
transactionId: string;
uuid: string;
superseded: boolean;
@@ -488,6 +501,7 @@ export type CacheRequest = { id: number } & (
| { kind: 'init'; scope: string; hotCapacity?: number }
| { kind: 'current-revision' }
| { kind: 'current-storage-generation' }
+ | { kind: 'inspect-mutations' }
| {
kind: 'read';
opId?: string;
@@ -537,6 +551,7 @@ export type CacheRequest = { id: number } & (
data: unknown;
linkPatches?: OptimisticLinkPatchWire[];
revalidations?: QueryRevalidationWire[];
+ clientMetadata?: Record<string, unknown>;
identityBindings?: IdentityBindingWire[];
createdAtMs: number;
owner: string;
diff --git a/apps/web/src/lib/graphql-cache/telemetry.ts b/apps/web/src/lib/graphql-cache/telemetry.ts
index 36c26e6693..bf12219d6a 100644
--- a/apps/web/src/lib/graphql-cache/telemetry.ts
+++ b/apps/web/src/lib/graphql-cache/telemetry.ts
@@ -526,6 +526,7 @@ export function operationCategoryForRequest(
'teardown',
'clear',
'current-storage-generation',
+ 'inspect-mutations',
() => 'lifecycle' as const
)
.exhaustive();
diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts
index 6d98860bbe..fdd6d87e14 100644
--- a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts
+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts
@@ -483,6 +483,7 @@ export function isCacheRequest(value: unknown): value is CacheRequest {
);
case 'current-revision':
case 'current-storage-generation':
+ case 'inspect-mutations':
return hasOnlyKeys(value, ['id', 'kind']);
case 'read':
return (
@@ -555,6 +556,7 @@ export function isCacheRequest(value: unknown): value is CacheRequest {
'linkPatches',
'revalidations',
'identityBindings',
+ 'clientMetadata',
'createdAtMs',
'owner',
'nowMs',
@@ -569,6 +571,7 @@ export function isCacheRequest(value: unknown): value is CacheRequest {
(value.linkPatches === undefined || Array.isArray(value.linkPatches)) &&
(value.revalidations === undefined ||
Array.isArray(value.revalidations)) &&
+ isOptionalRecord(value.clientMetadata) &&
(value.identityBindings === undefined ||
(Array.isArray(value.identityBindings) &&
value.identityBindings.length <= 32 &&
diff --git a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
index 476470bf80..c3bf8f8a73 100644
--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
@@ -1,4 +1,4 @@
-import type { IdentityBindingWire } from '../protocol';
+import type { IdentityBindingWire, MutationInspection } from '../protocol';
/**
* Typed surface of the generated wasm package (`cache-wasm`), loaded
* dynamically so the repo type-checks without the generated artifacts.
@@ -116,6 +116,7 @@ export interface CacheEngine {
data: unknown,
identity: string | undefined
): Promise<CacheEngineHydrationResult>;
+ inspectMutations(): Promise<MutationInspection[]>;
enqueueOptimisticMutation(
originOpId: string | undefined,
uuid: string,
@@ -129,7 +130,8 @@ export interface CacheEngine {
createdAtMs: number,
leaseOwner: string,
nowMs: number,
- leaseExpiresAtMs: number
+ leaseExpiresAtMs: number,
+ clientMetadata?: Record<string, unknown>
): Promise<EnqueueOptimisticMutationResult>;
inspectQueryVariants(
query: string,
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
index e7e7aff074..17084472a1 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
@@ -566,7 +566,8 @@ export class CacheWorkerCore {
request.createdAtMs,
request.owner,
request.nowMs,
- request.leaseExpiresAtMs
+ request.leaseExpiresAtMs,
+ request.clientMetadata
);
result.revision = parseCacheRevision(result.revision);
this.fanOut(result, true);
@@ -598,6 +599,10 @@ export class CacheWorkerCore {
request.variableFilters ?? []
);
})
+ .with(
+ { kind: 'inspect-mutations' },
+ async () => await this.requireEngine().inspectMutations()
+ )
.with({ kind: 'claim-next-mutation' }, async (request) => {
const engine = this.requireEngine();
return await engine.claimNextMutation(
diff --git a/apps/web/src/lib/queries/email/attachment.test.tsx b/apps/web/src/lib/queries/email/attachment.test.tsx
index 043d30bfe6..23bec5d9b2 100644
--- a/apps/web/src/lib/queries/email/attachment.test.tsx
+++ b/apps/web/src/lib/queries/email/attachment.test.tsx
@@ -84,6 +84,44 @@ describe('useUploadDraftAttachmentsMutation', () => {
expect(toastFailureMock).not.toHaveBeenCalled();
});
+ it('cleans up a created record when its durable receipt cannot be written', async () => {
+ const attachment = file();
+ const clear = vi.fn();
+ const mutation = mountEmailMutation(useUploadDraftAttachmentsMutation);
+ await expect(
+ mutation.mutateAsync({
+ draftID: 'draft-1',
+ attachments: [attachment],
+ onAttachmentAdded: async () => {
+ throw new Error('Disk full');
+ },
+ onAttachmentUploadFailed: clear,
+ })
+ ).rejects.toThrow('Upload failed');
+ expect(uploadToPresignedUrlMock).not.toHaveBeenCalled();
+ expect(removeDraftAttachmentMock).toHaveBeenCalledWith(
+ { draftID: 'draft-1', attachmentID: 'att-1' },
+ undefined
+ );
+ expect(clear).toHaveBeenCalledWith(attachment);
+ });
+
+ it('retains a successful upload when recording its receipt fails', async () => {
+ uploadToPresignedUrlMock.mockResolvedValue(ok(undefined));
+ const mutation = mountEmailMutation(useUploadDraftAttachmentsMutation);
+ await expect(
+ mutation.mutateAsync({
+ draftID: 'draft-1',
+ attachments: [file()],
+ onAttachmentUploaded: async () => {
+ throw new Error('Disk full');
+ },
+ })
+ ).rejects.toThrow('Disk full');
+ expect(uploadToPresignedUrlMock).toHaveBeenCalledOnce();
+ expect(removeDraftAttachmentMock).not.toHaveBeenCalled();
+ });
+
it('keeps the id when the record removal fails after a failed upload', async () => {
uploadToPresignedUrlMock.mockResolvedValue(
err([{ code: 'SERVER_ERROR', message: 'upload failed' }])
diff --git a/apps/web/src/lib/queries/email/attachment.ts b/apps/web/src/lib/queries/email/attachment.ts
index ed18c9f437..c5a1c5ef86 100644
--- a/apps/web/src/lib/queries/email/attachment.ts
+++ b/apps/web/src/lib/queries/email/attachment.ts
@@ -21,7 +21,14 @@ type UploadDraftAttachmentsParams = {
* the content upload can take a long time, and a debounced draft save that
* still sees the file without an id would add it to the draft a second time.
*/
- onAttachmentAdded?: (file: File, attachmentID: string) => void;
+ onAttachmentAdded?: (
+ file: File,
+ attachmentID: string
+ ) => void | Promise<void>;
+ onAttachmentUploaded?: (
+ file: File,
+ attachmentID: string
+ ) => void | Promise<void>;
/**
* Called when the content upload fails, once its attachment record has been
* confirmed removed from the draft, so the file becomes eligible for a
@@ -64,8 +71,6 @@ export const useUploadDraftAttachmentsMutation = (
)
);
- params.onAttachmentAdded?.(attachment, result.attachment_id);
-
// Any content-upload failure must become an UploadDraftAttachmentError
// so onError removes the record and clears the id -- a plain throw from
// the fetch (network drop, abort) would otherwise leave the id in
@@ -75,6 +80,7 @@ export const useUploadDraftAttachmentsMutation = (
file: attachment,
};
try {
+ await params.onAttachmentAdded?.(attachment, result.attachment_id);
if (source.kind === 'staged') {
await uploadNativeStagedFileToPresignedUrl(
{ ...source.staged, mimeType: result.content_type },
@@ -108,6 +114,8 @@ export const useUploadDraftAttachmentsMutation = (
context
);
}
+ // Upload succeeded. A failed local receipt must not delete server data.
+ await params.onAttachmentUploaded?.(attachment, result.attachment_id);
}
},
...withCallbacks<void, Error, UploadDraftAttachmentsParams>(
diff --git a/apps/web/src/lib/queries/email/draft-queue.test.ts b/apps/web/src/lib/queries/email/draft-queue.test.ts
index 68050215a9..d2ae9c87ca 100644
--- a/apps/web/src/lib/queries/email/draft-queue.test.ts
+++ b/apps/web/src/lib/queries/email/draft-queue.test.ts
@@ -1,3 +1,4 @@
+import type { LocalDraft } from '@app/features/email-compose/core/local-draft';
import { optimisticContextOf } from '@graphql-cache/exchange/optimistic';
import type { MutationSettlement } from '@graphql-cache/protocol';
import type {
@@ -7,12 +8,20 @@ import type {
import { type Client, createClient, type Operation } from '@urql/core';
import { beforeEach, expect, it, vi } from 'vitest';
import { map, pipe } from 'wonka';
+import {
+ localDraftMessage,
+ readLocalDraft,
+ restoreLocalAttachments,
+} from './local-drafts';
const mocks = vi.hoisted(() => ({
readRecordsByKeys: vi.fn(),
onCacheChanged: vi.fn(),
onMutationSettled: vi.fn(),
client: undefined as Client | undefined,
+ queueBlocked: false,
+ cacheEnabled: true,
+ assertQueueAvailable: vi.fn(),
}));
vi.mock('@core/component/Toast/Toast', () => ({ toast: { failure: vi.fn() } }));
vi.mock('@core/constant/featureFlags', () => ({
@@ -23,13 +32,15 @@ vi.mock('@macro-inc/observability', () => ({
Telemetry: { error: vi.fn() },
}));
vi.mock('@service-storage/graphql-soup', () => ({
+ assertEmailDraftQueueAvailable: mocks.assertQueueAvailable,
+ graphqlDraftQueueBlocked: () => mocks.queueBlocked,
getGraphqlCacheHost: () => ({
readRecordsByKeys: mocks.readRecordsByKeys,
onCacheChanged: mocks.onCacheChanged,
onMutationSettled: mocks.onMutationSettled,
}),
getGraphqlSoupClient: () => mocks.client,
- graphqlCacheEnabled: () => true,
+ graphqlCacheEnabled: () => mocks.cacheEnabled,
}));
vi.mock('../client', () => ({ queryClient: { invalidateQueries: vi.fn() } }));
vi.mock('../soup/cache', () => ({
@@ -42,6 +53,7 @@ vi.mock('./thread', () => ({ fetchAndCacheThread: vi.fn() }));
import {
deleteEmailDraftQueued,
+ draftQueueActive,
readEmailDraft,
saveEmailDraftQueued,
watchEmailDrafts,
@@ -66,6 +78,8 @@ const args: GraphqlSaveEmailDraftArgs = {
beforeEach(() => {
vi.resetAllMocks();
+ mocks.queueBlocked = false;
+ mocks.cacheEnabled = true;
});
async function setup() {
@@ -138,6 +152,32 @@ async function setup() {
return { operations, local, draftResult, threadResult };
}
+it.each(['save', 'delete'] as const)(
+ 'blocks an uncached fallback %s before changing local intent or sending a request',
+ async (operation) => {
+ const { operations } = await setup();
+ mocks.assertQueueAvailable.mockImplementation(() => {
+ throw new Error('Queued drafts are preserved');
+ });
+ await expect(
+ operation === 'save'
+ ? saveEmailDraftQueued({ args })
+ : deleteEmailDraftQueued({ draftId: handle, threadId: 'local-thread' })
+ ).rejects.toThrow('Queued drafts are preserved');
+ expect(operations).toEqual([]);
+ expect(readLocalDraft).not.toHaveBeenCalled();
+ }
+);
+
+it('keeps local persistence enabled for GraphQL drafts while the queue is unavailable', () => {
+ mocks.cacheEnabled = false;
+ mocks.queueBlocked = true;
+ expect(draftQueueActive('graphql')).toBe(true);
+ expect(draftQueueActive('rest')).toBe(false);
+ mocks.queueBlocked = false;
+ expect(draftQueueActive('graphql')).toBe(false);
+});
+
it('uses resolved IDs for an old-handle save without duplicating the cached draft', async () => {
const { operations } = await setup();
expect(await saveEmailDraftQueued({ args })).toEqual({ kind: 'queued' });
@@ -288,3 +328,73 @@ it('retains a sent record mutation handle without returning editable content', a
mutationUuid: handle,
});
});
+
+vi.mock('./local-drafts', () => ({
+ readLocalDraft: vi.fn(async () => undefined),
+ localDraftMessage: vi.fn(),
+ restoreLocalAttachments: vi.fn(),
+ beginDraftAttempt: vi.fn(),
+ markDraftAttemptQueued: vi.fn(),
+ draftSyncPaused: vi.fn(),
+ localDraftStore: { subscribe: vi.fn(() => () => {}) },
+}));
+
+const workingCopy = (status: LocalDraft['status']): LocalDraft => ({
+ key: handle,
+ accountId: 'owner',
+ generation: 'generation',
+ revision: 2,
+ acknowledgedRevision: 2,
+ draftId: handle,
+ serverDraftId: serverId,
+ threadId: 'local-thread',
+ serverThreadId: 'server-thread',
+ content: { subject: 'Stale local subject' },
+ attachments: [],
+ status,
+ updatedAt: 1,
+});
+
+it('reads authoritative content once the local working copy is synced', async () => {
+ const { draftResult } = await setup();
+ const cached = draftResult();
+ cached.records[0].record.subject = 'New edit from another device';
+ vi.mocked(readLocalDraft).mockResolvedValue(workingCopy('synced'));
+ mocks.readRecordsByKeys.mockResolvedValue(cached);
+ const result = await readEmailDraft(serverId);
+ expect(result?.draft?.subject).toBe('New edit from another device');
+ expect(restoreLocalAttachments).not.toHaveBeenCalled();
+});
+
+it('keeps a confirmed server identity while attachment receipts are pending', async () => {
+ await setup();
+ const local = workingCopy('dirty');
+ local.attachments = [
+ {
+ type: 'local',
+ id: 'file',
+ name: 'a.txt',
+ mimeType: 'text/plain',
+ size: 1,
+ lastModified: 0,
+ uploaded: false,
+ },
+ ];
+ vi.mocked(readLocalDraft).mockResolvedValue(local);
+ mocks.readRecordsByKeys.mockResolvedValue({ revision: '1', records: [] });
+ expect(await readEmailDraft(serverId)).toMatchObject({
+ persistence: 'committed',
+ local,
+ });
+ expect(localDraftMessage).toHaveBeenCalledWith(local);
+});
+
+it('does not reopen unsynced content over an authoritative sent record', async () => {
+ const { draftResult } = await setup();
+ const cached = draftResult();
+ cached.records[0].record.isDraft = false;
+ vi.mocked(readLocalDraft).mockResolvedValue(workingCopy('failed'));
+ mocks.readRecordsByKeys.mockResolvedValue(cached);
+ expect((await readEmailDraft(serverId))?.draft).toBeUndefined();
+ expect(restoreLocalAttachments).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/lib/queries/email/draft-queue.ts b/apps/web/src/lib/queries/email/draft-queue.ts
index c0bb308db2..117f13f759 100644
--- a/apps/web/src/lib/queries/email/draft-queue.ts
+++ b/apps/web/src/lib/queries/email/draft-queue.ts
@@ -13,9 +13,11 @@ import {
EmailThreadMessageFieldsFragmentDoc,
} from '@service-storage/graphql/generated/graphql';
import {
+ assertEmailDraftQueueAvailable,
getGraphqlCacheHost,
getGraphqlSoupClient,
graphqlCacheEnabled,
+ graphqlDraftQueueBlocked,
} from '@service-storage/graphql-soup';
import { queryClient } from '../client';
import {
@@ -33,22 +35,74 @@ import {
} from './graphql/draft';
import { mapGraphqlEmailMessage } from './graphql/mapper';
import { emailKeys } from './keys';
+import {
+ beginDraftAttempt,
+ draftSyncPaused,
+ localDraftMessage,
+ localDraftStore,
+ markDraftAttemptQueued,
+ readLocalDraft,
+ restoreLocalAttachments,
+} from './local-drafts';
import { fetchAndCacheThread, type ThreadQueryTransport } from './thread';
+export { assertEmailDraftQueueAvailable };
+
/** Read content and persistence state together, including resolved local handles. */
-export async function readEmailDraft(draftId: string) {
+export async function readEmailDraft(
+ draftId: string,
+ options: { attachments?: boolean } = {}
+) {
+ const local = await readLocalDraft(draftId);
const host = getGraphqlCacheHost();
- if (!host) return;
- const result = await readRecordsByKeys(
- host,
- selectRecords(EmailThreadMessageFieldsFragmentDoc),
- [`GraphqlSoupEmailMessage:${draftId}`]
- );
- const selected = result.records[0];
+ const result = host
+ ? await readRecordsByKeys(
+ host,
+ selectRecords(EmailThreadMessageFieldsFragmentDoc),
+ [`GraphqlSoupEmailMessage:${local?.serverDraftId ?? draftId}`]
+ )
+ : undefined;
+ const selected = result?.records[0];
+ // A confirmed sent record always wins. A fully synced working copy must
+ // also yield to newer server content, attachments, and scheduling state.
+ if (
+ selected &&
+ (!selected.record.isDraft || !local || local.status === 'synced')
+ ) {
+ return {
+ draft: selected.record.isDraft
+ ? mapGraphqlEmailMessage(selected.record)
+ : undefined,
+ persistence: selected.identity?.pending
+ ? ('queued' as const)
+ : ('committed' as const),
+ mutationUuid: local?.key ?? selected.identity?.mutationUuid ?? undefined,
+ local: selected.record.isDraft ? local : undefined,
+ };
+ }
+ const admittedDelete =
+ local?.status === 'deleting' &&
+ !!local.queuedAttemptId &&
+ local.queuedAttemptId === local.latestAttemptId;
+ if (local && (!admittedDelete || options.attachments === false)) {
+ return {
+ draft: localDraftMessage(local),
+ // Upload receipts are separate from the body save. Pending files must
+ // not demote an acknowledged server identity to a client handle.
+ persistence:
+ local.serverDraftId && local.acknowledgedRevision >= local.revision
+ ? ('committed' as const)
+ : ('queued' as const),
+ mutationUuid: local.key,
+ local,
+ attachments:
+ options.attachments === false
+ ? undefined
+ : await restoreLocalAttachments(local),
+ };
+ }
if (!selected) return;
return {
- // Rollback can expose a sent base before its settlement arrives. Keep
- // its mutation handle for correlation, without exposing editable content.
draft: selected.record.isDraft
? mapGraphqlEmailMessage(selected.record)
: undefined,
@@ -72,7 +126,15 @@ export function watchEmailDrafts(
getGraphqlSoupClient();
const host = getGraphqlCacheHost();
const cache = host?.onCacheChanged(() => changed());
+ const local = localDraftStore.subscribe(() => changed());
const settlement = host?.onMutationSettled((result) => {
+ if (
+ result.status === 'permanently-failed' &&
+ result.errorCode === 'LOCAL_SUPERSEDED'
+ ) {
+ changed();
+ return;
+ }
const code =
result.status === 'permanently-failed'
? draftFailureCode(result.errorCode)
@@ -84,6 +146,7 @@ export function watchEmailDrafts(
});
});
return () => {
+ local();
cache?.();
settlement?.();
};
@@ -104,7 +167,7 @@ export function watchEmailDrafts(
export function draftQueueActive(
threadTransport?: ThreadQueryTransport
): boolean {
- if (!graphqlCacheEnabled()) return false;
+ if (!graphqlCacheEnabled() && !graphqlDraftQueueBlocked()) return false;
return threadTransport
? threadTransport === 'graphql'
: isFeatureEnabled(enableGraphqlSoup);
@@ -204,13 +267,27 @@ export async function saveEmailDraftQueued(input: {
completingThread?: boolean;
previousThreadId?: string;
}): Promise<QueuedDraftSave> {
+ getGraphqlSoupClient();
+ assertEmailDraftQueueAvailable();
+ const local = await readLocalDraft(String(input.args.draftId));
+ if (local && draftSyncPaused(local))
+ return { kind: 'rejected', code: draftFailureCode(local.errorCode) };
+ const attempt = local
+ ? await beginDraftAttempt(
+ { ...local, revision: input.args.localRevision ?? local.revision },
+ 'save'
+ )
+ : undefined;
const cached = await readCachedDraftAndThread(
String(input.args.draftId),
input.args.threadDbId
);
- const outcome = await executeGraphqlSaveEmailDraft(getGraphqlSoupClient(), {
+ const client = getGraphqlSoupClient();
+ assertEmailDraftQueueAvailable();
+ const outcome = await executeGraphqlSaveEmailDraft(client, {
...input.args,
...cached,
+ ...(local ? { draftId: local.draftId, clientMetadata: attempt } : {}),
mutationUuid:
cached.mutationUuid ??
input.args.mutationUuid ??
@@ -226,7 +303,16 @@ export async function saveEmailDraftQueued(input: {
),
};
}
- if (outcome.kind === 'queued') return { kind: 'queued' };
+ if (outcome.kind === 'queued') {
+ if (attempt) {
+ try {
+ await markDraftAttemptQueued(attempt);
+ } catch (error) {
+ reportError(error);
+ }
+ }
+ return { kind: 'queued' };
+ }
try {
markThreadDraftSaved(outcome.threadId);
if (input.previousThreadId && input.previousThreadId !== outcome.threadId) {
@@ -261,11 +347,18 @@ export async function deleteEmailDraftQueued(input: {
threadId: string;
completingThread?: boolean;
}): Promise<QueuedDraftDelete> {
+ getGraphqlSoupClient();
+ assertEmailDraftQueueAvailable();
+ const local = await readLocalDraft(input.draftId);
+ const attempt = local ? await beginDraftAttempt(local, 'delete') : undefined;
const cached = await readCachedDraftAndThread(input.draftId, input.threadId);
- const outcome = await executeGraphqlDeleteEmailDraft(getGraphqlSoupClient(), {
+ const client = getGraphqlSoupClient();
+ assertEmailDraftQueueAvailable();
+ const outcome = await executeGraphqlDeleteEmailDraft(client, {
existingThread: cached.existingThread,
mutationUuid: cached.mutationUuid ?? input.draftId,
- draftId: String(cached.draftId),
+ draftId: local?.draftId ?? String(cached.draftId),
+ clientMetadata: attempt,
threadDbId: cached.threadDbId,
});
if (outcome.kind === 'failed') {
@@ -274,7 +367,16 @@ export async function deleteEmailDraftQueued(input: {
code: rejection(outcome.code, 'Failed to delete draft', input.threadId),
};
}
- if (outcome.kind === 'queued') return { kind: 'queued' };
+ if (outcome.kind === 'queued') {
+ if (attempt) {
+ try {
+ await markDraftAttemptQueued(attempt);
+ } catch (error) {
+ reportError(error);
+ }
+ }
+ return { kind: 'queued' };
+ }
try {
markThreadDraftSaved(input.threadId);
void queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });
diff --git a/apps/web/src/lib/queries/email/graphql/draft.ts b/apps/web/src/lib/queries/email/graphql/draft.ts
index 5d17d3ae58..2b0bd10c31 100644
--- a/apps/web/src/lib/queries/email/graphql/draft.ts
+++ b/apps/web/src/lib/queries/email/graphql/draft.ts
@@ -1,3 +1,4 @@
+import type { DraftAttempt } from '@app/features/email-compose/core/local-draft';
import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';
import {
executeOptimisticMutation,
@@ -71,6 +72,8 @@ export type GraphqlSaveEmailDraftArgs = Omit<
senderIsSignal?: boolean;
/** Original queue coalescing key survives adoption of server IDs. */
mutationUuid?: string;
+ clientMetadata?: DraftAttempt;
+ localRevision?: number;
};
/** Maps a REST-shaped contact to the mutation's input shape. */
@@ -248,6 +251,8 @@ export async function executeGraphqlSaveEmailDraft(
newThreadOwnerId: _newThreadOwnerId,
senderIsSignal: _senderIsSignal,
mutationUuid: _mutationUuid,
+ clientMetadata: _clientMetadata,
+ localRevision: _localRevision,
...input
} = args;
const variables: SaveEmailDraftMutationVariables = { input };
@@ -295,6 +300,7 @@ export async function executeGraphqlSaveEmailDraft(
// draft instead of one per debounce tick. The delete reuses the key —
// a discard supersedes any still-queued save.
uuid: args.mutationUuid ?? String(args.draftId),
+ clientMetadata: args.clientMetadata,
identityBindings: [
{
localKey: `GraphqlSoupEmailMessage:${args.draftId}`,
@@ -369,6 +375,7 @@ export type GraphqlDeleteEmailDraftArgs = {
threadDbId: string;
existingThread?: DraftThread;
mutationUuid?: string;
+ clientMetadata?: DraftAttempt;
};
/**
@@ -425,6 +432,7 @@ export async function executeGraphqlDeleteEmailDraft(
// still-queued save of this draft — the replaced entry never replays,
// and the delete itself is an idempotent no-op if nothing was created.
uuid: args.mutationUuid ?? args.draftId,
+ clientMetadata: args.clientMetadata,
identityBindings: [
{
localKey: `GraphqlSoupEmailMessage:${args.draftId}`,
diff --git a/apps/web/src/lib/queries/email/local-draft-source.test.ts b/apps/web/src/lib/queries/email/local-draft-source.test.ts
new file mode 100644
index 0000000000..95612a133c
--- /dev/null
+++ b/apps/web/src/lib/queries/email/local-draft-source.test.ts
@@ -0,0 +1,159 @@
+import type { LocalDraft } from '@app/features/email-compose/core/local-draft';
+import { createRoot, createSignal } from 'solid-js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const runtime = vi.hoisted(() => ({
+ list: vi.fn<() => Promise<LocalDraft[]>>(),
+ listeners: new Set<() => void>(),
+}));
+vi.mock('./local-drafts', () => ({
+ listLocalDrafts: runtime.list,
+ localDraftStore: {
+ subscribe(listener: () => void) {
+ runtime.listeners.add(listener);
+ return () => runtime.listeners.delete(listener);
+ },
+ },
+}));
+vi.mock('../client', () => ({
+ queryClient: { getQueryCache: () => ({ subscribe: () => () => {} }) },
+}));
+
+import {
+ createLocalDraftSource,
+ localDraftEntities,
+ localDraftMatchesFilters,
+} from './local-draft-source';
+
+const draft = (overrides: Partial<LocalDraft> = {}): LocalDraft => ({
+ key: 'handle',
+ draftId: 'handle',
+ threadId: 'thread',
+ accountId: 'owner',
+ generation: 'generation',
+ revision: 2,
+ acknowledgedRevision: 1,
+ content: { subject: 'Recover me' },
+ attachments: [],
+ status: 'failed',
+ updatedAt: 1,
+ ...overrides,
+});
+
+beforeEach(() => {
+ runtime.list.mockReset();
+ runtime.listeners.clear();
+});
+
+describe('local draft discovery', () => {
+ it('does not touch draft storage in REST mode and ignores a late result after disabling', async () => {
+ let resolve!: (drafts: LocalDraft[]) => void;
+ runtime.list.mockReturnValue(
+ new Promise((done) => {
+ resolve = done;
+ })
+ );
+ const state = createRoot((dispose) => {
+ const [enabled, setEnabled] = createSignal(false);
+ return { source: createLocalDraftSource(enabled), setEnabled, dispose };
+ });
+ try {
+ expect(runtime.list).not.toHaveBeenCalled();
+ state.setEnabled(true);
+ expect(runtime.list).toHaveBeenCalledOnce();
+ state.setEnabled(false);
+ resolve([draft()]);
+ await Promise.resolve();
+ expect(state.source.drafts()).toEqual([]);
+ expect(state.source.ready()).toBe(true);
+ } finally {
+ state.dispose();
+ }
+ expect(runtime.listeners.size).toBe(0);
+ });
+
+ it('refreshes recoverable drafts after a cross-tab invalidation', async () => {
+ runtime.list.mockResolvedValue([]);
+ const state = createRoot((dispose) => ({
+ source: createLocalDraftSource(() => true),
+ dispose,
+ }));
+ try {
+ await Promise.resolve();
+ expect(state.source.drafts()).toEqual([]);
+ runtime.list.mockResolvedValue([draft()]);
+ for (const listener of runtime.listeners) listener();
+ await Promise.resolve();
+ expect(state.source.drafts()[0].content.subject).toBe('Recover me');
+ } finally {
+ state.dispose();
+ }
+ });
+
+ it('emits one canonical conversation row and excludes synced or deleting copies', () => {
+ const rows = localDraftEntities([
+ draft({ serverThreadId: 'canonical' }),
+ draft({ key: 'reply', serverThreadId: 'canonical' }),
+ draft({ key: 'synced', threadId: 'synced', status: 'synced' }),
+ draft({
+ key: 'deleting',
+ threadId: 'deleting',
+ status: 'deleting',
+ latestAttemptId: 'delete',
+ queuedAttemptId: 'delete',
+ }),
+ ]);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ id: 'canonical',
+ isDraft: true,
+ name: 'Recover me',
+ });
+ });
+
+ it('respects selected inboxes, senders, date ranges, and server-only email views', () => {
+ const local = draft({
+ inboxId: 'personal',
+ senderEmail: '[email protected]',
+ updatedAt: Date.parse('2026-10-01'),
+ });
+ expect(
+ localDraftMatchesFilters(local, {
+ emailView: 'drafts',
+ include: { emailLinkId: ['personal'] },
+ exclude: {},
+ })
+ ).toBe(true);
+ expect(
+ localDraftMatchesFilters(local, {
+ include: { emailLinkId: ['work'] },
+ exclude: {},
+ })
+ ).toBe(false);
+ expect(
+ localDraftMatchesFilters(local, {
+ include: {},
+ exclude: { emailSender: ['[email protected]'] },
+ })
+ ).toBe(false);
+ expect(
+ localDraftMatchesFilters(local, {
+ include: { emailUpdatedAt: { lt: '2026-09-01' } },
+ exclude: {},
+ })
+ ).toBe(false);
+ expect(
+ localDraftMatchesFilters(local, {
+ emailView: 'sent',
+ include: {},
+ exclude: {},
+ })
+ ).toBe(false);
+ expect(
+ localDraftMatchesFilters(local, {
+ include: { emailCalendarOnly: true },
+ exclude: {},
+ })
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/lib/queries/email/local-draft-source.ts b/apps/web/src/lib/queries/email/local-draft-source.ts
new file mode 100644
index 0000000000..a39e58650c
--- /dev/null
+++ b/apps/web/src/lib/queries/email/local-draft-source.ts
@@ -0,0 +1,152 @@
+import type { LocalDraft } from '@app/features/email-compose/core/local-draft';
+import type {
+ FieldFilters,
+ QueryState,
+} from '@app/features/next-soup/filters/filter-store/types';
+import type { EmailEntity } from '@entity';
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
+import { authKeys } from '../auth/keys';
+import { queryClient } from '../client';
+import { listLocalDrafts, localDraftStore } from './local-drafts';
+
+/** Account-scoped local data source; notifications are invalidations, never the truth. */
+export function createLocalDraftSource(enabled: Accessor<boolean>) {
+ const [drafts, setDrafts] = createSignal<LocalDraft[]>([]);
+ const [ready, setReady] = createSignal(false);
+ let generation = 0;
+ let disposed = false;
+ const refresh = async () => {
+ const request = ++generation;
+ if (!enabled()) {
+ setDrafts([]);
+ setReady(true);
+ return;
+ }
+ try {
+ const entries = await listLocalDrafts();
+ if (!disposed && request === generation)
+ setDrafts(entries.sort((a, b) => b.updatedAt - a.updatedAt));
+ } catch {
+ if (!disposed && request === generation) setDrafts([]);
+ } finally {
+ if (!disposed && request === generation) setReady(true);
+ }
+ };
+ const unsubscribe = localDraftStore.subscribe(() => {
+ void refresh();
+ });
+ const auth = queryClient.getQueryCache().subscribe((event) => {
+ if (event.query.queryHash === JSON.stringify(authKeys.userInfo.queryKey))
+ void refresh();
+ });
+ onCleanup(() => {
+ disposed = true;
+ unsubscribe();
+ auth();
+ });
+ createEffect(
+ on(enabled, () => {
+ void refresh();
+ })
+ );
+ return { drafts: () => (enabled() ? drafts() : []), ready };
+}
+
+/** One conversation row, even when several local reply drafts share it. */
+export function localDraftEntities(
+ drafts: readonly LocalDraft[]
+): EmailEntity[] {
+ const rows = new Map<string, EmailEntity>();
+ for (const draft of drafts) {
+ if (
+ draft.status === 'synced' ||
+ (draft.status === 'deleting' &&
+ draft.queuedAttemptId &&
+ draft.queuedAttemptId === draft.latestAttemptId)
+ )
+ continue;
+ const id = draft.serverThreadId ?? draft.threadId ?? draft.key;
+ if (rows.has(id)) continue;
+ rows.set(id, {
+ type: 'email',
+ id,
+ name: draft.content.subject || 'Draft email',
+ ownerId: draft.accountId,
+ isRead: true,
+ isDraft: true,
+ isImportant: false,
+ isSignal: true,
+ done: false,
+ linkId: draft.inboxId,
+ senderEmail: draft.senderEmail,
+ participants: (draft.content.to ?? []).map((contact) => ({
+ email: contact.email,
+ name: contact.name ?? undefined,
+ })),
+ createdAt: new Date(draft.updatedAt),
+ updatedAt: new Date(draft.updatedAt),
+ snippet:
+ draft.status === 'failed' ||
+ draft.status === 'unconfirmed' ||
+ draft.status === 'delete-failed'
+ ? 'Saved on this device · Not synced'
+ : 'Saved on this device',
+ });
+ }
+ return [...rows.values()];
+}
+
+/** Server email filters also apply to recovery rows, which never visit that server. */
+export function localDraftMatchesFilters(
+ draft: LocalDraft,
+ query: QueryState
+): boolean {
+ if (query.emailView === 'sent') return false;
+ const matches = (filters: FieldFilters, exclude: boolean) => {
+ const fields: [string[] | undefined, (string | undefined)[]][] = [
+ [filters.emailLinkId, [draft.inboxId]],
+ [filters.threadId, [draft.threadId, draft.serverThreadId]],
+ [filters.emailSender, [draft.senderEmail]],
+ [filters.emailProjectId, []],
+ ];
+ for (const [selected, actual] of fields) {
+ if (!selected?.length) continue;
+ const match = actual.some(
+ (value) => value !== undefined && selected.includes(value)
+ );
+ if (exclude ? match : !match) return false;
+ }
+ const values: [boolean | undefined, boolean][] = [
+ [filters.emailSeen, true],
+ [filters.emailDone, false],
+ [filters.emailImportance, true],
+ [filters.emailCalendarOnly, false],
+ ];
+ for (const [selected, actual] of values) {
+ if (
+ selected !== undefined &&
+ (exclude ? selected === actual : selected !== actual)
+ )
+ return false;
+ }
+ if (filters.emailShared === 'only' && !exclude) return false;
+ const range = filters.emailUpdatedAt;
+ if (range) {
+ const time = draft.updatedAt;
+ const match =
+ (!range.gt || time > Date.parse(range.gt)) &&
+ (!range.gte || time >= Date.parse(range.gte)) &&
+ (!range.lt || time < Date.parse(range.lt)) &&
+ (!range.lte || time <= Date.parse(range.lte));
+ if (exclude ? match : !match) return false;
+ }
+ return true;
+ };
+ return matches(query.include, false) && matches(query.exclude, true);
+}
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.ts
new file mode 100644
index 0000000000..9d081d47f3
--- /dev/null
+++ b/apps/web/src/lib/queries/email/local-draft-store.test.ts
@@ -0,0 +1,328 @@
+import { Blob as NodeBlob } from 'node:buffer';
+import 'fake-indexeddb/auto';
+import type { LocalDraft } from '@app/features/email-compose/core/local-draft';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createLocalDraftStore } from './local-draft-store';
+
+const stores: ReturnType<typeof createLocalDraftStore>[] = [];
+const open = (name = crypto.randomUUID()) => {
+ const store = createLocalDraftStore(name);
+ stores.push(store);
+ return store;
+};
+const snapshot = (
+ subject = 'Keep this draft',
+ expectedRevision = 0
+): Omit<LocalDraft, 'revision' | 'acknowledgedRevision' | 'updatedAt'> & {
+ expectedRevision: number;
+} => ({
+ expectedRevision,
+ key: 'local',
+ accountId: 'owner',
+ generation: 'generation',
+ draftId: 'local',
+ threadId: 'thread',
+ content: { subject },
+ attachments: [],
+ status: 'dirty',
+});
+afterEach(async () => {
+ for (const store of stores.splice(0)) await store.close();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('durable email working copies', () => {
+ it('retains rejected content and further edits across reopening', async () => {
+ const name = crypto.randomUUID();
+ const first = open(name);
+ const session = await first.activate('owner');
+ await first.save(session, snapshot());
+ await first.update(session, 'local', (draft) => ({
+ ...draft,
+ status: 'failed',
+ errorCode: 'INTERNAL',
+ }));
+ await first.save(session, snapshot('Edited after rejection', 1));
+ await first.close();
+ const second = open(name);
+ expect(
+ await second.read(await second.activate('owner'), 'local')
+ ).toMatchObject({
+ revision: 2,
+ status: 'failed',
+ content: { subject: 'Edited after rejection' },
+ });
+ });
+ it('commits file bytes with their references and restores them after reopening', async () => {
+ const name = crypto.randomUUID();
+ const first = open(name);
+ const owner = await first.activate('owner');
+ const draft = snapshot();
+ draft.attachments = [
+ {
+ type: 'local',
+ id: 'file',
+ name: 'note.txt',
+ mimeType: 'text/plain',
+ size: 5,
+ lastModified: 0,
+ uploaded: false,
+ },
+ ];
+ await first.save(
+ owner,
+ draft,
+ new Map([['file', new NodeBlob(['hello']) as unknown as Blob]])
+ );
+ await first.close();
+ const second = open(name);
+ const session = await second.activate('owner');
+ expect(await (await second.file(session, 'local', 'file'))?.text()).toBe(
+ 'hello'
+ );
+ await second.save(session, snapshot('Keep this draft', 1));
+ expect(await second.file(session, 'local', 'file')).toBeUndefined();
+ });
+ it('rejects stale snapshots inside the transaction across tabs', async () => {
+ const name = crypto.randomUUID();
+ const first = open(name);
+ const second = open(name);
+ const owner = await first.activate('owner');
+ await second.activate('owner');
+ await first.save(owner, snapshot('Original'));
+ const stale = snapshot('Slow older edit', 1);
+ await second.save(owner, snapshot('Newer edit', 1));
+ await expect(
+ first.save(
+ owner,
+ stale,
+ new Map([['stale-file', new NodeBlob(['stale']) as unknown as Blob]])
+ )
+ ).rejects.toThrow('changed while saving');
+ expect(await first.read(owner, 'local')).toMatchObject({
+ revision: 2,
+ content: { subject: 'Newer edit' },
+ });
+ expect(await first.file(owner, 'local', 'stale-file')).toBeUndefined();
+ await first.save(owner, snapshot('Edit based on latest', 2));
+ expect((await second.read(owner, 'local'))?.revision).toBe(3);
+ });
+ it('fences callbacks after discard and account changes', async () => {
+ const store = open();
+ const owner = await store.activate('owner');
+ await store.save(owner, snapshot());
+ await store.update(owner, 'local', () => undefined);
+ await expect(store.save(owner, snapshot('late edit'))).rejects.toThrow(
+ 'no longer active'
+ );
+ await expect(store.activate('another-owner')).rejects.toThrow();
+ await store.clear();
+ await store.activate('another-owner');
+ await expect(store.save(owner, snapshot())).rejects.toThrow(
+ 'no longer active'
+ );
+ expect(await store.list(owner)).toEqual([]);
+ });
+ it('does not notify subscribers from reads or session activation', async () => {
+ const store = open();
+ const owner = await store.activate('owner');
+ let notifications = 0;
+ const stop = store.subscribe(() => notifications++);
+ await store.activate('owner');
+ await store.list(owner);
+ await store.read(owner, 'local');
+ expect(notifications).toBe(0);
+ await store.save(owner, snapshot());
+ expect(notifications).toBe(1);
+ stop();
+ });
+});
+
+describe('working-copy concurrency fences', () => {
+ it('does not let a stale tab activate a prior session after logout', async () => {
+ const store = open();
+ const owner = await store.activate('owner', 'new-epoch');
+ await store.save(owner, snapshot());
+ await expect(
+ store.activate('owner', 'old-epoch', () => false)
+ ).rejects.toThrow();
+ await expect(store.activate('other-owner', 'new-epoch')).rejects.toThrow();
+ expect(await store.list(owner)).toHaveLength(1);
+ });
+ it('does not let a delayed logout wipe the next account session', async () => {
+ const store = open();
+ await store.activate('old-owner', 'old-epoch');
+ const next = await store.activate('owner', 'new-epoch');
+ await store.save(next, snapshot());
+ await store.clear(true, 'old-epoch');
+ expect(await store.list(next)).toHaveLength(1);
+ });
+ it('retires the old epoch even if logout cannot rotate localStorage', async () => {
+ const store = open();
+ const owner = await store.activate('owner', 'old-epoch');
+ await store.save(owner, snapshot());
+ await store.clear(true);
+ await expect(store.activate('owner', 'old-epoch')).rejects.toThrow();
+ expect(
+ await store.list(await store.activate('owner', 'new-epoch'))
+ ).toEqual([]);
+ });
+ it('merges upload receipts committed after a snapshot was captured', async () => {
+ const store = open();
+ const owner = await store.activate('owner');
+ const input = snapshot();
+ input.attachments = [
+ {
+ type: 'local',
+ id: 'file',
+ name: 'file',
+ mimeType: '',
+ size: 0,
+ lastModified: 0,
+ uploaded: false,
+ },
+ ];
+ await store.save(owner, input);
+ await store.update(owner, 'local', (draft) => ({
+ ...draft,
+ attachments: [
+ { ...input.attachments[0], attachmentId: 'uploaded', uploaded: true },
+ ],
+ }));
+ await store.save(owner, { ...input, expectedRevision: 1 });
+ expect((await store.read(owner, 'local'))?.attachments[0]).toMatchObject({
+ attachmentId: 'uploaded',
+ uploaded: true,
+ });
+ });
+ it('repairs a failed receipt journal from completed in-memory upload', async () => {
+ const store = open();
+ const owner = await store.activate('owner');
+ const input = snapshot();
+ input.attachments = [
+ {
+ type: 'local',
+ id: 'file',
+ name: 'file',
+ mimeType: '',
+ size: 0,
+ lastModified: 0,
+ attachmentId: 'uploaded',
+ uploaded: false,
+ },
+ ];
+ await store.save(owner, input);
+ if (input.attachments[0].type !== 'local')
+ throw new Error('Expected local fixture');
+ input.attachments[0] = { ...input.attachments[0], uploaded: true };
+ await store.save(owner, { ...input, expectedRevision: 1 });
+ expect((await store.read(owner, 'local'))?.attachments[0]).toMatchObject({
+ attachmentId: 'uploaded',
+ uploaded: true,
+ });
+ });
+ it('explicit undo uses a new generation without admitting late pre-send writes', async () => {
+ const store = open();
+ const owner = await store.activate('owner');
+ const original = {
+ ...snapshot(),
+ generation: await store.generation(owner, 'local'),
+ };
+ await store.save(owner, original);
+ await store.update(owner, 'local', () => undefined);
+ const generation = await store.generation(owner, 'local', true);
+ await store.save(owner, {
+ ...original,
+ generation,
+ content: { subject: 'Undo' },
+ });
+ await expect(store.save(owner, original)).rejects.toThrow();
+ expect((await store.read(owner, 'local'))?.content.subject).toBe('Undo');
+ });
+ it('retires a server alias and removes attachment bytes across tabs on discard', async () => {
+ const name = crypto.randomUUID();
+ const first = open(name);
+ const second = open(name);
+ const owner = await first.activate('owner');
+ await second.activate('owner');
+ // Another tab began a save through the server ID before discard.
+ const aliasGeneration = await second.generation(owner, 'server');
+ const original = {
+ ...snapshot(),
+ serverDraftId: 'server',
+ attachments: [
+ {
+ type: 'local' as const,
+ id: 'file',
+ name: 'note.txt',
+ mimeType: 'text/plain',
+ size: 5,
+ lastModified: 0,
+ uploaded: false,
+ },
+ ],
+ };
+ await first.save(
+ owner,
+ original,
+ new Map([['file', new NodeBlob(['hello']) as unknown as Blob]])
+ );
+ await first.update(owner, 'local', () => undefined);
+ expect(await second.read(owner, 'server')).toBeUndefined();
+ expect(await second.file(owner, 'local', 'file')).toBeUndefined();
+ for (const generation of [
+ aliasGeneration,
+ await second.generation(owner, 'server'),
+ ]) {
+ await expect(
+ second.save(owner, {
+ ...snapshot('Late server edit'),
+ key: 'server',
+ draftId: 'server',
+ generation,
+ })
+ ).rejects.toThrow('no longer active');
+ }
+ expect(await second.list(owner)).toEqual([]);
+ });
+});
+
+describe('notification failures do not affect durable commits', () => {
+ it('opens and saves when BroadcastChannel construction throws', async () => {
+ vi.stubGlobal(
+ 'BroadcastChannel',
+ class {
+ constructor() {
+ throw new Error('Unavailable');
+ }
+ }
+ );
+ const store = open();
+ const owner = await store.activate('owner');
+ await store.save(owner, snapshot());
+ expect(await store.list(owner)).toHaveLength(1);
+ });
+ it('resolves commits and notifies remaining listeners after notification errors', async () => {
+ vi.stubGlobal(
+ 'BroadcastChannel',
+ class {
+ postMessage() {
+ throw new Error('Unavailable');
+ }
+ close() {}
+ }
+ );
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const store = open();
+ const owner = await store.activate('owner');
+ const listener = vi.fn();
+ store.subscribe(() => {
+ throw new Error('Bad listener');
+ });
+ store.subscribe(listener);
+ await store.save(owner, snapshot());
+ expect(await store.list(owner)).toHaveLength(1);
+ expect(listener).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/lib/queries/email/local-draft-store.ts b/apps/web/src/lib/queries/email/local-draft-store.ts
new file mode 100644
index 0000000000..275c7d446c
--- /dev/null
+++ b/apps/web/src/lib/queries/email/local-draft-store.ts
@@ -0,0 +1,547 @@
+import type {
+ DraftAttempt,
+ LocalDraft,
+} from '@app/features/email-compose/core/local-draft';
+
+/** Only pre-metadata queue entries need a separate durable association. */
+type AttemptRecord = DraftAttempt & {
+ transactionId: string;
+ storageGeneration: string;
+};
+type Session = { accountId: string; epoch: string };
+type StoredDraft = LocalDraft & { epoch: string };
+const STORES = ['drafts', 'files', 'attempts', 'meta'] as const;
+
+/** Transactional working-copy storage. Unlike a query cache, it never evicts edits. */
+export function createLocalDraftStore(
+ dbName = 'macro-email-working-copies-v1'
+) {
+ let connection: Promise<IDBDatabase> | undefined;
+ const listeners = new Set<() => void>();
+ let channel: BroadcastChannel | undefined;
+ const notify = () => {
+ for (const listener of listeners) {
+ try {
+ listener();
+ } catch (error) {
+ console.error('Unable to notify local draft subscriber', error);
+ }
+ }
+ };
+ const changed = () => {
+ notify();
+ try {
+ channel?.postMessage(null);
+ } catch {
+ /* Durable state remains readable without notifications. */
+ }
+ };
+ const open = () =>
+ (connection ??= new Promise<IDBDatabase>((resolve, reject) => {
+ const request = indexedDB.open(dbName, 1);
+ request.onupgradeneeded = () => {
+ for (const name of STORES) request.result.createObjectStore(name);
+ };
+ request.onerror = () => {
+ connection = undefined;
+ reject(request.error);
+ };
+ request.onsuccess = () => {
+ const db = request.result;
+ db.onversionchange = () => {
+ db.close();
+ 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. */
+ }
+ };
+ }));
+ async function transaction<T>(
+ mode: IDBTransactionMode,
+ run: (tx: IDBTransaction, finish: (value: T) => void) => void,
+ publish = true
+ ): Promise<T> {
+ const db = await open();
+ return await new Promise<T>((resolve, reject) => {
+ const tx = db.transaction([...STORES], mode);
+ let value: T;
+ tx.oncomplete = () => {
+ resolve(value);
+ if (mode === 'readwrite' && publish) changed();
+ };
+ tx.onabort = () =>
+ reject(tx.error ?? new Error('Draft storage transaction aborted'));
+ tx.onerror = () =>
+ reject(tx.error ?? new Error('Unable to save draft on this device'));
+ try {
+ run(tx, (next) => {
+ value = next;
+ });
+ } catch (error) {
+ tx.abort();
+ reject(error);
+ }
+ });
+ }
+ function withSession<T>(
+ tx: IDBTransaction,
+ session: Session,
+ run: () => void,
+ finish: (value: T) => void,
+ stale: T
+ ) {
+ const request = tx.objectStore('meta').get('session');
+ request.onsuccess = () => {
+ const current = request.result as Session | undefined;
+ if (
+ current?.accountId !== session.accountId ||
+ current.epoch !== session.epoch
+ ) {
+ finish(stale);
+ return;
+ }
+ run();
+ };
+ }
+ const read = async (session: Session, id: string) =>
+ await transaction<LocalDraft | undefined>('readonly', (tx, finish) => {
+ withSession(
+ tx,
+ session,
+ () => {
+ const request = tx.objectStore('drafts').getAll();
+ request.onsuccess = () =>
+ finish(
+ (request.result as StoredDraft[]).find(
+ (draft) =>
+ draft.epoch === session.epoch &&
+ draft.accountId === session.accountId &&
+ (draft.key === id ||
+ draft.draftId === id ||
+ draft.serverDraftId === id)
+ )
+ );
+ },
+ finish,
+ undefined
+ );
+ });
+ return {
+ /** Account transitions clear old content and fence outstanding transactions. */
+ async activate(
+ accountId: string,
+ epoch?: string,
+ isCurrent = () => true
+ ): Promise<Session> {
+ return await transaction(
+ 'readwrite',
+ (tx, finish) => {
+ const meta = tx.objectStore('meta');
+ const retired = meta.get(['retired-session', epoch ?? '']);
+ retired.onsuccess = () => {
+ if (epoch && retired.result) {
+ tx.abort();
+ return;
+ }
+ const request = meta.get('session');
+ request.onsuccess = () => {
+ const previous = request.result as Session | undefined;
+ if (
+ !isCurrent() ||
+ (previous &&
+ previous.accountId !== accountId &&
+ (!epoch || previous.epoch === epoch))
+ ) {
+ tx.abort();
+ return;
+ }
+ if (
+ previous?.accountId === accountId &&
+ (!epoch || previous.epoch === epoch)
+ ) {
+ finish(previous);
+ return;
+ }
+ for (const name of STORES) tx.objectStore(name).clear();
+ const session = {
+ accountId,
+ epoch: epoch ?? crypto.randomUUID(),
+ };
+ meta.put(session, 'session');
+ finish(session);
+ };
+ };
+ },
+ false
+ );
+ },
+ read,
+ async generation(
+ session: Session,
+ key: string,
+ revive = false
+ ): Promise<string> {
+ const result = await transaction<string | undefined>(
+ 'readwrite',
+ (tx, finish) =>
+ withSession(
+ tx,
+ session,
+ () => {
+ const meta = tx.objectStore('meta');
+ const request = meta.get(['generation', key]);
+ request.onsuccess = () => {
+ const generation = revive
+ ? crypto.randomUUID()
+ : (request.result ?? crypto.randomUUID());
+ meta.put(generation, ['generation', key]);
+ finish(generation);
+ };
+ },
+ finish,
+ undefined
+ ),
+ false
+ );
+ if (!result) throw new Error('This draft session is no longer active');
+ return result;
+ },
+ async list(session: Session): Promise<LocalDraft[]> {
+ return await transaction('readonly', (tx, finish) =>
+ withSession(
+ tx,
+ session,
+ () => {
+ const request = tx.objectStore('drafts').getAll();
+ request.onsuccess = () =>
+ finish(
+ (request.result as StoredDraft[]).filter(
+ (draft) =>
+ draft.accountId === session.accountId &&
+ draft.epoch === session.epoch
+ )
+ );
+ },
+ finish,
+ []
+ )
+ );
+ },
+ /** Compare the snapshot revision and commit its content and files atomically. */
+ async save(
+ session: Session,
+ input: Omit<
+ LocalDraft,
+ 'revision' | 'acknowledgedRevision' | 'updatedAt'
+ > & { expectedRevision: number },
+ files: ReadonlyMap<string, Blob> = new Map()
+ ): Promise<LocalDraft> {
+ const result = await transaction<LocalDraft | Error | undefined>(
+ 'readwrite',
+ (tx, finish) =>
+ withSession(
+ tx,
+ session,
+ () => {
+ const drafts = tx.objectStore('drafts');
+ const retired = tx
+ .objectStore('meta')
+ .get(['retired', input.key, input.generation]);
+ retired.onsuccess = () => {
+ if (retired.result) {
+ finish(undefined);
+ return;
+ }
+ const request = drafts.get(input.key);
+ request.onsuccess = () => {
+ const previous = request.result as StoredDraft | undefined;
+ if (previous && previous.generation !== input.generation) {
+ finish(undefined);
+ return;
+ }
+ const paused =
+ previous?.status === 'failed' ||
+ previous?.status === 'unconfirmed' ||
+ previous?.status === 'delete-failed';
+ if (previous?.status === 'deleting') {
+ finish(undefined);
+ return;
+ }
+ if ((previous?.revision ?? 0) !== input.expectedRevision) {
+ finish(
+ new Error(
+ 'This draft changed while saving. Reopen it to use the latest version.'
+ )
+ );
+ return;
+ }
+ const { expectedRevision: _expectedRevision, ...snapshot } =
+ input;
+ const draft: StoredDraft = {
+ ...snapshot,
+ epoch: session.epoch,
+ latestAttemptId: previous?.latestAttemptId,
+ queuedAttemptId: previous?.queuedAttemptId,
+ attachments: input.attachments.map((attachment) => {
+ if (attachment.type !== 'local') return attachment;
+ const receipt = previous?.attachments.find(
+ (saved) =>
+ saved.type === 'local' && saved.id === attachment.id
+ );
+ // Upload callbacks can commit while file bytes are being copied.
+ // The working-copy snapshot must not erase a newer receipt.
+ return receipt?.type === 'local'
+ ? {
+ ...attachment,
+ attachmentId:
+ receipt.attachmentId ??
+ (attachment.uploaded
+ ? attachment.attachmentId
+ : undefined),
+ uploaded:
+ receipt.uploaded ||
+ (attachment.uploaded &&
+ (!receipt.attachmentId ||
+ receipt.attachmentId ===
+ attachment.attachmentId)),
+ }
+ : attachment;
+ }),
+ serverDraftId:
+ previous?.serverDraftId ?? input.serverDraftId,
+ serverThreadId:
+ previous?.serverThreadId ?? input.serverThreadId,
+ revision: (previous?.revision ?? 0) + 1,
+ acknowledgedRevision: previous?.acknowledgedRevision ?? 0,
+ status: paused ? previous.status : 'dirty',
+ errorCode: paused ? previous.errorCode : undefined,
+ updatedAt: Date.now(),
+ };
+ for (const [id, blob] of files)
+ tx.objectStore('files').put(blob, [input.key, id]);
+ const retained = new Set(
+ input.attachments.flatMap((a) =>
+ a.type === 'local' ? [a.id] : []
+ )
+ );
+ for (const attachment of previous?.attachments ?? [])
+ if (
+ attachment.type === 'local' &&
+ !retained.has(attachment.id)
+ )
+ tx.objectStore('files').delete([
+ input.key,
+ attachment.id,
+ ]);
+ drafts.put(draft, input.key);
+ finish(draft);
+ };
+ };
+ },
+ finish,
+ undefined
+ )
+ );
+ if (result instanceof Error) throw result;
+ if (!result) throw new Error('This draft session is no longer active');
+ return result;
+ },
+ async file(
+ session: Session,
+ key: string,
+ id: string
+ ): Promise<Blob | undefined> {
+ return await transaction('readonly', (tx, finish) =>
+ withSession(
+ tx,
+ session,
+ () => {
+ const request = tx.objectStore('files').get([key, id]);
+ request.onsuccess = () => finish(request.result);
+ },
+ finish,
+ undefined
+ )
+ );
+ },
+ async update(
+ session: Session,
+ key: string,
+ change: (draft: LocalDraft) => LocalDraft | undefined
+ ): Promise<LocalDraft | undefined> {
+ return await transaction('readwrite', (tx, finish) =>
+ withSession(
+ tx,
+ session,
+ () => {
+ const drafts = tx.objectStore('drafts');
+ const request = drafts.get(key);
+ request.onsuccess = () => {
+ const previous = request.result as StoredDraft | undefined;
+ if (!previous) {
+ finish(undefined);
+ return;
+ }
+ const next = change(previous);
+ if (next) drafts.put({ ...next, epoch: session.epoch }, key);
+ else {
+ // A reopened editor may know only the server ID. Retire every
+ // identity in this transaction so it cannot recreate the copy
+ // under a different key after the content has been removed.
+ const meta = tx.objectStore('meta');
+ for (const id of new Set([
+ key,
+ previous.draftId,
+ previous.serverDraftId,
+ ])) {
+ if (!id) continue;
+ const generation = meta.get(['generation', id]);
+ generation.onsuccess = () => {
+ if (generation.result)
+ meta.put(true, ['retired', id, generation.result]);
+ meta.put(previous.generation, ['generation', id]);
+ meta.put(true, ['retired', id, previous.generation]);
+ };
+ }
+ drafts.delete(key);
+ for (const attachment of previous.attachments)
+ if (attachment.type === 'local')
+ tx.objectStore('files').delete([key, attachment.id]);
+ }
+ finish(next);
+ };
+ },
+ finish,
+ undefined
+ )
+ );
+ },
+ async recordAttempt(
+ session: Session,
+ attempt: AttemptRecord
+ ): Promise<void> {
+ await transaction<void>('readwrite', (tx, finish) =>
+ withSession(
+ tx,
+ session,
+ () => {
+ tx.objectStore('attempts').put(attempt, [
+ attempt.storageGeneration,
+ attempt.transactionId,
+ ]);
+ finish();
+ },
+ finish,
+ undefined
+ )
+ );
+ },
+ async removeAttempt(
+ session: Session,
+ storageGeneration: string,
+ transactionId: string
+ ): Promise<void> {
+ await transaction<void>(
+ 'readwrite',
+ (tx, finish) =>
+ withSession(
+ tx,
+ session,
+ () => {
+ const request = tx.objectStore('attempts').openCursor();
+ request.onsuccess = () => {
+ const cursor = request.result;
+ if (!cursor) {
+ finish();
+ return;
+ }
+ const attempt = cursor.value as AttemptRecord;
+ if (
+ attempt.storageGeneration === storageGeneration &&
+ attempt.transactionId === transactionId
+ )
+ cursor.delete();
+ cursor.continue();
+ };
+ },
+ finish,
+ undefined
+ ),
+ false
+ );
+ },
+ async attempts(session: Session): Promise<AttemptRecord[]> {
+ return await transaction(
+ 'readwrite',
+ (tx, finish) =>
+ withSession(
+ tx,
+ session,
+ () => {
+ const attempts: AttemptRecord[] = [];
+ const request = tx.objectStore('attempts').openCursor();
+ request.onsuccess = () => {
+ const cursor = request.result;
+ if (!cursor) {
+ finish(attempts);
+ return;
+ }
+ const attempt = cursor.value as Partial<AttemptRecord>;
+ if (
+ typeof attempt.transactionId !== 'string' ||
+ typeof attempt.storageGeneration !== 'string'
+ )
+ cursor.delete();
+ else if (attempt.accountId === session.accountId)
+ attempts.push(attempt as AttemptRecord);
+ cursor.continue();
+ };
+ },
+ finish,
+ []
+ ),
+ false
+ );
+ },
+ async clear(retire = false, expectedEpoch?: string): Promise<void> {
+ await transaction<void>('readwrite', (tx, finish) => {
+ const meta = tx.objectStore('meta');
+ const request = meta.get('session');
+ request.onsuccess = () => {
+ const previous = request.result as Session | undefined;
+ if (expectedEpoch && previous && previous.epoch !== expectedEpoch) {
+ finish();
+ return;
+ }
+ for (const name of STORES) tx.objectStore(name).clear();
+ if (retire && previous)
+ meta.put(true, ['retired-session', previous.epoch]);
+ finish();
+ };
+ });
+ },
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ async close() {
+ if (connection) (await connection).close();
+ connection = undefined;
+ try {
+ channel?.close();
+ } catch {
+ /* Closing notifications cannot retain the database. */
+ }
+ channel = undefined;
+ },
+ };
+}
diff --git a/apps/web/src/lib/queries/email/local-drafts.test.ts b/apps/web/src/lib/queries/email/local-drafts.test.ts
new file mode 100644
index 0000000000..45850cc382
--- /dev/null
+++ b/apps/web/src/lib/queries/email/local-drafts.test.ts
@@ -0,0 +1,328 @@
+import 'fake-indexeddb/auto';
+import type { CacheHost } from '@graphql-cache/host/types';
+import type {
+ ClaimedMutation,
+ MutationInspection,
+} from '@graphql-cache/protocol';
+import type { OperationResult } from '@urql/core';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const auth = vi.hoisted(() => ({ user: { authenticated: true, id: 'owner' } }));
+const stagedUpload = vi.hoisted(() =>
+ vi.fn<() => { previewSrc: string; size: number } | undefined>()
+);
+vi.mock('../client', () => ({
+ queryClient: { getQueryData: () => auth.user },
+}));
+vi.mock('@core/mobile/nativeStagedUpload', () => ({
+ getNativeStagedUpload: stagedUpload,
+}));
+let runtime: typeof import('./local-drafts');
+const input = (subject = 'Draft') => ({
+ draft: { subject },
+ clientHandles: { draftId: 'local', threadId: 'thread' },
+ attachments: [],
+});
+const queue: MutationInspection[] = [];
+const host = {
+ inspectMutations: async () => queue,
+ currentStorageGeneration: async () => 'storage',
+} as unknown as CacheHost;
+const claimed = (metadata: unknown) =>
+ ({
+ transactionId: 'tx',
+ clientMetadata: metadata,
+ operationName: 'SaveEmailDraft',
+ superseded: false,
+ }) as ClaimedMutation;
+const success = {
+ data: {
+ saveEmailDraft: { draftId: 'server', thread: { id: 'server-thread' } },
+ },
+} as OperationResult;
+const failure = {
+ error: { graphQLErrors: [{ extensions: { code: 'INVALID' } }] },
+} as unknown as OperationResult;
+
+beforeEach(async () => {
+ vi.resetModules();
+ localStorage.clear();
+ queue.length = 0;
+ auth.user = { authenticated: true, id: 'owner' };
+ stagedUpload.mockReset();
+ runtime = await import('./local-drafts');
+ await runtime.localDraftStore.clear();
+});
+afterEach(async () => {
+ vi.unstubAllGlobals();
+ await runtime.localDraftStore.close();
+});
+
+describe('draft queue recovery', () => {
+ it('rejects an old editor generation after discard and Undo reuse the server identity', async () => {
+ const serverInput = (subject: string) => ({
+ draft: { db_id: 'server', subject },
+ attachments: [],
+ });
+ const original = await runtime.saveLocalDraft(serverInput('Original'));
+ await runtime.forgetLocalDraft('server');
+ await runtime.reviveLocalDraft('server');
+ const revived = await runtime.saveLocalDraft(serverInput('Explicit undo'));
+ expect(revived.revision).toBe(original.revision);
+ expect(revived.generation).not.toBe(original.generation);
+
+ await expect(
+ runtime.saveLocalDraft({
+ ...serverInput('Stale editor'),
+ expectedRevision: original.revision,
+ expectedGeneration: original.generation,
+ })
+ ).rejects.toThrow();
+ expect(await runtime.readLocalDraft('server')).toMatchObject({
+ generation: revived.generation,
+ revision: revived.revision,
+ content: { subject: 'Explicit undo' },
+ });
+ await expect(
+ runtime.saveLocalDraft({
+ ...serverInput('Edited after undo'),
+ expectedRevision: revived.revision,
+ expectedGeneration: revived.generation,
+ })
+ ).resolves.toMatchObject({
+ generation: revived.generation,
+ revision: revived.revision + 1,
+ content: { subject: 'Edited after undo' },
+ });
+ });
+ it('does not rebase an old editor snapshot onto a newer stored revision', async () => {
+ const original = await runtime.saveLocalDraft(input('Original'));
+ const latest = await runtime.saveLocalDraft(input('Other tab edited'));
+ await expect(
+ runtime.saveLocalDraft({
+ ...input('Old editor snapshot'),
+ expectedRevision: original.revision,
+ })
+ ).rejects.toThrow('changed while saving');
+ expect(await runtime.readLocalDraft('local')).toMatchObject({
+ revision: latest.revision,
+ content: { subject: 'Other tab edited' },
+ });
+ });
+ it('rejects an older snapshot whose file copy finishes after a newer save', async () => {
+ await runtime.saveLocalDraft(input('Original'));
+ const started = Promise.withResolvers<void>();
+ const response = Promise.withResolvers<Response>();
+ stagedUpload.mockReturnValueOnce({ previewSrc: '/staged-file', size: 5 });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(() => {
+ started.resolve();
+ return response.promise;
+ })
+ );
+ const older = runtime.saveLocalDraft({
+ ...input('Older snapshot'),
+ attachments: [{ type: 'local', file: new File(['hello'], 'note.txt') }],
+ });
+ const rejected = expect(older).rejects.toThrow('changed while saving');
+ await started.promise;
+ const newer = await runtime.saveLocalDraft(input('Newer snapshot'));
+ response.resolve(new Response('hello'));
+ await rejected;
+ expect(await runtime.readLocalDraft('local')).toMatchObject({
+ revision: newer.revision,
+ content: { subject: 'Newer snapshot' },
+ attachments: [],
+ });
+ });
+ it('wipes a discarded working copy and rejects stale saves through either identity', async () => {
+ const draft = await runtime.saveLocalDraft(input());
+ const saving = await runtime.beginDraftAttempt(draft, 'save');
+ const lifecycle = runtime.localDraftQueueLifecycle(host);
+ await lifecycle.onMutationAttemptResult!(claimed(saving), success, false);
+ const saved = (await runtime.readLocalDraft('server'))!;
+ const deleting = await runtime.beginDraftAttempt(saved, 'delete');
+ await lifecycle.onMutationAttemptResult!(
+ claimed(deleting),
+ { data: { deleteEmailDraft: { deleted: true } } } as OperationResult,
+ false
+ );
+ expect(await runtime.listLocalDrafts()).toEqual([]);
+ await expect(
+ runtime.saveLocalDraft(input('Stale handle'))
+ ).rejects.toThrow();
+ await expect(
+ runtime.saveLocalDraft({
+ draft: { db_id: 'server', subject: 'Stale server identity' },
+ attachments: [],
+ })
+ ).rejects.toThrow();
+ expect(await runtime.listLocalDrafts()).toEqual([]);
+ await runtime.reviveLocalDraft('server');
+ await runtime.saveLocalDraft({
+ draft: { db_id: 'server', subject: 'Explicit undo' },
+ attachments: [],
+ });
+ expect((await runtime.readLocalDraft('server'))?.content.subject).toBe(
+ 'Explicit undo'
+ );
+ });
+ it('keeps modern correlation in the queue without an ever-growing attempt journal', async () => {
+ const draft = await runtime.saveLocalDraft(input());
+ await runtime.beginDraftAttempt(draft, 'save');
+ const owner = await runtime.localDraftStore.activate('owner');
+ expect(await runtime.localDraftStore.attempts(owner)).toEqual([]);
+ });
+ it('does not mistake another tab’s live debounce for a lost save', async () => {
+ await runtime.saveLocalDraft(input());
+ await runtime.localDraftQueueLifecycle(host).prepareMutationQueue!();
+ expect((await runtime.readLocalDraft('local'))?.status).toBe('dirty');
+ });
+ it('does not reject an intent still crossing the local-to-queue admission gap', async () => {
+ const draft = await runtime.saveLocalDraft(input());
+ await runtime.beginDraftAttempt(draft, 'save');
+ await runtime.localDraftQueueLifecycle(host).prepareMutationQueue!();
+ expect((await runtime.readLocalDraft('local'))?.status).toBe('dirty');
+ });
+ it('marks an abandoned queued intent recoverable after restart', async () => {
+ const draft = await runtime.saveLocalDraft(input());
+ const attempt = await runtime.beginDraftAttempt(draft, 'save');
+ await runtime.markDraftAttemptQueued(attempt);
+ await runtime.localDraftQueueLifecycle(host).prepareMutationQueue!();
+ expect((await runtime.readLocalDraft('local'))?.status).toBe('unconfirmed');
+ });
+ it('does not let an old save overwrite a newer discard intent', async () => {
+ const draft = await runtime.saveLocalDraft(input());
+ const saving = await runtime.beginDraftAttempt(draft, 'save');
+ await runtime.beginDraftAttempt(draft, 'delete');
+ await runtime.localDraftQueueLifecycle(host).onMutationAttemptResult!(
+ claimed(saving),
+ success,
+ false
+ );
+ expect(await runtime.readLocalDraft('local')).toMatchObject({
+ status: 'deleting',
+ serverDraftId: 'server',
+ acknowledgedRevision: draft.revision,
+ });
+ });
+ it('does not acknowledge later edits or let an old result clear newer failure', async () => {
+ const first = await runtime.saveLocalDraft(input('First'));
+ const saving = await runtime.beginDraftAttempt(first, 'save');
+ const second = await runtime.saveLocalDraft(input('Second'));
+ const newer = await runtime.beginDraftAttempt(second, 'save');
+ const lifecycle = runtime.localDraftQueueLifecycle(host);
+ await lifecycle.onMutationAttemptResult!(claimed(newer), failure, false);
+ await lifecycle.onMutationAttemptResult!(claimed(saving), success, false);
+ expect(await runtime.readLocalDraft('local')).toMatchObject({
+ status: 'failed',
+ revision: second.revision,
+ acknowledgedRevision: first.revision,
+ content: { subject: 'Second' },
+ });
+ });
+ it('preserves legacy attachment references and sender before replay', async () => {
+ queue.push({
+ transactionId: 'legacy',
+ uuid: 'local',
+ query: '',
+ operationName: 'SaveEmailDraft',
+ superseded: false,
+ variables: {
+ input: { draftId: 'local', threadDbId: 'thread', subject: 'Legacy' },
+ },
+ optimisticData: {
+ saveEmailDraft: {
+ draft: {
+ from: { email: '[email protected]' },
+ attachmentsDraft: [
+ {
+ id: 'attachment',
+ fileName: 'report.pdf',
+ contentType: 'application/pdf',
+ size: 12,
+ s3Key: 's3',
+ },
+ ],
+ attachmentsForwarded: [
+ {
+ attachmentId: 'forwarded',
+ filename: 'forward.txt',
+ mimeType: 'text/plain',
+ sizeBytes: 5,
+ },
+ ],
+ },
+ },
+ },
+ });
+ const lifecycle = runtime.localDraftQueueLifecycle(host);
+ await lifecycle.prepareMutationQueue!();
+ expect(await runtime.readLocalDraft('local')).toMatchObject({
+ senderEmail: '[email protected]',
+ attachments: [
+ { type: 'remote', attachmentId: 'attachment', fileName: 'report.pdf' },
+ { type: 'forwarded', attachmentId: 'forwarded' },
+ ],
+ });
+ await lifecycle.onMutationAttemptResult!(
+ { ...claimed(undefined), transactionId: 'legacy' },
+ success,
+ false
+ );
+ queue.length = 0;
+ await runtime.localDraftQueueLifecycle(host).prepareMutationQueue!();
+ expect(
+ await runtime.localDraftStore.attempts(
+ await runtime.localDraftStore.activate('owner')
+ )
+ ).toEqual([]);
+ });
+ it('rejects stale account and epoch readers without wiping existing content', async () => {
+ await runtime.saveLocalDraft(input());
+ auth.user = { authenticated: true, id: 'other-owner' };
+ await expect(runtime.listLocalDrafts()).rejects.toThrow('no longer active');
+ auth.user = { authenticated: true, id: 'owner' };
+ expect(await runtime.listLocalDrafts()).toHaveLength(1);
+ localStorage.setItem('email-working-copies:epoch', 'new-session');
+ await expect(runtime.listLocalDrafts()).rejects.toThrow('no longer active');
+ });
+ it('rejects delayed old-editor work after logout even if authentication changes', async () => {
+ const prior = await runtime.saveLocalDraft(input());
+ const owner = await runtime.localDraftStore.activate('owner');
+ auth.user = { authenticated: false, id: '' };
+ await runtime.clearLocalDrafts();
+ auth.user = { authenticated: true, id: 'other-owner' };
+ await expect(
+ runtime.saveLocalDraft(input('Late old editor'))
+ ).rejects.toThrow('no longer active');
+ await expect(
+ runtime.localDraftStore.save(owner, {
+ ...prior,
+ expectedRevision: prior.revision,
+ })
+ ).rejects.toThrow();
+ });
+ it('reconciles again after a recovery failure without mutation metadata', async () => {
+ const lifecycle = runtime.localDraftQueueLifecycle(host);
+ await lifecycle.prepareMutationQueue!();
+ const draft = await runtime.saveLocalDraft(input());
+ const attempt = await runtime.beginDraftAttempt(draft, 'save');
+ await runtime.markDraftAttemptQueued(attempt);
+ await lifecycle.onMutationAttemptResult!(
+ claimed(undefined),
+ {
+ error: {
+ graphQLErrors: [{ extensions: { code: 'LOCAL_RECOVERY_FAILED' } }],
+ },
+ } as unknown as OperationResult,
+ false
+ );
+ await lifecycle.prepareMutationQueue!();
+ expect(await runtime.readLocalDraft('local')).toMatchObject({
+ status: 'unconfirmed',
+ content: { subject: 'Draft' },
+ });
+ });
+});
diff --git a/apps/web/src/lib/queries/email/local-drafts.ts b/apps/web/src/lib/queries/email/local-drafts.ts
new file mode 100644
index 0000000000..5d009f1a44
--- /dev/null
+++ b/apps/web/src/lib/queries/email/local-drafts.ts
@@ -0,0 +1,795 @@
+import type { SaveEmailDraft } from '@app/features/email-compose/context/compose-capabilities';
+import type {
+ DraftAttempt,
+ LocalDraft,
+ LocalDraftAttachment,
+} from '@app/features/email-compose/core/local-draft';
+import type { DraftFormAttachment } from '@app/features/email-compose/primitives/email-form-state';
+import type { EmailMessage } from '@app/features/email-message/core/email-message';
+import { getNativeStagedUpload } from '@core/mobile/nativeStagedUpload';
+import type { NormalizedCacheExchangeOptions } from '@graphql-cache/exchange/normalized-cache-exchange';
+import type { CacheHost } from '@graphql-cache/host/types';
+import type {
+ ClaimedMutation,
+ MutationInspection,
+} from '@graphql-cache/protocol';
+import type { OperationResult } from '@urql/core';
+import { authKeys } from '../auth/keys';
+import type { UserInfoData } from '../auth/user-info';
+import { queryClient } from '../client';
+import { createLocalDraftStore } from './local-draft-store';
+
+export const localDraftStore = createLocalDraftStore();
+const fileIds = new WeakMap<File, string>();
+const fileCopies = new WeakMap<File, Promise<Blob>>();
+const pendingWrites = new Set<Promise<LocalDraft>>();
+const EPOCH_KEY = 'email-working-copies:epoch';
+let documentSession: { accountId: string; epoch: string } | undefined;
+let retiredSession = false;
+
+function storageEpoch() {
+ let epoch = localStorage.getItem(EPOCH_KEY);
+ if (!epoch) {
+ epoch = crypto.randomUUID();
+ localStorage.setItem(EPOCH_KEY, epoch);
+ }
+ return epoch;
+}
+
+export async function flushLocalDrafts(): Promise<void> {
+ while (pendingWrites.size) await Promise.all([...pendingWrites]);
+}
+
+export async function clearLocalDrafts(): Promise<void> {
+ // Quarantine before clearing so a failed disk wipe cannot expose old drafts.
+ retiredSession = true;
+ let quarantineError: unknown;
+ let previousEpoch = documentSession?.epoch;
+ try {
+ previousEpoch ??= localStorage.getItem(EPOCH_KEY) ?? undefined;
+ localStorage.setItem(EPOCH_KEY, crypto.randomUUID());
+ } catch (error) {
+ quarantineError = error;
+ }
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ localDraftStore.clear(true, previousEpoch),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('Clearing draft storage timed out')),
+ 2_000
+ );
+ }),
+ ]);
+ } catch (error) {
+ if (quarantineError)
+ throw new AggregateError(
+ [quarantineError, error],
+ 'Unable to clear local drafts'
+ );
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+async function session() {
+ const user = queryClient.getQueryData<UserInfoData>(
+ authKeys.userInfo.queryKey
+ );
+ if (!user?.authenticated || !user.id)
+ throw new Error('Sign in to save drafts on this device');
+ const epoch = storageEpoch();
+ if (
+ retiredSession ||
+ (documentSession &&
+ (documentSession.accountId !== user.id ||
+ documentSession.epoch !== epoch))
+ ) {
+ throw new Error(
+ 'This draft session is no longer active; reload to use the current account'
+ );
+ }
+ documentSession ??= { accountId: user.id, epoch };
+ const expected = documentSession;
+ return await localDraftStore.activate(
+ expected.accountId,
+ expected.epoch,
+ () => {
+ const current = queryClient.getQueryData<UserInfoData>(
+ authKeys.userInfo.queryKey
+ );
+ return (
+ !retiredSession &&
+ current?.authenticated === true &&
+ current.id === expected.accountId &&
+ localStorage.getItem(EPOCH_KEY) === expected.epoch
+ );
+ }
+ );
+}
+
+export async function listLocalDrafts(): Promise<LocalDraft[]> {
+ const owner = await session();
+ return await localDraftStore.list(owner);
+}
+export async function readLocalDraft(
+ id: string
+): Promise<LocalDraft | undefined> {
+ return await localDraftStore.read(await session(), id);
+}
+
+/** Local body HTML uses the same base64 representation as the editor's save input. */
+export function localDraftMessage(local: LocalDraft): EmailMessage {
+ const content = local.content;
+ const time = new Date(local.updatedAt).toISOString();
+ return {
+ ...content,
+ db_id: local.serverDraftId ?? local.draftId,
+ thread_db_id: local.serverThreadId ?? local.threadId ?? local.draftId,
+ link_id: local.inboxId ?? '',
+ is_draft: true,
+ created_at: time,
+ updated_at: time,
+ body_html_sanitized: content.body_html,
+ to: content.to ?? [],
+ cc: content.cc ?? [],
+ bcc: content.bcc ?? [],
+ from: { email: local.senderEmail ?? '' },
+ labels: [],
+ attachments: [],
+ attachments_draft: local.attachments.flatMap((attachment) =>
+ attachment.type === 'remote'
+ ? [
+ {
+ id: attachment.attachmentId,
+ file_name: attachment.fileName,
+ content_type: attachment.contentType,
+ size: attachment.fileSize,
+ s3_key: '',
+ },
+ ]
+ : []
+ ),
+ attachments_forwarded: local.attachments.flatMap((attachment) =>
+ attachment.type === 'forwarded'
+ ? [
+ {
+ attachment_id: attachment.attachmentId,
+ filename: attachment.fileName,
+ mime_type: attachment.mimeType,
+ size_bytes: attachment.fileSize,
+ },
+ ]
+ : []
+ ),
+ };
+}
+
+async function copyFile(file: File): Promise<Blob> {
+ let pending = fileCopies.get(file);
+ if (!pending) {
+ pending = (async () => {
+ const staged = getNativeStagedUpload(file);
+ if (!staged) return file;
+ if (!staged.previewSrc)
+ throw new Error('Attachment bytes are unavailable on this device');
+ const response = await fetch(staged.previewSrc);
+ if (!response.ok)
+ throw new Error('Unable to preserve attachment on this device');
+ const blob = await response.blob();
+ if (blob.size !== staged.size)
+ throw new Error('Attachment size mismatch');
+ return blob;
+ })();
+ fileCopies.set(file, pending);
+ }
+ try {
+ return await pending;
+ } catch (error) {
+ fileCopies.delete(file);
+ throw error;
+ }
+}
+
+export type LocalDraftInput = SaveEmailDraft & {
+ expectedRevision?: number;
+ expectedGeneration?: string;
+ attachments: readonly DraftFormAttachment[];
+ senderEmail?: string;
+};
+
+/** Called on every edit, including edits made while server autosave is paused. */
+export function saveLocalDraft(input: LocalDraftInput): Promise<LocalDraft> {
+ const write = persistLocalDraft(input);
+ pendingWrites.add(write);
+ void finishLocalWrite(write);
+ return write;
+}
+
+async function finishLocalWrite(write: Promise<LocalDraft>): Promise<void> {
+ try {
+ await write;
+ } catch {
+ /* The caller reports the original write failure. */
+ } finally {
+ pendingWrites.delete(write);
+ }
+}
+
+async function persistLocalDraft(input: LocalDraftInput): Promise<LocalDraft> {
+ const owner = await session();
+ const id = input.clientHandles?.draftId ?? input.draft.db_id;
+ if (!id)
+ throw new Error('Draft identity must be minted before local persistence');
+ const previous = await localDraftStore.read(owner, id);
+ const key = previous?.key ?? id;
+ const files = new Map<string, Blob>();
+ const attachments: LocalDraftAttachment[] = [];
+ for (const attachment of input.attachments) {
+ if (attachment.type !== 'local') {
+ attachments.push({ ...attachment });
+ continue;
+ }
+ let fileId = fileIds.get(attachment.file);
+ if (!fileId) {
+ fileId = crypto.randomUUID();
+ fileIds.set(attachment.file, fileId);
+ }
+ const blob = await copyFile(attachment.file);
+ files.set(fileId, blob);
+ const old = previous?.attachments.find(
+ (entry) => entry.type === 'local' && entry.id === fileId
+ );
+ attachments.push({
+ type: 'local',
+ id: fileId,
+ name: attachment.file.name,
+ mimeType: blob.type || attachment.file.type,
+ size: blob.size,
+ lastModified: attachment.file.lastModified,
+ attachmentId: attachment.attachmentId,
+ uploaded:
+ !!attachment.attachmentId &&
+ (attachment.uploaded === true ||
+ (old?.type === 'local' &&
+ old.attachmentId === attachment.attachmentId &&
+ old.uploaded)),
+ });
+ }
+ return await localDraftStore.save(
+ owner,
+ {
+ key,
+ expectedRevision: input.expectedRevision ?? previous?.revision ?? 0,
+ accountId: owner.accountId,
+ generation:
+ input.expectedGeneration ??
+ previous?.generation ??
+ (await localDraftStore.generation(owner, key)),
+ draftId: previous?.draftId ?? id,
+ threadId:
+ previous?.threadId ??
+ input.clientHandles?.threadId ??
+ input.draft.thread_db_id ??
+ undefined,
+ serverDraftId:
+ previous?.serverDraftId ??
+ (input.clientHandles ? undefined : (input.draft.db_id ?? undefined)),
+ serverThreadId: previous?.serverThreadId,
+ inboxId: input.inboxId,
+ senderEmail: input.senderEmail,
+ content: structuredClone({
+ ...input.draft,
+ replying_to_id:
+ input.draft.replying_to_id ?? previous?.content.replying_to_id,
+ provider_id: input.draft.provider_id ?? previous?.content.provider_id,
+ provider_thread_id:
+ input.draft.provider_thread_id ??
+ previous?.content.provider_thread_id,
+ thread_db_id:
+ input.draft.thread_db_id ?? previous?.content.thread_db_id,
+ }),
+ attachments,
+ status: 'dirty',
+ },
+ files
+ );
+}
+
+export async function restoreLocalAttachments(
+ local: LocalDraft
+): Promise<DraftFormAttachment[]> {
+ const owner = await session();
+ const attachments: DraftFormAttachment[] = [];
+ for (const attachment of local.attachments) {
+ if (attachment.type !== 'local') {
+ attachments.push(attachment);
+ continue;
+ }
+ const blob = await localDraftStore.file(owner, local.key, attachment.id);
+ if (!blob)
+ throw new Error(
+ `The locally saved attachment ${attachment.name} is unavailable`
+ );
+ const file = new File([blob], attachment.name, {
+ type: attachment.mimeType,
+ lastModified: attachment.lastModified,
+ });
+ fileIds.set(file, attachment.id);
+ attachments.push({
+ type: 'local',
+ file,
+ attachmentId: attachment.attachmentId,
+ uploaded: attachment.uploaded,
+ uploadPending: !attachment.uploaded && !!attachment.attachmentId,
+ });
+ }
+ return attachments;
+}
+
+export function draftSyncPaused(local: LocalDraft): boolean {
+ return (
+ local.status === 'failed' ||
+ local.status === 'unconfirmed' ||
+ local.status === 'delete-failed'
+ );
+}
+
+export async function resumeLocalDraft(id: string): Promise<void> {
+ const owner = await session();
+ const draft = await localDraftStore.read(owner, id);
+ if (!draft) return;
+ await localDraftStore.update(owner, draft.key, (current) => ({
+ ...current,
+ status: 'dirty',
+ errorCode: undefined,
+ latestAttemptId: undefined,
+ queuedAttemptId: undefined,
+ }));
+}
+
+export async function forgetLocalDraft(id: string): Promise<void> {
+ const owner = await session();
+ const draft = await localDraftStore.read(owner, id);
+ if (draft) await localDraftStore.update(owner, draft.key, () => undefined);
+}
+
+/** Only an explicit server Undo may start a fresh lifetime for a retired handle. */
+export async function reviveLocalDraft(id: string): Promise<void> {
+ const owner = await session();
+ await localDraftStore.generation(owner, id, true);
+}
+
+export async function clearLocalAttachmentReceipt(
+ draftId: string,
+ attachmentId: string
+): Promise<void> {
+ const owner = await session();
+ const draft = await localDraftStore.read(owner, draftId);
+ if (!draft) return;
+ await localDraftStore.update(owner, draft.key, (current) => ({
+ ...current,
+ attachments: current.attachments.map((attachment) =>
+ attachment.type === 'local' && attachment.attachmentId === attachmentId
+ ? { ...attachment, attachmentId: undefined, uploaded: false }
+ : attachment
+ ),
+ }));
+}
+
+/** A record ID is not an upload receipt; persist both stages independently. */
+export async function recordLocalAttachment(
+ draftId: string,
+ file: File,
+ attachmentId: string | undefined,
+ uploaded: boolean
+): Promise<void> {
+ const owner = await session();
+ const draft = await localDraftStore.read(owner, draftId);
+ const id = fileIds.get(file);
+ if (!draft || !id) return;
+ await localDraftStore.update(owner, draft.key, (current) => {
+ if (current.generation !== draft.generation) return current;
+ const attachments = current.attachments.map((attachment) =>
+ attachment.type === 'local' && attachment.id === id
+ ? { ...attachment, attachmentId, uploaded }
+ : attachment
+ );
+ return {
+ ...current,
+ attachments,
+ status:
+ !draftSyncPaused(current) &&
+ current.status !== 'deleting' &&
+ current.acknowledgedRevision === current.revision &&
+ !attachments.some(
+ (attachment) => attachment.type === 'local' && !attachment.uploaded
+ )
+ ? 'synced'
+ : current.status,
+ };
+ });
+}
+
+export async function beginDraftAttempt(
+ local: LocalDraft,
+ operation: 'save' | 'delete'
+): Promise<DraftAttempt> {
+ const owner = await session();
+ if (local.accountId !== owner.accountId)
+ throw new Error('This draft belongs to a previous account');
+ const attempt: DraftAttempt = {
+ kind: 'email-draft',
+ id: crypto.randomUUID(),
+ draftKey: local.key,
+ accountId: owner.accountId,
+ generation: local.generation,
+ revision: local.revision,
+ operation,
+ };
+ await localDraftStore.update(owner, local.key, (current) =>
+ current.generation !== local.generation ||
+ (operation === 'save' &&
+ (current.revision !== local.revision ||
+ draftSyncPaused(current) ||
+ current.status === 'deleting'))
+ ? current
+ : {
+ ...current,
+ latestAttemptId: attempt.id,
+ queuedAttemptId: undefined,
+ status: operation === 'delete' ? 'deleting' : 'dirty',
+ }
+ );
+ return attempt;
+}
+
+/** Admission is separate from intent: two stores cannot enqueue atomically. */
+export async function markDraftAttemptQueued(
+ attempt: DraftAttempt
+): Promise<void> {
+ const owner = await session();
+ if (owner.accountId !== attempt.accountId) return;
+ await localDraftStore.update(owner, attempt.draftKey, (draft) =>
+ draft.generation !== attempt.generation ||
+ draft.latestAttemptId !== attempt.id ||
+ draftSyncPaused(draft) ||
+ draft.status === 'synced'
+ ? draft
+ : {
+ ...draft,
+ queuedAttemptId: attempt.id,
+ status:
+ attempt.operation === 'delete'
+ ? 'deleting'
+ : draft.revision === attempt.revision
+ ? 'queued'
+ : draft.status,
+ }
+ );
+}
+
+function attemptOf(
+ mutation: Pick<ClaimedMutation, 'clientMetadata'>
+): DraftAttempt | undefined {
+ const value = mutation.clientMetadata;
+ if (
+ !value ||
+ value.kind !== 'email-draft' ||
+ typeof value.id !== 'string' ||
+ typeof value.draftKey !== 'string' ||
+ typeof value.accountId !== 'string' ||
+ typeof value.generation !== 'string' ||
+ typeof value.revision !== 'number' ||
+ (value.operation !== 'save' && value.operation !== 'delete')
+ )
+ return;
+ return value as DraftAttempt;
+}
+
+function object(value: unknown): Record<string, unknown> {
+ return value && typeof value === 'object'
+ ? (value as Record<string, unknown>)
+ : {};
+}
+function objects(value: unknown): Record<string, unknown>[] {
+ return Array.isArray(value) ? value.map(object) : [];
+}
+function text(value: unknown): string | undefined {
+ return typeof value === 'string' ? value : undefined;
+}
+
+/** Replay bookkeeping runs even when no composer is mounted. */
+export function localDraftQueueLifecycle(
+ host: CacheHost
+): Pick<
+ NormalizedCacheExchangeOptions,
+ 'prepareMutationQueue' | 'beforeMutationAttempt' | 'onMutationAttemptResult'
+> {
+ let initialized: Promise<void> | undefined;
+ const legacy = new Map<string, DraftAttempt>();
+ const migrated = new Map<string, number>();
+ async function preserveLegacy(
+ mutation: MutationInspection
+ ): Promise<DraftAttempt | undefined> {
+ if (
+ mutation.operationName !== 'SaveEmailDraft' &&
+ mutation.operationName !== 'DeleteEmailDraft'
+ )
+ return;
+ const known = legacy.get(mutation.transactionId);
+ if (known) return known;
+ const owner = await session();
+ const storageGeneration = await host.currentStorageGeneration();
+ const saved = (await localDraftStore.attempts(owner)).find(
+ (entry) =>
+ entry.transactionId === mutation.transactionId &&
+ entry.storageGeneration === storageGeneration
+ );
+ if (saved) {
+ const previous = await localDraftStore.read(owner, saved.draftKey);
+ const previousId = text(object(mutation.variables.input).draftId);
+ if (previous && previousId && previous.revision === saved.revision)
+ migrated.set(previousId, previous.revision);
+ legacy.set(mutation.transactionId, saved);
+ return saved;
+ }
+ const input = object(mutation.variables.input);
+ const id = text(input.draftId);
+ if (!id) throw new Error('Queued email draft has no recoverable identity');
+ let draft = await localDraftStore.read(owner, id);
+ let revision = 0;
+ if (
+ mutation.operationName === 'SaveEmailDraft' &&
+ (!draft || migrated.get(id) === draft.revision)
+ ) {
+ const optimistic = object(object(mutation.optimisticData).saveEmailDraft);
+ const message = object(optimistic.draft);
+ const attachments: LocalDraftAttachment[] = [
+ ...objects(message.attachmentsDraft).map(
+ (attachment): LocalDraftAttachment => ({
+ type: 'remote',
+ attachmentId: String(attachment.id),
+ fileName: String(attachment.fileName ?? ''),
+ contentType: String(attachment.contentType ?? ''),
+ fileSize: Number(attachment.size ?? 0),
+ url: String(attachment.s3Key ?? ''),
+ })
+ ),
+ ...objects(message.attachmentsForwarded).map(
+ (attachment): LocalDraftAttachment => ({
+ type: 'forwarded',
+ attachmentId: String(attachment.attachmentId),
+ fileName: String(attachment.filename ?? ''),
+ mimeType: String(attachment.mimeType ?? ''),
+ fileSize: Number(attachment.sizeBytes ?? 0),
+ })
+ ),
+ ];
+ const contacts = (value: unknown) =>
+ objects(value).map((entry) => ({
+ email: String(entry.email ?? ''),
+ name: text(entry.name),
+ photo_url: text(entry.photoUrl),
+ }));
+ draft = await localDraftStore.save(owner, {
+ expectedRevision: draft?.revision ?? 0,
+ key: draft?.key ?? id,
+ accountId: owner.accountId,
+ generation: draft?.generation ?? crypto.randomUUID(),
+ draftId: draft?.draftId ?? id,
+ threadId: text(input.threadDbId),
+ inboxId: text(input.linkId) ?? text(message.linkId),
+ senderEmail: text(object(message.from).email),
+ content: {
+ subject: String(input.subject ?? ''),
+ body_html: text(input.bodyHtml),
+ body_text: text(input.bodyText),
+ body_macro: text(input.bodyMacro),
+ replying_to_id: text(input.replyingToId),
+ provider_id: text(input.providerId),
+ provider_thread_id: text(input.providerThreadId),
+ to: contacts(input.to),
+ cc: contacts(input.cc),
+ bcc: contacts(input.bcc),
+ },
+ attachments,
+ status: 'queued',
+ });
+ migrated.set(id, draft.revision);
+ revision = draft.revision;
+ }
+ if (!draft) return;
+ const attempt: DraftAttempt = {
+ kind: 'email-draft',
+ id: crypto.randomUUID(),
+ draftKey: draft.key,
+ accountId: owner.accountId,
+ generation: draft.generation,
+ revision,
+ operation:
+ mutation.operationName === 'DeleteEmailDraft' ? 'delete' : 'save',
+ };
+ // The mapping is only for queue records written by an older app version.
+ await localDraftStore.recordAttempt(owner, {
+ ...attempt,
+ transactionId: mutation.transactionId,
+ storageGeneration,
+ });
+ if (revision || !draft.latestAttemptId)
+ await localDraftStore.update(owner, draft.key, (current) =>
+ current.revision !== draft.revision
+ ? current
+ : {
+ ...current,
+ latestAttemptId: attempt.id,
+ queuedAttemptId: attempt.id,
+ status: attempt.operation === 'delete' ? 'deleting' : 'queued',
+ }
+ );
+ legacy.set(mutation.transactionId, attempt);
+ return attempt;
+ }
+ async function prepare() {
+ const owner = await session();
+ if (!host.inspectMutations)
+ throw new Error('Draft recovery requires an updated cache runtime');
+ const before = await localDraftStore.list(owner);
+ const queue = await host.inspectMutations();
+ const storageGeneration = await host.currentStorageGeneration();
+ for (const mutation of queue)
+ if (!attemptOf(mutation)) await preserveLegacy(mutation);
+ const active = new Set(
+ queue.map(
+ (mutation) =>
+ (attemptOf(mutation) ?? legacy.get(mutation.transactionId))?.draftKey
+ )
+ );
+ for (const draft of before) {
+ // Dirty copies can belong to another tab's live debounce. Only reconcile
+ // an unchanged intent that was actually marked as enqueued/deleting.
+ if (
+ active.has(draft.key) ||
+ draft.queuedAttemptId !== draft.latestAttemptId ||
+ !draft.queuedAttemptId ||
+ (draft.status !== 'queued' && draft.status !== 'deleting')
+ )
+ continue;
+ await localDraftStore.update(owner, draft.key, (current) =>
+ current.generation === draft.generation &&
+ current.revision === draft.revision &&
+ current.latestAttemptId === draft.latestAttemptId &&
+ current.status === draft.status
+ ? {
+ ...current,
+ status:
+ current.status === 'deleting' ? 'delete-failed' : 'unconfirmed',
+ }
+ : current
+ );
+ }
+ const transactions = new Set(
+ queue.map((mutation) => mutation.transactionId)
+ );
+ for (const attempt of await localDraftStore.attempts(owner)) {
+ if (
+ attempt.storageGeneration !== storageGeneration ||
+ !transactions.has(attempt.transactionId)
+ )
+ await localDraftStore.removeAttempt(
+ owner,
+ attempt.storageGeneration,
+ attempt.transactionId
+ );
+ }
+ }
+ async function resolveAttempt(mutation: ClaimedMutation) {
+ const current = attemptOf(mutation) ?? legacy.get(mutation.transactionId);
+ if (
+ current ||
+ (mutation.operationName !== 'SaveEmailDraft' &&
+ mutation.operationName !== 'DeleteEmailDraft')
+ )
+ return current;
+ if (!host.inspectMutations)
+ throw new Error('Cannot preserve queued email draft');
+ const queued = (await host.inspectMutations()).find(
+ (entry) => entry.transactionId === mutation.transactionId
+ );
+ if (!queued)
+ throw new Error('Queued email draft disappeared before recovery');
+ return await preserveLegacy(queued);
+ }
+ return {
+ async prepareMutationQueue() {
+ try {
+ initialized ??= prepare();
+ await initialized;
+ } catch (error) {
+ initialized = undefined;
+ throw error;
+ }
+ },
+ async beforeMutationAttempt(mutation) {
+ const attempt = await resolveAttempt(mutation);
+ if (!attempt) return true;
+ const owner = await session();
+ if (owner.accountId !== attempt.accountId) return false;
+ const local = await localDraftStore.read(owner, attempt.draftKey);
+ if (!local || local.generation !== attempt.generation) return false;
+ await markDraftAttemptQueued(attempt);
+ return attempt.operation === 'delete'
+ ? local.latestAttemptId === attempt.id && local.status === 'deleting'
+ : !draftSyncPaused(local) &&
+ local.status !== 'deleting' &&
+ attempt.revision >= local.acknowledgedRevision;
+ },
+ async onMutationAttemptResult(mutation, result, retry) {
+ if (
+ result.error?.graphQLErrors.some(
+ (error) => error.extensions.code === 'LOCAL_RECOVERY_FAILED'
+ )
+ )
+ initialized = undefined;
+ const attempt = attemptOf(mutation) ?? legacy.get(mutation.transactionId);
+ if (!attempt || retry) return;
+ await settleDraftAttempt(attempt, result, mutation.superseded);
+ },
+ };
+}
+
+async function settleDraftAttempt(
+ attempt: DraftAttempt,
+ result: OperationResult,
+ superseded: boolean
+) {
+ const owner = await session();
+ if (owner.accountId !== attempt.accountId) return;
+ const code = result.error?.graphQLErrors[0]?.extensions.code;
+ const failed = !!result.error || result.data == null;
+ const payload = result.data?.saveEmailDraft;
+ await localDraftStore.update(owner, attempt.draftKey, (draft) => {
+ if (draft.generation !== attempt.generation) return draft;
+ if (code === 'DRAFT_ALREADY_SENT') return undefined;
+ const latest = draft.latestAttemptId === attempt.id;
+ if (attempt.operation === 'delete') {
+ if (!latest) return draft;
+ return failed
+ ? {
+ ...draft,
+ status: 'delete-failed',
+ errorCode: typeof code === 'string' ? code : 'INTERNAL',
+ }
+ : undefined;
+ }
+ if (failed)
+ return superseded || !latest
+ ? draft
+ : {
+ ...draft,
+ status: 'failed',
+ errorCode: typeof code === 'string' ? code : 'INTERNAL',
+ };
+ const acknowledgedRevision = Math.max(
+ draft.acknowledgedRevision,
+ attempt.revision
+ );
+ return {
+ ...draft,
+ acknowledgedRevision,
+ serverDraftId: payload?.draftId ?? draft.serverDraftId,
+ serverThreadId: payload?.thread?.id ?? draft.serverThreadId,
+ status:
+ latest && !draftSyncPaused(draft) && draft.status !== 'deleting'
+ ? draft.revision !== attempt.revision ||
+ draft.attachments.some(
+ (attachment) =>
+ attachment.type === 'local' && !attachment.uploaded
+ )
+ ? 'dirty'
+ : 'synced'
+ : draft.status,
+ };
+ });
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.test.ts
index ddc77d6761..3327d8826b 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.test.ts
@@ -33,7 +33,7 @@ describe('GraphQL mutation retries', () => {
).toBe(false);
});
- it('honors explicit GraphQL retry metadata on an HTTP error', () => {
+ it('ignores legacy GraphQL retry metadata on an HTTP error', () => {
expect(
shouldRetryGraphqlMutation(
new CombinedError({
@@ -43,7 +43,7 @@ describe('GraphQL mutation retries', () => {
response: new Response(null, { status: 400 }),
})
)
- ).toBe(true);
+ ).toBe(false);
});
it('keeps transport failures retryable', () => {
@@ -55,18 +55,34 @@ describe('GraphQL mutation retries', () => {
});
it.each(['INVALID', 'UNAUTHORIZED', 'DRAFT_ALREADY_SENT', 'INTERNAL'])(
- 'does not retry %s without explicit server permission',
+ 'does not retry %s even with legacy server permission',
(code) => {
expect(
shouldRetryGraphqlMutation(
new CombinedError({
- graphQLErrors: [{ message: 'failed', extensions: { code } }],
+ graphQLErrors: [
+ { message: 'failed', extensions: { code, retryable: true } },
+ ],
})
)
).toBe(false);
}
);
+ it('does not let a transport error override an application rejection', () => {
+ expect(
+ shouldRetryGraphqlMutation(
+ new CombinedError({
+ graphQLErrors: [
+ { message: 'failed', extensions: { retryable: true } },
+ ],
+ networkError: new Error('connection lost'),
+ response: new Response(null, { status: 503 }),
+ })
+ )
+ ).toBe(false);
+ });
+
it('does not retry a response that also contains a permanent rejection', () => {
expect(
shouldRetryGraphqlMutation(
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.ts b/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.ts
index 6f22a4da17..89b06a7b20 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.ts
@@ -1,12 +1,10 @@
import { isTransientRequestError } from '@core/util/request-error';
import type { CombinedError } from '@urql/core';
-/** Keep uncertain writes queued; application errors require explicit server opt-in. */
+/** Retry transport failures; application errors always release the queue head. */
export function shouldRetryGraphqlMutation(error: CombinedError): boolean {
if (error.graphQLErrors.length > 0) {
- return error.graphQLErrors.every(
- (error) => error.extensions.retryable === true
- );
+ return false;
}
return isTransientRequestError(error);
}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
index 3b83d8556b..100da33df3 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
@@ -263,6 +263,10 @@ vi.mock('@core/util/reloadForNewerBuild', () => ({
reloadForNewerBuild: mocks.reloadForNewerBuild,
}));
vi.mock('@core/util/platform', () => ({ isTauri: () => mocks.tauri }));
+// Recovery lifecycle is covered with its real store in local-drafts.test.ts.
+vi.mock('@queries/email/local-drafts', () => ({
+ localDraftQueueLifecycle: () => ({}),
+}));
vi.mock('@core/util/platformFetch', () => ({
platformFetch: mocks.platformFetch,
}));
@@ -916,6 +920,59 @@ describe('GraphQL Soup browser cache session gate', () => {
readers.dispose();
});
+ it('requests a native update and uses the existing fallback when draft recovery commands are unavailable', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ mocks.tauri = true;
+ const soup = await import('./graphql-soup');
+ const { NativeCacheUpgradeRequiredError } = await import(
+ '@graphql-cache/host/tauri-host'
+ );
+ const cached = soup.getGraphqlSoupClient();
+ mocks.failInitialization(new NativeCacheUpgradeRequiredError());
+ expect(mocks.toastFailure).toHaveBeenCalledWith(
+ 'Macro update required',
+ expect.objectContaining({
+ subtext: expect.stringContaining('queued drafts are preserved'),
+ })
+ );
+ expect(soup.graphqlCacheEnabled()).toBe(false);
+ expect(soup.getGraphqlSoupClient()).not.toBe(cached);
+ expect(mocks.host.dispose).toHaveBeenCalledOnce();
+ expect(() => soup.assertEmailDraftQueueAvailable()).toThrow(
+ 'queued changes are preserved'
+ );
+ });
+
+ it.each([
+ ['SaveEmailDraft', 'saveEmailDraft'],
+ ['DeleteEmailDraft', 'deleteEmailDraft'],
+ ])(
+ 'prevents %s from overtaking preserved mutations through fallback transport',
+ async (name, field) => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const soup = await import('./graphql-soup');
+ soup.getGraphqlSoupClient();
+ // Initialization may fail after callers have already captured a client.
+ mocks.failInitialization();
+ await expect(
+ soup.dssGraphqlFetch('https://dss.test/graphql', {
+ method: 'POST',
+ body: JSON.stringify({
+ query: `mutation ${name} { ${field}(input: { draftId: "draft" }) { __typename } }`,
+ }),
+ })
+ ).rejects.toThrow('queued changes are preserved');
+ expect(mocks.platformFetch).not.toHaveBeenCalled();
+
+ mocks.platformFetch.mockResolvedValueOnce(new Response('{}'));
+ await soup.dssGraphqlFetch('https://dss.test/graphql', {
+ method: 'POST',
+ body: JSON.stringify({ query: 'query Read { user { id } }' }),
+ });
+ expect(mocks.platformFetch).toHaveBeenCalledOnce();
+ }
+ );
+
it('falls back quietly while another context holds the database', async () => {
const info = vi.spyOn(console, 'info').mockImplementation(() => {});
const soup = await import('./graphql-soup');
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
index a9e866b9ef..02faf076cf 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
@@ -15,6 +15,7 @@ import {
} from '@graphql-cache/exchange/normalized-cache-exchange';
import { CacheNavigationError } from '@graphql-cache/host/navigation-error';
import { createRetirableCacheHost } from '@graphql-cache/host/retirable-host';
+import { NativeCacheUpgradeRequiredError } from '@graphql-cache/host/tauri-host';
import type { CacheHost } from '@graphql-cache/host/types';
import {
createTauriCacheHost,
@@ -27,6 +28,7 @@ import { getBrowserTursoCacheRolloutDecision } from '@graphql-cache/rollout';
import { getOrCreateCacheScope } from '@graphql-cache/scope';
import { Telemetry } from '@macro-inc/observability';
import { notificationStateFromGraphql } from '@notifications/notification-state';
+import { localDraftQueueLifecycle } from '@queries/email/local-drafts';
import { getMacroApiToken } from '@service-auth/fetch';
import type { ApiUserNotification } from '@service-notification/generated/schemas/apiUserNotification';
import type { ChannelType } from '@service-notification/generated/schemas/channelType';
@@ -48,7 +50,13 @@ import {
type RequestPolicy,
subscriptionExchange,
} from '@urql/core';
-import { type DocumentNode, parse, print, visit } from 'graphql';
+import {
+ type DocumentNode,
+ getOperationAST,
+ parse,
+ print,
+ visit,
+} from 'graphql';
import {
createClient as createGraphqlWsClient,
type Client as GraphqlWsClient,
@@ -245,6 +253,31 @@ export async function dssGraphqlFetch(
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> {
+ // Even an in-flight cached client can fall back after queue initialization
+ // fails. Check at transport time so it cannot overtake preserved mutations.
+ if (graphqlDraftQueueBlocked() && typeof init?.body === 'string') {
+ const payload = JSON.parse(init.body) as {
+ query?: string;
+ operationName?: string;
+ };
+ if (typeof payload.query === 'string') {
+ const operation = getOperationAST(
+ parse(payload.query),
+ payload.operationName
+ );
+ if (
+ operation?.operation === 'mutation' &&
+ operation.selectionSet.selections.some(
+ (selection) =>
+ selection.kind === 'Field' &&
+ ['saveEmailDraft', 'deleteEmailDraft'].includes(
+ selection.name.value
+ )
+ )
+ )
+ assertEmailDraftQueueAvailable();
+ }
+ }
return Telemetry.span('graphql.transport', async (span) => {
const started = performance.now();
try {
@@ -415,6 +448,23 @@ let cachedCacheHost: CacheHost | undefined;
let cachedCacheCleanup: (() => void) | undefined;
let browserCacheClientActivated = false;
+/** An unavailable queue may still hold older writes; never bypass its ordering. */
+export function graphqlDraftQueueBlocked(): boolean {
+ cacheAvailability();
+ return (
+ cacheInitializationFailed ||
+ !!(cachedCacheHost && (cachedCacheHost.disabled || !graphqlCacheEnabled()))
+ );
+}
+
+export function assertEmailDraftQueueAvailable(): void {
+ if (graphqlDraftQueueBlocked()) {
+ throw new Error(
+ 'Draft sync is unavailable while queued changes are preserved. Reload or update Macro to resume the queue before saving or discarding.'
+ );
+ }
+}
+
function fallbackAfterInitializationFailure(): void {
const cleanup = cachedCacheCleanup;
cachedCacheCleanup = undefined;
@@ -444,7 +494,8 @@ export function getGraphqlCacheHost(): CacheHost | undefined {
* needed (or wanted) here: user↔cache consistency is enforced inside the
* engine by the identity witness on `QueryRoot.user.id` (a response for a
* different user wipes and rebinds the cache). See @graphql-cache/scope.
- * Any failure falls back to the plain fetch client for the session.
+ * Failures fall back to uncached reads. Draft mutations remain blocked until
+ * a reload or native update can resume the preserved queue.
*/
export function getGraphqlSoupClient(): Client {
const native = isTauri();
@@ -518,9 +569,17 @@ export function getGraphqlSoupClient(): Client {
}
reportCacheError(error, 'initialization');
fallbackAfterInitializationFailure();
- toast.failure('Local cache unavailable', {
- subtext: 'Macro will continue without local caching for this session.',
- });
+ toast.failure(
+ error instanceof NativeCacheUpgradeRequiredError
+ ? 'Macro update required'
+ : 'Local cache unavailable',
+ {
+ subtext:
+ error instanceof NativeCacheUpgradeRequiredError
+ ? error.message
+ : 'Macro will continue without local caching for this session.',
+ }
+ );
console.warn(
'graphql cache async init failed; using uncached client',
error
@@ -549,6 +608,7 @@ export function getGraphqlSoupClient(): Client {
preferGetMethod: false,
exchanges: [
normalizedCacheExchange(host, {
+ ...localDraftQueueLifecycle(host),
deletedRecordKeys: emailCacheDeletionKeys,
onCacheError: (error, operation) => {
// Initialization failure already reports before retiring the host;
@@ -570,8 +630,7 @@ export function getGraphqlSoupClient(): Client {
extractIdentity: (data) =>
(data as Partial<SoupQuery | GroupSoupQuery> | undefined)?.user
?.id,
- // Preserve the optimistic layer on transport failures and on
- // application failures the server explicitly allows us to retry.
+ // Preserve optimistic intent only while transport failures retry.
shouldRetryMutation: shouldRetryGraphqlMutation,
delegateRevalidation: delegateChannelNotificationRefresh,
}),
diff --git a/apps/web/src/lib/service-clients/service-storage/shared-mail-backfill.test.ts b/apps/web/src/lib/service-clients/service-storage/shared-mail-backfill.test.ts
index 3cf6a4c776..68e9ada8d3 100644
--- a/apps/web/src/lib/service-clients/service-storage/shared-mail-backfill.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/shared-mail-backfill.test.ts
@@ -36,17 +36,18 @@ function host() {
const input = { initial: { emailView: 'ALL' as const } };
describe('Shared Mail scope refresh', () => {
- it('continues Shared hydration when an OTA frontend runs on a native binary without entity filtering', async () => {
+ it('continues Shared hydration when native entity filtering is unavailable', async () => {
invokeMock.mockReset();
invokeMock.mockImplementation(async (command: string) => {
if (command === 'graphql_cache_init') return null;
+ if (command === 'graphql_cache_inspect_mutations') return [];
if (command === 'graphql_cache_read')
return { kind: 'hit', data: { user: { id: 'viewer' } } };
if (command === 'graphql_cache_entity_filter')
throw new Error('Command graphql_cache_entity_filter not found');
throw new Error(`Unexpected native command: ${command}`);
});
- const cache = createTauriCacheHost({ scope: 'legacy-ios' });
+ const cache = createTauriCacheHost({ scope: 'no-entity-filter' });
const fetch = vi
.fn()
.mockResolvedValueOnce({
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
index 4af03abbf1..8933f08fe6 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
@@ -303,6 +303,7 @@ pub async fn graphql_cache_enqueue_optimistic_mutation<R: Runtime>(
owner: String,
now_ms: i64,
lease_expires_at_ms: i64,
+ client_metadata: Option<serde_json::Value>,
) -> Result<EnqueueOptimisticMutationResultWire, String> {
let result = engine_handle(&state)?
.enqueue_optimistic_mutation(
@@ -319,6 +320,7 @@ pub async fn graphql_cache_enqueue_optimistic_mutation<R: Runtime>(
owner,
now_ms,
lease_expires_at_ms,
+ client_metadata,
)
.await?;
emit_ops_affected(&app, &result.result.affected_ops, &result.result.changed);
@@ -608,3 +610,11 @@ pub async fn graphql_cache_clear<R: Runtime>(
emit_cache_changed(&app, &revision, true);
Ok(revision)
}
+
+/// Reads durable queue entries without claiming or modifying them.
+#[tauri::command]
+pub async fn graphql_cache_inspect_mutations(
+ state: State<'_, CacheState>,
+) -> Result<Vec<cache_core::queue::MutationInspection>, String> {
+ engine_handle(&state)?.inspect_mutations().await
+}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
index 2b80e076cb..5b7f1471c4 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
@@ -185,6 +185,8 @@ pub enum InitialMutationClaimWire {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClaimedMutationWire {
+ /// Opaque client correlation restored from the durable source.
+ pub client_metadata: Option<serde_json::Value>,
/// Durable mutation id.
pub transaction_id: String,
/// Caller coalescing UUID.
@@ -293,8 +295,13 @@ impl TryFrom<ClaimedMutation> for ClaimedMutationWire {
fn try_from(claimed: ClaimedMutation) -> Result<Self, Self::Error> {
let requires_confirmation = claimed.queued.requires_confirmation();
+ let client_metadata = cache_core::queue::decode_optimistic_source(
+ &claimed.queued.optimistic.optimistic_data_json,
+ )?
+ .client_metadata;
let request = claimed.queued.mutation.request;
Ok(Self {
+ client_metadata,
transaction_id: claimed.queued.id.to_string(),
uuid: claimed.queued.uuid.to_string(),
superseded: claimed.queued.superseded,
@@ -691,6 +698,7 @@ impl EngineHandle {
lease_owner: String,
now_ms: i64,
lease_expires_at_ms: i64,
+ client_metadata: Option<serde_json::Value>,
) -> Result<EnqueueOptimisticMutationResultWire, String> {
let mut state = self.inner.lock().await;
let EngineState { engine, ops, .. } = &mut *state;
@@ -708,6 +716,7 @@ impl EngineHandle {
.enqueue_optimistic_mutation_with_projections(
origin,
BeginOptimisticWrite {
+ client_metadata: client_metadata.as_ref(),
uuid: &uuid,
query: &query,
operation_name: operation_name.as_deref(),
@@ -744,6 +753,18 @@ impl EngineHandle {
})
}
+ /// Reads queued operations without acquiring their leases.
+ pub async fn inspect_mutations(
+ &self,
+ ) -> Result<Vec<cache_core::queue::MutationInspection>, String> {
+ let state = self.inner.lock().await;
+ state
+ .engine
+ .inspect_mutations()
+ .await
+ .map_err(|error| error.to_string())
+ }
+
/// Claims the strict mutation queue head when it is runnable.
pub async fn claim_next_mutation(
&self,
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
index 5f434ca0a6..cbc149492a 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
@@ -566,6 +566,7 @@ fn optimistic_layer_commits_durably() {
"runner".to_string(),
10,
1_000,
+ Some(serde_json::json!({"draftRevision": 10})),
))
.unwrap();
assert_eq!(optimistic.result.affected_ops, vec!["client:1".to_string()]);
@@ -583,6 +584,18 @@ fn optimistic_layer_commits_durably() {
assert_eq!(claimed.uuid, "00000000-0000-4000-8000-000000000001");
assert!(!claimed.superseded);
assert!(!claimed.requires_confirmation);
+ assert_eq!(
+ claimed.client_metadata,
+ Some(serde_json::json!({"draftRevision": 10}))
+ );
+ let inspected = block_on(handle.inspect_mutations()).unwrap();
+ assert_eq!(inspected[0].client_metadata, claimed.client_metadata);
+ assert_eq!(inspected[0].transaction_id, claimed.transaction_id);
+ assert!(
+ block_on(handle.claim_next_mutation("another-runner".into(), 20, 100))
+ .unwrap()
+ .is_none()
+ );
// The optimistic view answers reads.
let ReadResultWire::Hit { data } = read(&handle, None) else {
@@ -630,6 +643,7 @@ fn rollback_drops_optimistic_contribution() {
"runner".to_string(),
10,
1_000,
+ None,
))
.unwrap();
let InitialMutationClaimWire::Claimed { mutation: claimed } = optimistic.initial_claim else {
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test/soup.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test/soup.rs
index c17c047e7b..e76aceda2e 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test/soup.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test/soup.rs
@@ -267,6 +267,7 @@ fn enqueue_archive(handle: &EngineHandle, n: u16) -> (String, String) {
"native-runner".into(),
10,
1000,
+ None,
))
.unwrap();
let InitialMutationClaimWire::Claimed { mutation } = result.initial_claim else {
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index 66f449eeff..9a6abed2e9 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -152,6 +152,14 @@ through the bundle updater, set `MIN_NATIVE_BUILD` to the first native build tha
includes that command. Older binaries must receive a native update before this
bundle; they cannot validate a saved hydration cursor against the cache database.
+Durable email-draft recovery additionally requires
+`graphql_cache_inspect_mutations` and queued `client_metadata` support. Set
+`MIN_NATIVE_BUILD` to the first full native build containing both before publishing
+this frontend as an OTA bundle. The frontend probes this command before claiming
+or enqueueing mutations. An older binary uses the existing uncached fallback and
+shows an update-required notice; its existing mutation queue stays intact until
+the user installs the native update.
+
## Automated offline tests (Linux)
See [native E2E](../../tests/native/README.md) for the isolated WebDriver setup,
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index cad88d2b8c..ae6f4806ad 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -273,6 +273,7 @@ pub fn run() {
graphql_cache_plugin::commands::graphql_cache_write,
graphql_cache_plugin::commands::graphql_cache_hydrate,
graphql_cache_plugin::commands::graphql_cache_enqueue_optimistic_mutation,
+ graphql_cache_plugin::commands::graphql_cache_inspect_mutations,
graphql_cache_plugin::commands::graphql_cache_inspect_query_variants,
graphql_cache_plugin::commands::graphql_cache_inspect_query,
graphql_cache_plugin::commands::graphql_cache_claim_next_mutation,
diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rs
index ddd13d5979..0e3c81ba4b 100644
--- a/crates/client/cache-core/src/engine.rs
+++ b/crates/client/cache-core/src/engine.rs
@@ -263,6 +263,8 @@ pub enum RollbackOptimisticWriteResult {
/// Borrowed inputs for atomically beginning one optimistic mutation.
pub struct BeginOptimisticWrite<'a> {
+ /// Opaque durable client correlation, never sent to the server.
+ pub client_metadata: Option<&'a Json>,
/// Local entities whose IDs must be resolved from the committed response.
pub identity_bindings: &'a [IdentityBinding],
/// Caller-supplied RFC UUID used only for safe coalescing.
@@ -1628,6 +1630,7 @@ impl<S: Storage> Engine<S> {
.map_err(|_| EngineError::InvalidMutationUuid(input.uuid.to_owned()))?;
self.ensure_revision_can_advance()?;
let BeginOptimisticWrite {
+ client_metadata,
uuid: _,
query,
operation_name,
@@ -1688,6 +1691,7 @@ impl<S: Storage> Engine<S> {
IdentityState::NotHydrated | IdentityState::Missing => None,
};
let source = OptimisticSource {
+ client_metadata: client_metadata.cloned(),
identity_bindings: identity_bindings.to_vec(),
mutation_data: data.clone(),
link_patches: patches,
@@ -1882,6 +1886,20 @@ impl<S: Storage> Engine<S> {
})
}
+ /// Reads durable queue entries without acquiring or changing their leases.
+ pub async fn inspect_mutations(
+ &self,
+ ) -> Result<Vec<crate::queue::MutationInspection>, EngineError<S::Error>> {
+ self.storage
+ .load_mutation_queue()
+ .await
+ .map_err(EngineError::Storage)?
+ .into_iter()
+ .map(crate::queue::MutationInspection::try_from)
+ .collect::<Result<_, _>>()
+ .map_err(EngineError::InvalidOptimisticProjection)
+ }
+
/// Claims the oldest runnable mutation. A leased or backed-off head
/// blocks every later mutation.
pub async fn claim_next_mutation(
diff --git a/crates/client/cache-core/src/queue.rs b/crates/client/cache-core/src/queue.rs
index 54e55ea348..de9c1339c7 100644
--- a/crates/client/cache-core/src/queue.rs
+++ b/crates/client/cache-core/src/queue.rs
@@ -80,6 +80,10 @@ const OPTIMISTIC_SOURCE_ENVELOPE_PREFIX: &str = "@macro-cache/optimistic-source:
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OptimisticSource {
+ /// Client recovery context, such as the local draft revision being saved.
+ /// Stored with the mutation for replay; never included in server requests.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub client_metadata: Option<Json>,
/// Explicit bindings for resolving locally created entities at settlement.
#[serde(default)]
pub identity_bindings: Vec<IdentityBinding>,
@@ -99,6 +103,8 @@ pub struct OptimisticSource {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct OptimisticSourceEnvelope {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ client_metadata: Option<Json>,
#[serde(default)]
identity_bindings: Vec<IdentityBinding>,
version: u8,
@@ -125,6 +131,7 @@ struct OptimisticSourceEnvelopeV2 {
pub fn encode_optimistic_source(source: &OptimisticSource) -> String {
let envelope = canonical_json(
&serde_json::to_value(OptimisticSourceEnvelope {
+ client_metadata: source.client_metadata.clone(),
identity_bindings: source.identity_bindings.clone(),
version: OPTIMISTIC_SOURCE_VERSION,
mutation_data: source.mutation_data.clone(),
@@ -142,6 +149,7 @@ pub fn encode_optimistic_source(source: &OptimisticSource) -> String {
pub fn decode_optimistic_source(value: &str) -> Result<OptimisticSource, String> {
let Some(envelope) = value.strip_prefix(OPTIMISTIC_SOURCE_ENVELOPE_PREFIX) else {
return Ok(OptimisticSource {
+ client_metadata: None,
identity_bindings: Vec::new(),
mutation_data: serde_json::from_str(value).map_err(|error| error.to_string())?,
link_patches: Vec::new(),
@@ -160,6 +168,7 @@ pub fn decode_optimistic_source(value: &str) -> Result<OptimisticSource, String>
serde_json::from_value(value).map_err(|error| error.to_string())?;
debug_assert_eq!(envelope.version, 2);
Ok(OptimisticSource {
+ client_metadata: None,
identity_bindings: Vec::new(),
mutation_data: envelope.mutation_data,
link_patches: envelope.link_patches,
@@ -171,6 +180,7 @@ pub fn decode_optimistic_source(value: &str) -> Result<OptimisticSource, String>
let envelope: OptimisticSourceEnvelope =
serde_json::from_value(value).map_err(|error| error.to_string())?;
Ok(OptimisticSource {
+ client_metadata: envelope.client_metadata,
identity_bindings: envelope.identity_bindings,
mutation_data: envelope.mutation_data,
link_patches: envelope.link_patches,
@@ -293,6 +303,48 @@ pub struct ClaimedMutation {
pub lease_generation: u64,
}
+/// Read-only durable request snapshot. It contains no authority to settle a lease.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MutationInspection {
+ /// Durable queue position, encoded without losing JavaScript integer precision.
+ pub transaction_id: String,
+ /// Caller-provided coalescing key.
+ pub uuid: String,
+ /// Whether a later request supersedes this snapshot.
+ pub superseded: bool,
+ /// GraphQL document used for replay.
+ pub query: String,
+ /// Selected operation name.
+ pub operation_name: Option<String>,
+ /// Request variables, excluding transport credentials.
+ pub variables: Json,
+ /// Opaque client correlation; never sent to the GraphQL server.
+ pub client_metadata: Option<Json>,
+ /// Original optimistic response for migrating durable local intent.
+ pub optimistic_data: Json,
+}
+
+impl TryFrom<QueuedMutation> for MutationInspection {
+ type Error = String;
+
+ fn try_from(queued: QueuedMutation) -> Result<Self, Self::Error> {
+ let source = decode_optimistic_source(&queued.optimistic.optimistic_data_json)?;
+ let request = queued.mutation.request;
+ Ok(Self {
+ transaction_id: queued.id.to_string(),
+ uuid: queued.uuid.to_string(),
+ superseded: queued.superseded,
+ query: request.query,
+ operation_name: request.operation_name,
+ variables: serde_json::from_str(&request.variables_json)
+ .map_err(|error| error.to_string())?,
+ client_metadata: source.client_metadata,
+ optimistic_data: source.mutation_data,
+ })
+ }
+}
+
/// Parameters for claiming the strict queue head.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MutationClaimRequest {
diff --git a/crates/client/cache-core/tests/email_archive_optimistic.rs b/crates/client/cache-core/tests/email_archive_optimistic.rs
index d31329763a..a8a0e623a2 100644
--- a/crates/client/cache-core/tests/email_archive_optimistic.rs
+++ b/crates/client/cache-core/tests/email_archive_optimistic.rs
@@ -52,6 +52,7 @@ async fn enqueue(
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
identity_bindings: &[],
uuid,
query: MUTATION,
diff --git a/crates/client/cache-core/tests/email_draft_optimistic.rs b/crates/client/cache-core/tests/email_draft_optimistic.rs
index f52fc23039..0f99bfe937 100644
--- a/crates/client/cache-core/tests/email_draft_optimistic.rs
+++ b/crates/client/cache-core/tests/email_draft_optimistic.rs
@@ -344,6 +344,7 @@ fn queued_draft_save_is_visible_in_the_thread_page_read() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "11111111-1111-4111-8111-111111111101",
query: MUTATION,
operation_name: Some("SaveEmailDraft"),
@@ -412,6 +413,7 @@ fn queued_draft_delete_removes_the_draft_from_the_thread_page_read() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "11111111-1111-4111-8111-111111111102",
query: MUTATION,
operation_name: Some("SaveEmailDraft"),
@@ -433,6 +435,7 @@ fn queued_draft_delete_removes_the_draft_from_the_thread_page_read() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "11111111-1111-4111-8111-111111111103",
query: DELETE_MUTATION,
operation_name: Some("DeleteEmailDraft"),
@@ -537,6 +540,7 @@ fn identity_binding_keeps_newer_edits_readable_across_commit_and_restart() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "11111111-1111-4111-8111-111111111104",
query: MUTATION,
operation_name: Some("SaveEmailDraft"),
@@ -555,6 +559,7 @@ fn identity_binding_keeps_newer_edits_readable_across_commit_and_restart() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "11111111-1111-4111-8111-111111111104",
query: MUTATION,
operation_name: Some("SaveEmailDraft"),
@@ -652,6 +657,7 @@ fn committed_draft_save_with_the_same_id_keeps_the_draft_visible() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "11111111-1111-4111-8111-111111111104",
query: MUTATION,
operation_name: Some("SaveEmailDraft"),
@@ -731,6 +737,7 @@ fn committed_alias_id_response_skips_the_patch_and_stays_readable() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "11111111-1111-4111-8111-111111111105",
query: MUTATION,
operation_name: Some("SaveEmailDraft"),
diff --git a/crates/client/cache-core/tests/grouped_optimistic.rs b/crates/client/cache-core/tests/grouped_optimistic.rs
index 3591e6fab9..cab9327f1f 100644
--- a/crates/client/cache-core/tests/grouped_optimistic.rs
+++ b/crates/client/cache-core/tests/grouped_optimistic.rs
@@ -296,6 +296,7 @@ fn cache_only_read_observes_move_and_rollback_restores_it() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000021",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -381,6 +382,7 @@ fn success_reapplies_recipe_and_returns_deduplicated_revalidation() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000022",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -462,6 +464,7 @@ fn missing_destination_is_created_with_the_updated_item() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000023",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -541,6 +544,7 @@ fn missing_destination_rejects_the_whole_patch_set_without_enqueueing() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000024",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
diff --git a/crates/client/cache-core/tests/identity_commit.rs b/crates/client/cache-core/tests/identity_commit.rs
index 9d380e2786..cd8fe38957 100644
--- a/crates/client/cache-core/tests/identity_commit.rs
+++ b/crates/client/cache-core/tests/identity_commit.rs
@@ -21,6 +21,7 @@ async fn enqueue(engine: &mut Engine<InMemoryStorage>, uuid: &str) -> MutationId
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid,
query: MUTATION,
operation_name: None,
@@ -134,6 +135,7 @@ async fn enqueue_aliased(engine: &mut Engine<InMemoryStorage>) -> MutationId {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: UUID,
query: ALIASED_MUTATION,
operation_name: None,
@@ -484,6 +486,7 @@ fn cross_inbox_draft_settlement_preserves_source_thread_and_rebases_queued_edits
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: UUID,
query: SAVE,
operation_name: None,
@@ -623,6 +626,7 @@ fn rollback_after_restart_returns_persisted_revalidations_with_resolved_ids() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: UUID,
query: MUTATION,
operation_name: None,
diff --git a/crates/client/cache-core/tests/mutation_queue.rs b/crates/client/cache-core/tests/mutation_queue.rs
index 401c55dab7..a167531f5d 100644
--- a/crates/client/cache-core/tests/mutation_queue.rs
+++ b/crates/client/cache-core/tests/mutation_queue.rs
@@ -16,6 +16,7 @@ use serde_json::json;
#[test]
fn optimistic_source_supports_versioned_and_legacy_json() {
let source = OptimisticSource {
+ client_metadata: Some(json!({"kind": "email-draft", "revision": 10})),
identity_bindings: Vec::new(),
mutation_data: json!({"rename": {"name": "next"}}),
link_patches: Vec::new(),
@@ -77,6 +78,12 @@ fn optimistic_source_supports_versioned_and_legacy_json() {
json!({"rename": {"name": "legacy"}})
);
assert!(legacy_v2.projection_mutations.is_empty());
+ assert!(legacy_v2.client_metadata.is_none());
+ let without_metadata = encode_optimistic_source(&OptimisticSource {
+ client_metadata: None,
+ ..source
+ });
+ assert!(!without_metadata.contains("clientMetadata"));
assert!(
decode_optimistic_source(
r#"@macro-cache/optimistic-source:{"version":2,"mutationData":{},"projectionMutations":[]}"#,
diff --git a/crates/client/cache-core/tests/optimistic.rs b/crates/client/cache-core/tests/optimistic.rs
index 3fe5f0e4f2..cf992456ea 100644
--- a/crates/client/cache-core/tests/optimistic.rs
+++ b/crates/client/cache-core/tests/optimistic.rs
@@ -299,6 +299,7 @@ async fn reconciliation_engine() -> (Engine<ClaimFailingStorage>, MutationId) {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000005",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -378,6 +379,7 @@ async fn begin_value(
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid,
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -410,6 +412,86 @@ async fn durable_value(engine: &Engine<InMemoryStorage>) -> Option<String> {
}
}
+#[test]
+fn mutation_inspection_preserves_metadata_without_claiming_or_changing_leases() {
+ block_on(async {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ let variables = mutation_vars("local edit");
+ let data = mutation_response("Status", "local edit");
+ let metadata = json!({"kind": "email-draft", "revision": 10});
+ let (id, _) = engine
+ .begin_optimistic_write(
+ None,
+ BeginOptimisticWrite {
+ uuid: "00000000-0000-4000-8000-000000000030",
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &variables,
+ data: &data,
+ link_patches: &[],
+ revalidations: &[],
+ identity_bindings: &[],
+ created_at_ms: 1,
+ client_metadata: Some(&metadata),
+ },
+ )
+ .await
+ .unwrap();
+ let before = engine.storage().load_mutation_queue().await.unwrap();
+ let inspected = engine.inspect_mutations().await.unwrap();
+ assert_eq!(inspected.len(), 1);
+ assert_eq!(inspected[0].transaction_id, id.to_string());
+ assert_eq!(inspected[0].client_metadata, Some(metadata.clone()));
+ assert_eq!(inspected[0].optimistic_data, data);
+ assert_eq!(
+ inspected[0].variables,
+ serde_json::to_value(&variables).unwrap()
+ );
+ assert!(
+ !inspected[0]
+ .variables
+ .to_string()
+ .contains("clientMetadata")
+ );
+ assert_eq!(
+ engine.storage().load_mutation_queue().await.unwrap(),
+ before
+ );
+
+ let claimed = engine
+ .claim_next_mutation(MutationClaimRequest {
+ owner: "runner".into(),
+ now_ms: 10,
+ lease_expires_at_ms: 100,
+ })
+ .await
+ .unwrap()
+ .unwrap();
+ let before = engine.storage().load_mutation_queue().await.unwrap();
+ let inspected = engine.inspect_mutations().await.unwrap();
+ assert_eq!(inspected[0].client_metadata, Some(metadata));
+ assert_eq!(
+ engine.storage().load_mutation_queue().await.unwrap(),
+ before
+ );
+ assert_eq!(claimed.queued.mutation.attempt_count, 1);
+ assert!(
+ engine
+ .claim_next_mutation(MutationClaimRequest {
+ owner: "another-runner".into(),
+ now_ms: 20,
+ lease_expires_at_ms: 200,
+ })
+ .await
+ .unwrap()
+ .is_none()
+ );
+ let wire = serde_json::to_value(&inspected[0]).unwrap();
+ assert!(wire.get("leaseGeneration").is_none());
+ assert!(wire.get("leaseOwner").is_none());
+ });
+}
+
#[test]
fn begin_persists_mutation_and_optimistic_layer() {
block_on(async {
@@ -419,6 +501,7 @@ fn begin_persists_mutation_and_optimistic_layer() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000006",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -457,6 +540,7 @@ fn enqueue_claims_new_mutation_when_queue_was_empty() {
.enqueue_optimistic_mutation(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000007",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -492,6 +576,7 @@ fn enqueue_claims_older_strict_head() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000008",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -509,6 +594,7 @@ fn enqueue_claims_older_strict_head() {
.enqueue_optimistic_mutation(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000009",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -545,6 +631,7 @@ fn enqueue_does_not_skip_a_leased_or_deferred_head() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000010",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -570,6 +657,7 @@ fn enqueue_does_not_skip_a_leased_or_deferred_head() {
.enqueue_optimistic_mutation(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000011",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -629,6 +717,7 @@ fn claim_failure_after_enqueue_preserves_one_durable_visible_mutation() {
.enqueue_optimistic_mutation(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000012",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -740,6 +829,7 @@ fn claimed_success_atomically_commits_real_response() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000013",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -793,6 +883,7 @@ fn retryable_failure_keeps_optimistic_layer_and_blocks_later_mutations() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000014",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -810,6 +901,7 @@ fn retryable_failure_keeps_optimistic_layer_and_blocks_later_mutations() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000015",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -858,6 +950,7 @@ fn permanent_failure_rolls_back_only_the_claimed_head() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000016",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -875,6 +968,7 @@ fn permanent_failure_rolls_back_only_the_claimed_head() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000017",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -912,6 +1006,7 @@ fn stale_claim_cannot_settle_mutation() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000018",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -984,6 +1079,7 @@ fn pending_replacement_restores_fields_omitted_by_the_new_intent() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: X,
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -1011,6 +1107,7 @@ fn pending_replacement_restores_fields_omitted_by_the_new_intent() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: X,
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -1148,6 +1245,7 @@ fn invalid_uuid_is_rejected_before_queue_hydration() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "not-a-uuid",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -1185,6 +1283,7 @@ fn clear_and_identity_reset_drop_durable_queue() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000019",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
diff --git a/crates/client/cache-core/tests/predicate.rs b/crates/client/cache-core/tests/predicate.rs
index 66627f4210..d56dee692b 100644
--- a/crates/client/cache-core/tests/predicate.rs
+++ b/crates/client/cache-core/tests/predicate.rs
@@ -125,6 +125,7 @@ async fn try_begin_with_projection_uuid(
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid,
query: OPTIMISTIC_MUTATION,
operation_name: Some("SetEntityProperty"),
diff --git a/crates/client/cache-core/tests/property_assignment_optimistic.rs b/crates/client/cache-core/tests/property_assignment_optimistic.rs
index b3e7b1ac64..fa79958bc7 100644
--- a/crates/client/cache-core/tests/property_assignment_optimistic.rs
+++ b/crates/client/cache-core/tests/property_assignment_optimistic.rs
@@ -92,6 +92,7 @@ async fn enqueue(engine: &mut Engine<InMemoryStorage>, value: &str, now: i64) ->
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
identity_bindings: &[],
uuid: UUID,
query: MUTATION,
diff --git a/crates/client/cache-core/tests/query_inspection.rs b/crates/client/cache-core/tests/query_inspection.rs
index 9b328cb456..fd934be12b 100644
--- a/crates/client/cache-core/tests/query_inspection.rs
+++ b/crates/client/cache-core/tests/query_inspection.rs
@@ -499,6 +499,7 @@ mutation SetEntityProperty($input: SetEntityPropertyInput!) {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000002",
query: mutation,
operation_name: Some("SetEntityProperty"),
diff --git a/crates/client/cache-core/tests/record_selection.rs b/crates/client/cache-core/tests/record_selection.rs
index fcb9678b48..ac794c3169 100644
--- a/crates/client/cache-core/tests/record_selection.rs
+++ b/crates/client/cache-core/tests/record_selection.rs
@@ -287,6 +287,7 @@ fn merges_optimistic_updates_with_cold_linked_bases() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000003",
query: mutation,
operation_name: Some("SetProperty"),
@@ -348,6 +349,7 @@ fn includes_optimistic_only_records() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000004",
query: mutation,
operation_name: Some("SetProperty"),
diff --git a/crates/client/cache-core/tests/search.rs b/crates/client/cache-core/tests/search.rs
index 693e72c0e8..10415bd0e7 100644
--- a/crates/client/cache-core/tests/search.rs
+++ b/crates/client/cache-core/tests/search.rs
@@ -307,6 +307,7 @@ fn optimistic_records_explicitly_overlay_the_durable_search_catalog() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000020",
query: RENAME,
operation_name: Some("Rename"),
diff --git a/crates/client/cache-core/tests/search_buckets.rs b/crates/client/cache-core/tests/search_buckets.rs
index 878d120e41..404b32fb60 100644
--- a/crates/client/cache-core/tests/search_buckets.rs
+++ b/crates/client/cache-core/tests/search_buckets.rs
@@ -273,6 +273,7 @@ fn optimistic_bucket_moves_overlay_borrowed_catalogs_through_settlement() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000001",
query: mutation,
operation_name: None,
diff --git a/crates/client/cache-core/tests/viewer_fields.rs b/crates/client/cache-core/tests/viewer_fields.rs
index fcbd0c86b5..2500866b68 100644
--- a/crates/client/cache-core/tests/viewer_fields.rs
+++ b/crates/client/cache-core/tests/viewer_fields.rs
@@ -243,6 +243,7 @@ fn query_updates_remain_scoped_while_an_optimistic_layer_is_pending() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000001",
query: "mutation { setEntityProperty { id } }",
operation_name: None,
diff --git a/crates/client/cache-turso/src/storage/test/projection_writes.rs b/crates/client/cache-turso/src/storage/test/projection_writes.rs
index 228ee9a6f3..a89f6f760a 100644
--- a/crates/client/cache-turso/src/storage/test/projection_writes.rs
+++ b/crates/client/cache-turso/src/storage/test/projection_writes.rs
@@ -126,6 +126,7 @@ fn unchanged_authority_still_rebases_durable_optimistic_intent() {
let mut mutation = queued("Pending");
mutation.optimistic.optimistic_data_json =
cache_core::queue::encode_optimistic_source(&cache_core::queue::OptimisticSource {
+ client_metadata: None,
identity_bindings: Vec::new(),
mutation_data: serde_json::json!({}),
link_patches: Vec::new(),
diff --git a/crates/client/cache-turso/tests/draft_identity.rs b/crates/client/cache-turso/tests/draft_identity.rs
index 079a727a9a..c3e3684b25 100644
--- a/crates/client/cache-turso/tests/draft_identity.rs
+++ b/crates/client/cache-turso/tests/draft_identity.rs
@@ -61,6 +61,7 @@ async fn enqueue(
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: UUID,
query: if delete { DELETE } else { SAVE },
operation_name: Some(if delete {
diff --git a/crates/client/cache-turso/tests/engine_turso.rs b/crates/client/cache-turso/tests/engine_turso.rs
index 2e6c0ed19f..8de57572b1 100644
--- a/crates/client/cache-turso/tests/engine_turso.rs
+++ b/crates/client/cache-turso/tests/engine_turso.rs
@@ -203,6 +203,7 @@ fn optimistic_hydration_retry_complete_and_reopen_run_over_turso() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000001008",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -319,6 +320,7 @@ fn stale_local_head_and_storage_settlement_races_report_stale_claims() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000001009",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -336,6 +338,7 @@ fn stale_local_head_and_storage_settlement_races_report_stale_claims() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000001010",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
@@ -420,6 +423,7 @@ fn optimistic_discard_restores_durable_base_over_turso() {
.begin_optimistic_write(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000001011",
query: MUTATION,
operation_name: Some("SetEntityProperty"),
diff --git a/crates/client/cache-turso/tests/predicate.rs b/crates/client/cache-turso/tests/predicate.rs
index ab7a32a744..76a687af26 100644
--- a/crates/client/cache-turso/tests/predicate.rs
+++ b/crates/client/cache-turso/tests/predicate.rs
@@ -112,6 +112,7 @@ async fn begin_optimistic_projection(
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000001000",
query: r#"
mutation SetEntityProperty($input: SetEntityPropertyInput!) {
@@ -470,6 +471,7 @@ fn turso_rehydrates_and_queries_durable_optimistic_projection_layers() {
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000001001",
query: r#"
mutation SetEntityProperty($input: SetEntityPropertyInput!) {
diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rs
index 07e471bad1..078e30bac8 100644
--- a/crates/client/cache-wasm/src/shell.rs
+++ b/crates/client/cache-wasm/src/shell.rs
@@ -236,6 +236,7 @@ enum JsInitialMutationClaim {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct JsClaimedMutation {
+ client_metadata: Option<serde_json::Value>,
transaction_id: String,
uuid: String,
superseded: bool,
@@ -254,8 +255,14 @@ impl TryFrom<ClaimedMutation> for JsClaimedMutation {
fn try_from(claimed: ClaimedMutation) -> Result<Self, Self::Error> {
let requires_confirmation = claimed.queued.requires_confirmation();
+ let client_metadata = cache_core::queue::decode_optimistic_source(
+ &claimed.queued.optimistic.optimistic_data_json,
+ )
+ .map_err(err_js)?
+ .client_metadata;
let request = claimed.queued.mutation.request;
Ok(Self {
+ client_metadata,
transaction_id: claimed.queued.id.to_string(),
uuid: claimed.queued.uuid.to_string(),
superseded: claimed.queued.superseded,
@@ -1666,6 +1673,7 @@ impl CacheEngine {
lease_owner: String,
now_ms: f64,
lease_expires_at_ms: f64,
+ client_metadata: JsValue,
) -> js_sys::Promise {
let state = self.state.clone();
let ops = self.ops.clone();
@@ -1673,6 +1681,8 @@ impl CacheEngine {
let mut state = state.lock().await;
state.ensure_callable()?;
let vars = parse_variables(variables)?;
+ let client_metadata: Option<serde_json::Value> =
+ serde_wasm_bindgen::from_value(client_metadata).map_err(err_js)?;
let data: serde_json::Value = serde_wasm_bindgen::from_value(data).map_err(err_js)?;
let link_patches: Vec<OptimisticLinkPatch> = parse_vec(link_patches)?;
let revalidations: Vec<QueryRevalidation> = parse_vec(revalidations)?;
@@ -1740,6 +1750,7 @@ impl CacheEngine {
.enqueue_optimistic_mutation_with_projections(
origin,
BeginOptimisticWrite {
+ client_metadata: client_metadata.as_ref(),
uuid: &uuid,
query: &query,
operation_name: operation_name.as_deref(),
@@ -1830,6 +1841,18 @@ impl CacheEngine {
})
}
+ /// Inspects durable mutations without claiming them.
+ #[wasm_bindgen(js_name = inspectMutations)]
+ pub fn inspect_mutations(&self) -> js_sys::Promise {
+ let state = self.state.clone();
+ future_to_promise(async move {
+ let mut state = state.lock().await;
+ state.ensure_callable()?;
+ let result = state.engine_mut()?.inspect_mutations().await;
+ to_js(&state.engine_result(result)?)
+ })
+ }
+
/// Claims the oldest runnable queued mutation.
#[wasm_bindgen(js_name = claimNextMutation)]
pub fn claim_next_mutation(
diff --git a/crates/client/cache-wasm/src/shell/test.rs b/crates/client/cache-wasm/src/shell/test.rs
index 233134b25a..82edcd32bd 100644
--- a/crates/client/cache-wasm/src/shell/test.rs
+++ b/crates/client/cache-wasm/src/shell/test.rs
@@ -41,6 +41,10 @@ fn read_response_conversion_preserves_json_and_revision_strings() {
let records = JsRecordSelectionResult {
revision: u64::MAX.to_string(),
records: vec![cache_core::record_selection::SelectedRecord {
+ identity: cache_core::identity::IdentityStatus {
+ mutation_uuid: None,
+ pending: false,
+ },
record_key: EntityKey("Thing:one".into()),
record: data,
}],
@@ -1387,14 +1391,29 @@ async fn optimistic_v2_patch_is_filterable_after_enqueue_reopen_and_rollback() {
js(optimistic_document_data(DOCUMENT_ID)),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
1.0,
"optimistic-filter-runner".into(),
0.0,
100.0,
+ js(serde_json::json!({"draftRevision": 10})),
))
.await,
);
assert_eq!(enqueue["initialClaim"]["kind"], "claimed");
+ assert_eq!(
+ enqueue["initialClaim"]["mutation"]["clientMetadata"],
+ serde_json::json!({"draftRevision": 10})
+ );
+ let inspected: serde_json::Value = from_js(resolved(engine.inspect_mutations()).await);
+ assert_eq!(
+ inspected[0]["clientMetadata"],
+ serde_json::json!({"draftRevision": 10})
+ );
+ assert!(inspected[0].get("leaseGeneration").is_none());
+ let blocked: serde_json::Value =
+ from_js(resolved(engine.claim_next_mutation("another-runner".into(), 20.0, 100.0)).await);
+ assert!(blocked.is_null());
let transaction_id = enqueue["transactionId"].as_str().unwrap().to_owned();
let generation = enqueue["initialClaim"]["mutation"]["leaseGeneration"]
.as_str()
@@ -1515,10 +1534,12 @@ async fn queue_and_optimistic_layers_survive_preserve_reopen_in_id_order() {
})),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
1.0,
"first-owner".into(),
0.0,
50.0,
+ JsValue::UNDEFINED,
))
.await,
);
@@ -1536,10 +1557,12 @@ async fn queue_and_optimistic_layers_survive_preserve_reopen_in_id_order() {
})),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
2.0,
"second-owner".into(),
0.0,
50.0,
+ JsValue::UNDEFINED,
))
.await,
);
@@ -1639,10 +1662,12 @@ async fn optimistic_commit_reports_affected_ops_and_rejects_settled_or_malformed
})),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
123.0,
"runner".into(),
10.0,
1_000.0,
+ JsValue::UNDEFINED,
))
.await,
);
@@ -1737,10 +1762,12 @@ async fn destroy_recovery_wipes_records_and_queue() {
})),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
1.0,
"destroy-owner".into(),
0.0,
100.0,
+ JsValue::UNDEFINED,
))
.await;
resolved(engine.close()).await;
@@ -1953,10 +1980,12 @@ async fn storage_reset_errors_latch_and_block_hot_read_write_and_control_methods
})),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
1.0,
"nested-owner".into(),
0.0,
100.0,
+ JsValue::UNDEFINED,
))
.await;
assert_reset_required(engine.bound_identity()).await;
@@ -2065,10 +2094,12 @@ async fn physical_reset_serializes_recreates_and_preserves_interner_registration
})),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
1.0,
"reset-owner".into(),
0.0,
100.0,
+ JsValue::UNDEFINED,
))
.await;
@@ -2184,10 +2215,12 @@ async fn every_method_rejects_after_consuming_close() {
})),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
1.0,
"closed".into(),
1.0,
2.0,
+ JsValue::UNDEFINED,
))
.await;
assert_closed(engine.inspect_query_variants(
@@ -2534,10 +2567,12 @@ async fn queue_one_mutation(engine: &CacheEngine) {
})),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
1.0,
"stale-owner".into(),
0.0,
100.0,
+ JsValue::UNDEFINED,
))
.await;
}
diff --git a/crates/client/cache-wasm/src/shell/test/mail_projection.rs b/crates/client/cache-wasm/src/shell/test/mail_projection.rs
index 60cc56764e..9b454df95a 100644
--- a/crates/client/cache-wasm/src/shell/test/mail_projection.rs
+++ b/crates/client/cache-wasm/src/shell/test/mail_projection.rs
@@ -26,10 +26,12 @@ fn enqueue(engine: &CacheEngine) -> js_sys::Promise {
js(mutation_data()),
JsValue::UNDEFINED,
JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
1.0,
"mail-owner".into(),
1.0,
100.0,
+ JsValue::UNDEFINED,
)
}
diff --git a/crates/graphql_email/src/mutation.rs b/crates/graphql_email/src/mutation.rs
index efb928b963..395d042649 100644
--- a/crates/graphql_email/src/mutation.rs
+++ b/crates/graphql_email/src/mutation.rs
@@ -415,8 +415,7 @@ fn saved_draft_message(saved: SavedUserDraft) -> Message {
/// Error taxonomy for the draft mutations (save and delete), mirroring the
/// REST `CreateDraftError` mapping with machine-readable `extensions.code`
-/// values the client's offline queue can branch on. Repository failures are
-/// retryable: a write may have committed before loading its response failed.
+/// values the client can use to offer recovery without blocking its mutation queue.
fn draft_mutation_error(error: &EmailErr) -> async_graphql::Error {
let (message, code) = match error {
EmailErr::MessageAlreadySent(_) => {
@@ -434,20 +433,16 @@ fn draft_mutation_error(error: &EmailErr) -> async_graphql::Error {
("email draft body is invalid", "INVALID")
}
EmailErr::Unauthorized => ("not authorized to modify email draft", "UNAUTHORIZED"),
- EmailErr::RepoErr(_) => {
- return retryable_email_error(async_graphql::Error::new("email draft mutation failed"));
- }
_ => ("email draft mutation failed", "INTERNAL"),
};
async_graphql::Error::new(message).extend_with(|_, extensions| extensions.set("code", code))
}
-/// State-setting writes and draft handles are idempotent; an uncertain reply
-/// must not roll back the client after the domain write already committed.
-fn retryable_email_error(error: async_graphql::Error) -> async_graphql::Error {
+/// A failed response may follow a committed write. Preserve its error code so
+/// callers can offer an explicit retry using the original idempotent handle.
+fn internal_email_error(error: async_graphql::Error) -> async_graphql::Error {
error.extend_with(|_, extensions| {
extensions.set("code", "INTERNAL");
- extensions.set("retryable", true);
})
}
@@ -472,7 +467,7 @@ async fn reload_thread<O: EmailThreadMutationOutput>(
) -> async_graphql::Result<O::Thread> {
O::load_email_thread(ctx, user_id, thread_id)
.await
- .map_err(retryable_email_error)?
+ .map_err(internal_email_error)?
.ok_or_else(|| {
// The primary-backed lookup completed, but its All Mail projection
// can omit a trashed thread even after the write committed. Repeating
@@ -627,7 +622,7 @@ where
let draft_id = saved.draft.db_id;
let thread = reload_thread::<O>(ctx, user_id, saved.draft.thread_db_id)
.await
- .map_err(retryable_email_error)?;
+ .map_err(internal_email_error)?;
Ok(SaveEmailDraftPayload {
draft_id,
draft: GraphqlSoupEmailMessage::from_content(EmailContentMessage::from(
@@ -668,7 +663,7 @@ where
let thread = match deleted.thread_id.filter(|_| !deleted.thread_deleted) {
Some(id) => O::load_email_thread(ctx, user_id, id)
.await
- .map_err(retryable_email_error)?,
+ .map_err(internal_email_error)?,
None => None,
};
Ok(DeleteEmailDraftPayload {
diff --git a/crates/graphql_email/src/mutation/test.rs b/crates/graphql_email/src/mutation/test.rs
index 55fe7d5fd9..c38d575ffe 100644
--- a/crates/graphql_email/src/mutation/test.rs
+++ b/crates/graphql_email/src/mutation/test.rs
@@ -631,13 +631,13 @@ async fn save_email_draft_does_not_return_a_message_when_attachment_loading_fail
.as_ref()
.unwrap()
.get("retryable"),
- Some(&async_graphql::Value::Boolean(true))
+ None
);
assert!(response.data.into_json().unwrap().is_null());
}
#[tokio::test]
-async fn save_email_draft_can_retry_when_the_post_save_thread_reload_fails() {
+async fn save_email_draft_reports_internal_error_when_the_post_save_thread_reload_fails() {
let service = Arc::new(CapturingEmailMutationService {
thread_load_fails: true,
..Default::default()
@@ -656,10 +656,7 @@ async fn save_email_draft_can_retry_when_the_post_save_thread_reload_fails() {
extensions.get("code"),
Some(&async_graphql::Value::from("INTERNAL"))
);
- assert_eq!(
- extensions.get("retryable"),
- Some(&async_graphql::Value::Boolean(true))
- );
+ assert_eq!(extensions.get("retryable"), None);
assert!(response.data.into_json().unwrap().is_null());
}
diff --git a/crates/graphql_email/src/mutation/test/archive.rs b/crates/graphql_email/src/mutation/test/archive.rs
index 68280cbd04..85a2c35dc7 100644
--- a/crates/graphql_email/src/mutation/test/archive.rs
+++ b/crates/graphql_email/src/mutation/test/archive.rs
@@ -32,15 +32,12 @@ async fn missing_post_write_thread_does_not_block_the_mutation_queue_with_retrie
extensions.get("code"),
Some(&async_graphql::Value::from("NOT_FOUND"))
);
- assert_ne!(
- extensions.get("retryable"),
- Some(&async_graphql::Value::Boolean(true))
- );
+ assert_eq!(extensions.get("retryable"), None);
}
}
#[tokio::test]
-async fn archive_reply_failure_is_retryable_after_the_write_commits() {
+async fn archive_reply_failure_does_not_request_retries_after_the_write_commits() {
let service = Arc::new(CapturingEmailMutationService {
thread_load_fails: true,
..Default::default()
@@ -57,7 +54,7 @@ async fn archive_reply_failure_is_retryable_after_the_write_commits() {
.as_ref()
.unwrap()
.get("retryable"),
- Some(&async_graphql::Value::Boolean(true))
+ None
);
}
diff --git a/crates/soup_filter_cache_adapter/src/channels/test.rs b/crates/soup_filter_cache_adapter/src/channels/test.rs
index 8d01e7a63e..295dbd3d3f 100644
--- a/crates/soup_filter_cache_adapter/src/channels/test.rs
+++ b/crates/soup_filter_cache_adapter/src/channels/test.rs
@@ -306,6 +306,7 @@ async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-0000-0000-000000002000",
query: PATCH,
operation_name: None,
diff --git a/crates/soup_filter_cache_adapter/src/mail/test.rs b/crates/soup_filter_cache_adapter/src/mail/test.rs
index d624357458..59982f16de 100644
--- a/crates/soup_filter_cache_adapter/src/mail/test.rs
+++ b/crates/soup_filter_cache_adapter/src/mail/test.rs
@@ -309,6 +309,7 @@ async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-0000-0000-000000002000",
query: PARTIAL,
operation_name: None,
diff --git a/crates/soup_filter_cache_adapter/src/mail/test/drafts.rs b/crates/soup_filter_cache_adapter/src/mail/test/drafts.rs
index b68c8d01ea..a75b3b6b8b 100644
--- a/crates/soup_filter_cache_adapter/src/mail/test/drafts.rs
+++ b/crates/soup_filter_cache_adapter/src/mail/test/drafts.rs
@@ -98,6 +98,7 @@ async fn offline_lifecycle<S: PredicateIndexStorage>(storage: S) {
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-4000-8000-000000000081",
query: SAVE,
operation_name: Some("SaveEmailDraft"),
diff --git a/crates/soup_filter_cache_adapter/src/mail/test/optimistic.rs b/crates/soup_filter_cache_adapter/src/mail/test/optimistic.rs
index 3198484303..1ef9df1d24 100644
--- a/crates/soup_filter_cache_adapter/src/mail/test/optimistic.rs
+++ b/crates/soup_filter_cache_adapter/src/mail/test/optimistic.rs
@@ -60,6 +60,7 @@ async fn replacement_removals<S: PredicateIndexStorage>(storage: S) {
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-0000-0000-000000003000",
query: QUERY,
operation_name: None,
@@ -152,6 +153,7 @@ async fn optional_sorts<S: PredicateIndexStorage>(storage: S) {
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-0000-0000-000000003001",
query: QUERY,
operation_name: None,
diff --git a/crates/soup_filter_cache_adapter/src/notifications/test.rs b/crates/soup_filter_cache_adapter/src/notifications/test.rs
index 6a09151688..3359bffa11 100644
--- a/crates/soup_filter_cache_adapter/src/notifications/test.rs
+++ b/crates/soup_filter_cache_adapter/src/notifications/test.rs
@@ -117,6 +117,7 @@ async fn mark_done<S: Storage>(engine: &mut Engine<S>, id: &str, uuid: &str) ->
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid,
query: UPDATE,
operation_name: None,
diff --git a/crates/soup_filter_cache_adapter/src/notifications/test/large.rs b/crates/soup_filter_cache_adapter/src/notifications/test/large.rs
index 5f064c7460..98da820810 100644
--- a/crates/soup_filter_cache_adapter/src/notifications/test/large.rs
+++ b/crates/soup_filter_cache_adapter/src/notifications/test/large.rs
@@ -36,6 +36,7 @@ async fn large_set_lifecycle<S: PredicateIndexStorage>(storage: S) {
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-0000-0000-000000000101",
query: UPDATE,
operation_name: None,
diff --git a/crates/soup_filter_cache_adapter/src/properties/test.rs b/crates/soup_filter_cache_adapter/src/properties/test.rs
index 5e63026749..0a26507f49 100644
--- a/crates/soup_filter_cache_adapter/src/properties/test.rs
+++ b/crates/soup_filter_cache_adapter/src/properties/test.rs
@@ -81,6 +81,7 @@ fn favorites_membership_changes_optimistically_and_rolls_back_without_a_new_quer
.enqueue_optimistic_mutation_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
identity_bindings: &[],
uuid: "00000000-0000-7000-8000-000000000007",
query: FAVORITE,
@@ -319,6 +320,7 @@ fn independent_property_optimism_survives_rollback_and_commits() {
.enqueue_optimistic_mutation_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: &uuid,
query: SET,
operation_name: None,
diff --git a/crates/soup_filter_cache_adapter/src/test/file_type.rs b/crates/soup_filter_cache_adapter/src/test/file_type.rs
index 6d41270e52..9c69b1f3dd 100644
--- a/crates/soup_filter_cache_adapter/src/test/file_type.rs
+++ b/crates/soup_filter_cache_adapter/src/test/file_type.rs
@@ -249,6 +249,7 @@ async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
.begin_optimistic_write_with_projections(
None,
BeginOptimisticWrite {
+ client_metadata: None,
uuid: "00000000-0000-0000-0000-000000000100",
query: RENAME,
operation_name: Some("Rename"),
diff --git a/docs/AGENT_GUIDE/browser-technique.md b/docs/AGENT_GUIDE/browser-technique.md
index 0265309593..e843fd0c3a 100644
--- a/docs/AGENT_GUIDE/browser-technique.md
+++ b/docs/AGENT_GUIDE/browser-technique.md
@@ -48,6 +48,11 @@
`list_network_requests` (resourceTypes xhr/fetch), then `get_network_request` on the
suspicious reqid for headers/body. Pairing the console error with the failing request
localizes the fault in one step.
+- If the app root is empty, include `script` requests: a 502 for a Vite module
+ prevents the entry module from rendering, even when `/app/` returns 200. Check
+ proxy logs for Docker-to-host dial timeouts. The generated Vite proxy limits
+ upstream connections to 16 to avoid exhausting the host listener during module
+ loading; reload after updating and restarting only the affected proxy.
- `net::ERR_NETWORK_CHANGED` spam means the environment's network flapped: verify the stack
with curl from the shell, then `navigate_page` reload.
- Full-screen "Something went terribly wrong" dialogs: `Home` recovers navigation-level
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index f8c40c1ee7..7e2dec8e0c 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -507,8 +507,10 @@ writer. Email mutations and their uncached reply reloads use the primary; ordina
GraphQL/REST lists, direct Soup lookups, and realtime Soup hydration use the replica.
A mutation reply is fresh, but subsequent list refetches are eventually consistent
and can still return replica-stale read/archive state. Test that boundary separately
-from mutation reply correctness. A post-commit reply-load failure is retryable;
-it must not discard the queued intent. Deploy
+from mutation reply correctness. GraphQL application errors, including a failed
+post-commit reply load, release the queued mutation rather than retrying forever.
+Transport failures retain the existing retry policy. Draft recovery preserves local
+content and offers explicit Retry using the original handle. Deploy
the backend schema containing `setEmailThreadArchived` before this client.
Browser WASM and native cache builds must include the regenerated schema metadata;
native offline archive support therefore requires a full app build, not just OTA.
@@ -636,8 +638,15 @@ or the latest message when none is selected. `F` opens a forward and focuses To.
While an editable field is focused, Escape is handled by that field before the
close-reply shortcut.
An edited reply remains a draft when navigating away and returning. Standalone
-compose also flushes pending edits when leaving through app navigation. During
-send or discard, its sender and scheduling controls cannot change the operation.
+compose also flushes pending edits when leaving through app navigation. Switch
+views immediately after typing, before the 500 ms autosave debounce: the old
+thread must close, further navigation must work, and reopening must retain the
+last edit. Repeat with an existing draft and a new reply. During
+mobile Save Draft navigation, a failed local flush is reported and keeps the
+back menu and editor open with their contents intact. After another edit saves
+successfully, Save Draft can leave the composer. Reopen an existing reply after
+clearing its body: the saved empty body must not restore the original quoted HTML.
+During send or discard, its sender and scheduling controls cannot change the operation.
Attachments that can be opened are buttons named by their filename; Tab to one
and press Enter or Space. Removal is a separate button named `Remove <filename>`.
Removing a forwarded file keeps the received original.
@@ -645,6 +654,74 @@ When checking draft autosave, edit the body of a draft with uploaded or forwarde
attachments, wait for the save, and reopen it; the attachments should remain visible.
AI email tool drafts persist body-only edits; changing recipients or the subject
is not required to save the body.
+
+With GraphQL draft queuing enabled, working copies and pending attachment bytes
+are saved on this device independently of the mutation queue. A failed server
+save must leave the draft discoverable in **Drafts** (including grouped views)
+and in its reply thread. **Draft saved** sits immediately left of the desktop
+delete button after editing pauses for 500 ms and the latest local save completes,
+then fades out after two seconds, including offline saves. Resuming typing hides
+it immediately; another pause and saved version restart the timer. Background
+sync updates do not. Failures replace it with persistent **Retry** in the same place; hover for details.
+Clicking Send must not show the badge for its preparatory draft save, including
+when delivery fails. Later edits can show it again after the usual pause.
+Verify the label does not cycle through saving/syncing text on each edit and
+that retry remains accessible beside the actions on mobile. Editing while failed
+continues saving locally without repeatedly submitting the rejected request.
+Repeated local-save failures show one persistent warning per composer; recovery
+or closing that composer dismisses it. A later failure shows a new warning.
+Retry preserves the original draft handle. An already-sent rejection drops the
+local copy rather than recreating the sent message. The REST compose path keeps
+its existing behavior.
+
+Native draft recovery requires a full app update containing queue inspection and
+durable mutation metadata support. An older app receiving an OTA bundle shows
+**Macro update required** and uses the existing uncached fallback. Its old queue
+must remain intact, with no new claims or queued writes, until the native update.
+When the cache becomes unavailable, draft saves and discards must not bypass its
+preserved queue through GraphQL or REST fallback. Local editing stays durable;
+reload or update the app to resume server sync. Verify this after a native
+upgrade-required error and a worker initialization failure; ordinary reads still work.
+
+For recovery verification, reject a draft save with a GraphQL error (including
+legacy `retryable: true` metadata), then perform an unrelated queued action: the
+failed save must release the queue. Reload and reopen the draft; verify subject,
+recipients, body, and pending file contents. Retry and check that exactly one
+server draft exists. If per-mutation recovery preparation fails or times out,
+the mutation must fail and release the queue too, including legacy drafts that
+have not been copied into recovery storage. Existing local working copies remain;
+an unmigrated legacy edit can be lost if the queue held its only durable copy.
+Verify that an unrelated queued action still completes in both cases.
+Repeat with two tabs, a save response arriving after a newer
+edit, an attachment upload completing during another local save, and Discard
+while an attachment snapshot is still being saved. A snapshot based on an older
+local revision must fail without replacing newer content or files, including
+when another tab saves first. Reopen the draft to use the latest version.
+A completed discard must not resurrect on reload. A clean,
+fully synchronized local copy must not hide newer server edits or sent state.
+While online, create a disposable reply, wait for its server identity, discard
+it, then leave and reopen the thread and reload. Its local body and attachment
+bytes must be gone and the server draft must stay deleted. Repeat with a second
+tab holding the same draft under its server ID: a delayed save from that tab must
+not recreate the discarded working copy. Repeat after Undo revives the draft:
+the old tab must not overwrite the restored copy even when revisions match.
+A newly composed reply still saves.
+
+For offline replies, use a received email so recipients come from its contacts.
+Type a reply, leave the thread, and reopen it while still offline; repeat both
+immediately after typing and after waiting for autosave. The reply body and
+recipients must remain, including after reload. Delay local draft discovery while
+the cached thread is available: the reply editor must wait for the recovered
+draft before it can accept edits. When several local replies target the same
+message, reopen the most recently edited draft. This exercises the real form-to-
+storage boundary as well as queued saves; plain hand-built save inputs alone
+do not cover it.
+
+Explicit sign-out warns before removing unsynchronized local drafts and files.
+Cancel must retain them; confirm must clear them and fence in-flight work so the
+next account cannot see them. If local storage cannot be inspected, sign-out must
+still offer a warning and a way to continue. Do not verify this by deleting real
+user drafts; use disposable drafts in an isolated test session.
The three-dot button beneath a body reveals quoted content and a trimmed
signature. Plaintext and Macro Markdown use the existing Markdown renderer;
Macro Markdown messages retain document mentions. Ordinary HTML bodies use an
@@ -653,6 +730,16 @@ open shadow root: Playwright text locators can reach them, but a card's ordinary
Sending a reply from an inbox thread marks that thread done but stays on it;
only the explicit Mark done action opens the next email.
+Sending a message shows it in the open thread immediately, while delivery is
+still pending. It stays visible until the thread refresh confirms it, with no
+duplicate message. Failed delivery removes that message and restores the reply
+draft; a successful Undo Send removes it and reopens the draft. This temporary
+thread display uses the existing REST delivery path.
+Sending must leave the new message's reply composer closed. After delivery,
+focus belongs to the sent message card in the same thread pane, even while
+the thread refresh is still pending. Replying again requires clicking Reply
+or using a reply shortcut.
+
After a successful send, the `Email sent` notice offers `Undo`. Undo restores the
sent envelope and editable content, including when the reply used another inbox;
a slow background refresh must not keep the restored editor disabled. A rejected
@@ -675,25 +762,22 @@ offline: a blocking notice explains and nothing is attached.
For a new standalone email, a failed REST draft save is best-effort: Send can
still proceed without a draft ID when no save was queued and no attachment is
waiting to upload. A server rejection blocks sending even an existing draft.
-An internal draft-save failure, including a failed response read after the save
-commits, stays queued and retries with backoff. It must not permanently disable
-autosave; Send stays blocked until a save is confirmed. Invalid or unauthorized
-writes still stop retrying.
+GraphQL draft saves automatically retry only network failures. GraphQL errors,
+including internal, invalid, and unauthorized errors, fail the mutation and
+release the queue. The local working copy offers explicit Retry; Send stays
+blocked until a save is confirmed.
A successful save response with an invalid cache identity binding still commits
its normalizable server data and reports a cache diagnostic without replaying
the mutation or asking the user to save again. If that response also cannot be
normalized, the attempt stops retrying and reports a permanent cache failure.
-If an offline save is permanently rejected after reconnect, a persistent
-**Draft could not be saved** notice offers **Save as new draft**. The editor keeps
-the latest text and stops autosaving until that action is chosen. Recovery saves
-the current content under a new draft identity; a reply stays in its conversation.
-Previously saved attachments that cannot be copied require reattachment, with a
-separate notice. Verify that further typing alone does not retry the rejected
-write, recovery uses the newest text, and closing or resetting the composer
-removes its recovery notice. Other transient notices must not hide that action.
+If a queued GraphQL save is permanently rejected after reconnect, the draft status
+offers **Retry** using the original draft handle and latest locally saved content.
+Further typing saves locally without retrying the rejected write. Verify that
+pending attachment bytes survive reopening and that a reply stays in its
+conversation.
An already-sent rejection after reconnect follows the same path as an immediate
already-sent response: announce that the email or reply was sent, clear the local
-composer, and cancel pending autosave. It must never offer **Save as new draft**.
+composer, and cancel pending autosave. It must never offer Retry for that draft.
Verify this in standalone and reply composers, including a queued edit awaiting
its debounce and a failure racing the first identity read. A settlement for a
previous or different draft must not clear the current editor.
diff --git a/docs/RUNNING_LOCALLY.md b/docs/RUNNING_LOCALLY.md
index 7848659fba..cd978520e2 100644
--- a/docs/RUNNING_LOCALLY.md
+++ b/docs/RUNNING_LOCALLY.md
@@ -314,11 +314,18 @@ use that same HTTPS origin for attached local stacks.
If your host firewall blocks Docker-to-host traffic, allow the instance's
Docker network to reach the Vite port through `host.docker.internal`.
Startup verifies `/app/` through the HTTPS proxy before printing “ready”;
-a listening Vite port alone is insufficient. A 502 with a proxy log such as
-`dial tcp <host-gateway>:<vite-port>: i/o timeout` indicates this firewall path
-is blocked. Firewall rules must cover the current instance's Docker network
+a listening Vite port alone is insufficient. Persistent 502s with proxy logs such
+as `dial tcp <host-gateway>:<vite-port>: i/o timeout` can indicate this firewall
+path is blocked. Firewall rules must cover the current instance's Docker network
and frontend port, which can differ between instances.
+If `/app/` succeeds but the page stays blank, inspect script requests as well as
+API requests. Intermittent 502s for Vite modules can come from the burst of
+Docker-to-host connections during startup. The generated proxy limits Vite to
+16 upstream connections so module requests queue instead of exhausting the host
+listener. After applying an updated proxy configuration, restart only the
+instance's proxy and reload the page; existing databases and volumes can stay.
+
Trust `infra/local/certs/ca.pem` in the visiting browser once (see the
[certificate README](../infra/local/certs/README.md)), then open that URL.
The visiting machine must resolve the hostname and reach the proxy port over
diff --git a/tooling/xtask/crates/xtask_local/src/local/proxy.rs b/tooling/xtask/crates/xtask_local/src/local/proxy.rs
index ee7a79d792..0045204d77 100644
--- a/tooling/xtask/crates/xtask_local/src/local/proxy.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/proxy.rs
@@ -333,7 +333,14 @@ const FRONTEND_VITE: &str = r#" handle {
# Vite, whose backend proxy would send them straight back here.
@backend_root path BACKEND_PREFIXES
respond @backend_root 404
- reverse_proxy host.docker.internal:{$VITE_PORT}
+ reverse_proxy host.docker.internal:{$VITE_PORT} {
+ # Vite loads many modules concurrently. Bound Docker-to-host
+ # connections so the burst cannot exhaust the host listener and
+ # fail module imports with dial timeouts / 502s.
+ transport http {
+ max_conns_per_host 16
+ }
+ }
}
"#;
diff --git a/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs b/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs
index ffd99d81c0..1df8ce2311 100644
--- a/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs
@@ -193,6 +193,21 @@ fn static_frontend_block_is_opt_in() {
assert!(!headless_dev.contains("handle /mailpit/*"));
}
+/// Only host-run Vite needs protection from concurrent module connection bursts.
+#[test]
+fn vite_connection_limit_is_scoped_to_frontend() {
+ for mode in [Mode::Local, Mode::Dev] {
+ let attached = caddyfile(mode, false);
+ assert_eq!(attached.matches("max_conns_per_host").count(), 1);
+ let (backend_routes, frontend_route) = attached
+ .split_once("reverse_proxy host.docker.internal:{$VITE_PORT} {")
+ .expect("attached frontend must proxy to Vite");
+ assert!(!backend_routes.contains("max_conns_per_host"));
+ assert!(frontend_route.contains("transport http {\n max_conns_per_host 16"));
+ assert!(!caddyfile(mode, true).contains("max_conns_per_host"));
+ }
+}
+
/// Local Caddy speaks HTTPS with a machine certificate and stamps wildcard CORS
/// on every response. Dev still uses TLS (same proxy) but does not overlay
/// CORS, because it fans out to the shared-dev gateway.