Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: gql email save & delete draft mutations (#6494)
Peter Chinman6e5798fb6bdc
diff --git a/.sqlx/query-11e1b4a0bedea73283a010c9b5d7ce31b46818b73a7a479d13e28d1d82bbe7cd.json b/.sqlx/query-11e1b4a0bedea73283a010c9b5d7ce31b46818b73a7a479d13e28d1d82bbe7cd.jsonnew file mode 100644index 0000000000..24a941845d--- /dev/null+++ b/.sqlx/query-11e1b4a0bedea73283a010c9b5d7ce31b46818b73a7a479d13e28d1d82bbe7cd.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE email_messages SET has_attachments = true WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "11e1b4a0bedea73283a010c9b5d7ce31b46818b73a7a479d13e28d1d82bbe7cd"+}diff --git a/.sqlx/query-123dc99a0946a8c4e76ff5e95aebae6f4f2b734dbf953c4bce2f25477a73529a.json b/.sqlx/query-123dc99a0946a8c4e76ff5e95aebae6f4f2b734dbf953c4bce2f25477a73529a.jsonnew file mode 100644index 0000000000..77471e9b5e--- /dev/null+++ b/.sqlx/query-123dc99a0946a8c4e76ff5e95aebae6f4f2b734dbf953c4bce2f25477a73529a.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_thread_client_ids (client_id, link_id, thread_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (link_id, client_id)\n DO UPDATE SET thread_id = EXCLUDED.thread_id, created_at = now()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "123dc99a0946a8c4e76ff5e95aebae6f4f2b734dbf953c4bce2f25477a73529a"+}diff --git a/.sqlx/query-41f204705d52a2d4e526d3b348c0580c92f012508c885feff2bd15dfc6ccf145.json b/.sqlx/query-41f204705d52a2d4e526d3b348c0580c92f012508c885feff2bd15dfc6ccf145.jsonnew file mode 100644index 0000000000..71996fff76--- /dev/null+++ b/.sqlx/query-41f204705d52a2d4e526d3b348c0580c92f012508c885feff2bd15dfc6ccf145.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT created_at, updated_at FROM email_messages WHERE id = $1 AND link_id = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 1,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "41f204705d52a2d4e526d3b348c0580c92f012508c885feff2bd15dfc6ccf145"+}diff --git a/.sqlx/query-800ca32851afd60d31bc14325d2a8e9c76d503668d2917266edaecec7cd1ec35.json b/.sqlx/query-8f8e4a2218c8031181728280f8d881f7c820f8343e424b83c04482964de14e8b.jsonsimilarity index 53%rename from .sqlx/query-800ca32851afd60d31bc14325d2a8e9c76d503668d2917266edaecec7cd1ec35.jsonrename to .sqlx/query-8f8e4a2218c8031181728280f8d881f7c820f8343e424b83c04482964de14e8b.jsonindex 167fa20e8b..50c17fbcbf 100644--- a/.sqlx/query-800ca32851afd60d31bc14325d2a8e9c76d503668d2917266edaecec7cd1ec35.json+++ b/.sqlx/query-8f8e4a2218c8031181728280f8d881f7c820f8343e424b83c04482964de14e8b.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n DELETE FROM email_messages\n WHERE id = $1 AND thread_id = $2 AND is_draft = true AND is_sent = false\n RETURNING link_id\n ",+ "query": "\n DELETE FROM email_messages\n WHERE id = $1\n AND thread_id = $2\n AND link_id = ANY($3)\n AND is_draft = true\n AND is_sent = false\n RETURNING link_id\n ","describe": {"columns": [{@@ -12,12 +12,13 @@"parameters": {"Left": ["Uuid",- "Uuid"+ "Uuid",+ "UuidArray"]},"nullable": [false]},- "hash": "800ca32851afd60d31bc14325d2a8e9c76d503668d2917266edaecec7cd1ec35"+ "hash": "8f8e4a2218c8031181728280f8d881f7c820f8343e424b83c04482964de14e8b"}diff --git a/.sqlx/query-96c931c015873a83c4a930b2eb849f3f2226010d16ca70cc73375d4cbe7fa197.json b/.sqlx/query-96c931c015873a83c4a930b2eb849f3f2226010d16ca70cc73375d4cbe7fa197.jsonnew file mode 100644index 0000000000..8509bb6083--- /dev/null+++ b/.sqlx/query-96c931c015873a83c4a930b2eb849f3f2226010d16ca70cc73375d4cbe7fa197.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_draft_client_ids (client_id, link_id, message_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (link_id, client_id)\n DO UPDATE SET message_id = EXCLUDED.message_id, created_at = now()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "96c931c015873a83c4a930b2eb849f3f2226010d16ca70cc73375d4cbe7fa197"+}diff --git a/.sqlx/query-9ef7301d256f730320328bbefd630e4b80751898cd67f811f9a428965f612c67.json b/.sqlx/query-9ef7301d256f730320328bbefd630e4b80751898cd67f811f9a428965f612c67.jsonnew file mode 100644index 0000000000..59d9d5ca8b--- /dev/null+++ b/.sqlx/query-9ef7301d256f730320328bbefd630e4b80751898cd67f811f9a428965f612c67.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT message_id\n FROM email_draft_client_ids\n WHERE client_id = $1 AND link_id = ANY($2)\n ORDER BY created_at DESC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "message_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "UuidArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "9ef7301d256f730320328bbefd630e4b80751898cd67f811f9a428965f612c67"+}diff --git a/.sqlx/query-a5f8e2098c604eaf4122df1d69d404566d43655087ad3c9e8dc2e55b95976f9d.json b/.sqlx/query-a5f8e2098c604eaf4122df1d69d404566d43655087ad3c9e8dc2e55b95976f9d.jsonnew file mode 100644index 0000000000..6bbe92cbf4--- /dev/null+++ b/.sqlx/query-a5f8e2098c604eaf4122df1d69d404566d43655087ad3c9e8dc2e55b95976f9d.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT m.id AS \"message_db_id!\", m.thread_id AS \"thread_db_id!\"\n FROM email_draft_client_ids c\n JOIN email_messages m ON m.id = c.message_id\n WHERE c.link_id = $1 AND c.client_id = $2 AND m.link_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "message_db_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "thread_db_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "a5f8e2098c604eaf4122df1d69d404566d43655087ad3c9e8dc2e55b95976f9d"+}diff --git a/.sqlx/query-c9f5a85fbc20c611abb39134d4cf25f0bae3f739676aff2e9c448e294e853f6c.json b/.sqlx/query-c9f5a85fbc20c611abb39134d4cf25f0bae3f739676aff2e9c448e294e853f6c.jsonnew file mode 100644index 0000000000..7512381f57--- /dev/null+++ b/.sqlx/query-c9f5a85fbc20c611abb39134d4cf25f0bae3f739676aff2e9c448e294e853f6c.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT thread_id\n FROM email_thread_client_ids\n WHERE client_id = $1 AND link_id = ANY($2)\n ORDER BY created_at DESC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "UuidArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "c9f5a85fbc20c611abb39134d4cf25f0bae3f739676aff2e9c448e294e853f6c"+}diff --git a/.sqlx/query-3b147b8bcb7d08a87729fc68c562ea545e65d41bd61891ed3aad8eda3c4d90dd.json b/.sqlx/query-d61d85fbcb608cc93260ebb7eef475d0dfb7602cc4a59a2411fa8304f746131d.jsonsimilarity index 65%rename from .sqlx/query-3b147b8bcb7d08a87729fc68c562ea545e65d41bd61891ed3aad8eda3c4d90dd.jsonrename to .sqlx/query-d61d85fbcb608cc93260ebb7eef475d0dfb7602cc4a59a2411fa8304f746131d.jsonindex 3de2090f48..6a80cf5b2d 100644--- a/.sqlx/query-3b147b8bcb7d08a87729fc68c562ea545e65d41bd61891ed3aad8eda3c4d90dd.json+++ b/.sqlx/query-d61d85fbcb608cc93260ebb7eef475d0dfb7602cc4a59a2411fa8304f746131d.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO email_messages (\n id, provider_id, link_id, thread_id, provider_thread_id,\n replying_to_id, subject, from_contact_id, sent_at,\n has_attachments, is_read, is_starred, is_sent, is_draft,\n body_text, body_html_sanitized, body_macro, headers_jsonb,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)\n ON CONFLICT (id) DO UPDATE SET\n provider_id = EXCLUDED.provider_id,\n thread_id = EXCLUDED.thread_id,\n provider_thread_id = EXCLUDED.provider_thread_id,\n replying_to_id = EXCLUDED.replying_to_id,\n subject = EXCLUDED.subject,\n from_contact_id = EXCLUDED.from_contact_id,\n sent_at = EXCLUDED.sent_at,\n has_attachments = EXCLUDED.has_attachments,\n is_read = EXCLUDED.is_read,\n is_starred = EXCLUDED.is_starred,\n is_sent = EXCLUDED.is_sent,\n is_draft = EXCLUDED.is_draft,\n body_text = EXCLUDED.body_text,\n body_html_sanitized = EXCLUDED.body_html_sanitized,\n body_macro = EXCLUDED.body_macro,\n headers_jsonb = EXCLUDED.headers_jsonb,\n updated_at = NOW()\n ",+ "query": "\n INSERT INTO email_messages (\n id, provider_id, link_id, thread_id, provider_thread_id,\n replying_to_id, subject, from_contact_id, sent_at,\n has_attachments, is_read, is_starred, is_sent, is_draft,\n body_text, body_html_sanitized, body_macro, headers_jsonb,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)\n ON CONFLICT (id) DO UPDATE SET\n provider_id = EXCLUDED.provider_id,\n thread_id = EXCLUDED.thread_id,\n provider_thread_id = EXCLUDED.provider_thread_id,\n replying_to_id = EXCLUDED.replying_to_id,\n subject = EXCLUDED.subject,\n from_contact_id = EXCLUDED.from_contact_id,\n sent_at = EXCLUDED.sent_at,\n is_read = EXCLUDED.is_read,\n is_starred = EXCLUDED.is_starred,\n is_sent = EXCLUDED.is_sent,\n is_draft = EXCLUDED.is_draft,\n body_text = EXCLUDED.body_text,\n body_html_sanitized = EXCLUDED.body_html_sanitized,\n body_macro = EXCLUDED.body_macro,\n headers_jsonb = EXCLUDED.headers_jsonb,\n updated_at = NOW()\n WHERE email_messages.link_id = EXCLUDED.link_id\n AND email_messages.is_draft\n AND NOT email_messages.is_sent\n ","describe": {"columns": [],"parameters": {@@ -29,5 +29,5 @@},"nullable": []},- "hash": "3b147b8bcb7d08a87729fc68c562ea545e65d41bd61891ed3aad8eda3c4d90dd"+ "hash": "d61d85fbcb608cc93260ebb7eef475d0dfb7602cc4a59a2411fa8304f746131d"}diff --git a/.sqlx/query-edefa1a786af8acc7aec70203f3fc41661123b2be3a6dba1337c21d842c85dcc.json b/.sqlx/query-edefa1a786af8acc7aec70203f3fc41661123b2be3a6dba1337c21d842c85dcc.jsonnew file mode 100644index 0000000000..6339b34c2d--- /dev/null+++ b/.sqlx/query-edefa1a786af8acc7aec70203f3fc41661123b2be3a6dba1337c21d842c85dcc.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT subject, body_text, has_attachments FROM email_messages WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "subject",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "body_text",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "has_attachments",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true,+ true,+ false+ ]+ },+ "hash": "edefa1a786af8acc7aec70203f3fc41661123b2be3a6dba1337c21d842c85dcc"+}diff --git a/Cargo.lock b/Cargo.lockindex baf1fbde86..0fc9f6971a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7558,6 +7558,7 @@ dependencies = ["async-graphql","chrono","email",+ "email_utils","entity_access","futures","graphql_common",diff --git a/apps/web/src/features/email-compose/compose-adapter.ts b/apps/web/src/features/email-compose/compose-adapter.tsindex 6de65f443c..c3d65cfd85 100644--- a/apps/web/src/features/email-compose/compose-adapter.ts+++ b/apps/web/src/features/email-compose/compose-adapter.ts@@ -18,6 +18,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import { trackMention } from '@core/signal/mention';import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';import { getDisplayName, tryMacroId } from '@core/user';+import { deviceLooksOffline } from '@core/util/connectivity';import { interceptMailtoLinks } from '@core/util/interceptMailtoLinks';import { handleFileFolderDrop } from '@core/util/upload';import { Telemetry } from '@macro-inc/observability';@@ -34,6 +35,15 @@ import {useSaveDraftMutation,} from '@queries/email/draft';import { markThreadDraftSaved } from '@queries/email/draft-cache';+import {+ deleteEmailDraftQueued,+ draftQueueActive,+ saveEmailDraftQueued,+} from '@queries/email/draft-queue';+import {+ draftContactInput,+ type GraphqlSaveEmailDraftArgs,+} from '@queries/email/graphql/draft';import {archiveEmailThread,scheduleEmailMessage,@@ -46,25 +56,45 @@ import {} from '@queries/email/link';import {fetchAndCacheThread,+ type ThreadQueryTransport,useSendMessageMutation,useUnscheduleMessageMutation,} from '@queries/email/thread';import { invalidateSoupEntity, refetchSoupEntity } from '@queries/soup/cache';import type { ApiThread } from '@service-email/generated/schemas';import type { InfiniteData } from '@tanstack/solid-query';-import type {- ComposeNoticeOptions,- EmailComposeContext,+import { confirmDialog } from '@ui';+import { type Accessor, getOwner } from 'solid-js';+import {+ type ComposeNoticeOptions,+ type DraftClientHandles,+ DraftPersistRejected,+ type DraftSaveResult,+ type EmailComposeContext,+ type SaveEmailDraft,} from './context/compose-capabilities';+import { decodeBase64Utf8 } from './core/decode-base64';+import type { EmailDraft } from './core/email-draft';import { readDroppedEmailFiles } from './editor-adapter';import { makeAttachmentPublic } from './make-attachment-public';import { createEmailInboxSource } from './queries/inbox-source';import { restoreDraftBodyAfterUndo, runUndoSend } from './undo-send';+export type EmailComposeContextOptions = {+ /** Transport of the thread read this surface sits under; a compose surface has none. */+ threadTransport?: Accessor<ThreadQueryTransport | undefined>;+};+/** Construct under the composing surface's Solid owner to scope request progress. */-export function createEmailComposeContext(): EmailComposeContext {+export function createEmailComposeContext(+ options: EmailComposeContextOptions = {}+): EmailComposeContext {const accounts = useEmailLinksQuery();const headerId = useNonPrimaryEmailLinkIdHeader();+ const primaryId = usePrimaryEmailLinkId();+ // Attach handlers run as event handlers, which have no Solid owner of+ // their own; the dialog needs the surface's.+ const dialogOwner = getOwner();const user = useUserContext();const paywall = usePaywallState();const viewerEmail = useEmail();@@ -90,6 +120,54 @@ export function createEmailComposeContext(): EmailComposeContext {});const reportError = (error: unknown) =>Telemetry.error(error instanceof Error ? error : new Error(String(error)));++ // Queued writes address a draft by handles: the composer's minted ones, or a+ // confirmed draft's server ids, which resolve as their own handles.+ const queueHandles = ({+ draft,+ clientHandles,+ }: SaveEmailDraft):+ | (DraftClientHandles & { threadId: string })+ | undefined => {+ if (!draftQueueActive(options.threadTransport?.())) return undefined;+ if (clientHandles?.threadId) {+ return { ...clientHandles, threadId: clientHandles.threadId };+ }+ return draft.db_id && draft.thread_db_id+ ? { draftId: draft.db_id, threadId: draft.thread_db_id }+ : undefined;+ };+ const queuedSaveArgs = (+ draft: EmailDraft,+ handles: DraftClientHandles & { threadId: string },+ senderLinkId: string+ ): GraphqlSaveEmailDraftArgs => ({+ draftId: handles.draftId,+ threadDbId: handles.threadId,+ // Persist the selected inbox itself: the primary inbox can change before replay.+ linkId: senderLinkId || undefined,+ replyingToId: draft.replying_to_id ?? undefined,+ providerId: draft.provider_id ?? undefined,+ providerThreadId: draft.provider_thread_id ?? undefined,+ subject: draft.subject,+ to: (draft.to ?? []).map(draftContactInput),+ cc: (draft.cc ?? []).map(draftContactInput),+ bcc: (draft.bcc ?? []).map(draftContactInput),+ bodyHtml: draft.body_html ?? undefined,+ bodyText: draft.body_text ?? undefined,+ bodyMacro: draft.body_macro ?? undefined,+ // Client-only, for the optimistic entity: responses carry the body unencoded.+ senderLinkId,+ senderEmail:+ inboxSource.inboxes().find((inbox) => inbox.id === senderLinkId)+ ?.email_address ??+ viewerEmail() ??+ '',+ optimisticBodyHtml: draft.body_html+ ? decodeBase64Utf8(draft.body_html)+ : null,+ });+return {recipientName: (id) => getDisplayName(tryMacroId(id)),recordMention: (sourceId, targetId) => {@@ -97,8 +175,9 @@ export function createEmailComposeContext(): EmailComposeContext {},accounts: {...inboxSource,- primaryId: usePrimaryEmailLinkId(),+ primaryId,},+ connectivity: { looksOffline: deviceLooksOffline },viewerEmail,recipients: users,hasPaidAccess: useHasPaidAccess(),@@ -139,6 +218,12 @@ export function createEmailComposeContext(): EmailComposeContext {alert: (message, options) => toast.alert(message, notice(options)),dismiss: toast.dismiss,},+ async blockingNotice({ title, body }) {+ await confirmDialog(+ { title, body, confirmLabel: 'OK' },+ { owner: dialogOwner }+ );+ },reportError,},drafts: {@@ -148,8 +233,31 @@ export function createEmailComposeContext(): EmailComposeContext {inboxId,...input}) {+ const handles = queueHandles(input);+ if (handles) {+ const senderLinkId = inboxId ?? primaryId() ?? '';+ const outcome = await saveEmailDraftQueued({+ args: queuedSaveArgs(input.draft, handles, senderLinkId),+ completingThread,+ previousThreadId,+ });+ if (outcome.kind === 'rejected') {+ throw new DraftPersistRejected(outcome.code);+ }+ const saved: DraftSaveResult =+ outcome.kind === 'queued'+ ? { ...handles, inboxId: senderLinkId, persistence: 'queued' }+ : {+ draftId: outcome.draftId,+ threadId: outcome.threadId,+ inboxId: senderLinkId,+ persistence: 'committed',+ };+ return saved;+ }+ const { clientHandles: _clientHandles, ...restInput } = input;const result = await save.mutateAsync({- ...input,+ ...restInput,linkId: headerId(inboxId),skipSoupRefetch: completingThread,});@@ -173,6 +281,17 @@ export function createEmailComposeContext(): EmailComposeContext {};},async deleteDraft({ completingThread, inboxId, ...input }) {+ if (input.threadId && draftQueueActive(options.threadTransport?.())) {+ const outcome = await deleteEmailDraftQueued({+ draftId: input.draftId,+ threadId: input.threadId,+ completingThread,+ });+ if (outcome.kind === 'rejected') {+ throw new DraftPersistRejected(outcome.code);+ }+ return;+ }await remove.mutateAsync({...input,linkId: headerId(inboxId),diff --git a/apps/web/src/features/email-compose/context/compose-capabilities.ts b/apps/web/src/features/email-compose/context/compose-capabilities.tsindex c7dea92212..6a4a3fbd82 100644--- a/apps/web/src/features/email-compose/context/compose-capabilities.ts+++ b/apps/web/src/features/email-compose/context/compose-capabilities.ts@@ -21,8 +21,51 @@ export interface PersistedEmailIdentity {inboxId: string;}+/**+ * A draft save's identity plus how it landed. `queued`: the durable+ * mutation queue accepted the write under the caller's client handles, which+ * the server may not know yet; REST-only actions cannot use them until a+ * later save commits. Absent means committed.+ */+export interface DraftSaveResult extends PersistedEmailIdentity {+ persistence?: 'committed' | 'queued';+}++/** Server rejection codes for a draft save or delete. None is retried by autosave. */+export type DraftPersistFailureCode =+ | 'DRAFT_ALREADY_SENT'+ | 'NOT_FOUND'+ | 'INBOX_NOT_FOUND'+ | 'UNAUTHORIZED'+ | 'INVALID'+ | 'INTERNAL';++/**+ * A deterministic server rejection of a draft save or delete. Transport+ * failures reject with a plain error and may be retried; this one carries+ * the code so a composer can interpret it (an already-sent draft resets the+ * composer, anything else latches autosave).+ */+export class DraftPersistRejected extends Error {+ constructor(readonly code: DraftPersistFailureCode) {+ super(`Draft persistence rejected: ${code}`);+ this.name = 'DraftPersistRejected';+ }+}++/**+ * Client-minted identity for a draft the server has not confirmed. Carried+ * apart from `draft.db_id` (a server id) because only the durable queue can+ * resolve handles; a REST save ignores them and mints server ids instead.+ */+export interface DraftClientHandles {+ draftId: string;+ threadId?: string;+}+export interface SaveEmailDraft {draft: EmailDraft;+ clientHandles?: DraftClientHandles;sendTime?: Date | null;previousThreadId?: string;inboxId?: string;@@ -53,7 +96,7 @@ export interface EmailAttachmentChange {}export interface EmailDraftStorage {- saveDraft(input: SaveEmailDraft): Promise<PersistedEmailIdentity>;+ saveDraft(input: SaveEmailDraft): Promise<DraftSaveResult>;deleteDraft(input: DeleteEmailDraft): Promise<void>;restoreDraft(input: {draftId: string;@@ -104,9 +147,16 @@ export interface EmailComposeFeedback {alert(message: string, options?: ComposeNoticeOptions): void;dismiss(id: number): void;};+ /** A modal notice with a single acknowledgement; resolves when dismissed. */+ blockingNotice(input: { title: string; body: string }): Promise<void>;reportError(error: unknown): void;}+/** Best-effort device connectivity; a false negative surfaces as the guarded action's own failure. */+export interface EmailConnectivity {+ looksOffline(): boolean;+}+export interface EmailComposeAccounts {inboxes: Accessor<EmailInbox[]>;loading: Accessor<boolean>;@@ -145,6 +195,7 @@ export interface EmailComposeContext {delivery: EmailDelivery;notices: EmailComposeFeedback;accounts: EmailComposeAccounts;+ connectivity: EmailConnectivity;presentation: EmailComposePresentation;editorFiles: EmailEditorFiles;viewerEmail: Accessor<string | undefined>;diff --git a/apps/web/src/features/email-compose/primitives/attachment-persistence.ts b/apps/web/src/features/email-compose/primitives/attachment-persistence.tsindex 8d378034cc..1e21baa647 100644--- a/apps/web/src/features/email-compose/primitives/attachment-persistence.ts+++ b/apps/web/src/features/email-compose/primitives/attachment-persistence.ts@@ -1,5 +1,9 @@import { type Accessor, createSignal } from 'solid-js';-import type { EmailAttachmentStorage } from '../context/compose-capabilities';+import type {+ EmailAttachmentStorage,+ EmailComposeFeedback,+ EmailConnectivity,+} from '../context/compose-capabilities';import type { DraftFormAttachment } from './email-form-state';import type { EmailFormContextValue } from './email-form-types';@@ -13,6 +17,23 @@ type AttachmentState = Pick<| 'removeForwarded'>;+/**+ * A queued save carries only text; file bytes live in the composer's memory+ * until a save commits, so adding attachments offline is refused rather than+ * silently missed. Resolves true when the add must not proceed.+ */+export async function refuseAttachmentsOffline(+ connectivity: EmailConnectivity,+ notices: Pick<EmailComposeFeedback, 'blockingNotice'>+): Promise<boolean> {+ if (!connectivity.looksOffline()) return false;+ await notices.blockingNotice({+ title: "You're offline",+ body: "Attachments can't be added while you're offline. Reconnect and try again.",+ });+ return true;+}+/** Attachment transport and completion, independent of draft/send orchestration. */export function createAttachmentPersistence(options: {attachments: AttachmentState;diff --git a/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts b/apps/web/src/features/email-compose/primitives/compose-persistence.test.tsindex 703f025bae..3f4ab9b7a2 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@@ -288,3 +288,44 @@ it('uses the captured inbox for attachment upload when a sender switch queues be).toBe('other');root.dispose();});++it('retains the thread identity when undo reopens a standalone draft from its snapshot', async () => {+ const context = createComposeContext();+ vi.mocked(context.delivery.sendMessage).mockResolvedValue(response);+ vi.mocked(context.drafts.saveDraft).mockResolvedValue(response);+ vi.mocked(context.delivery.undoSend).mockImplementation(async (input) => {+ await input.onUndone();+ });+ let reopened: ReturnType<typeof mountEmailComposer> | undefined;+ const root = mountEmailComposer(context, {+ showDraft: (draftId) => {+ reopened = mountEmailComposer(context, undefined, { draftId });+ },+ });+ try {+ root.edit('Restore this draft');+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);+ root.dispose();+ const notice = vi+ .mocked(context.notices.feedback.success)+ .mock.calls.find(([message]) => message === 'Email sent');+ expect(notice?.[1]?.actions).toHaveLength(1);+ notice?.[1]?.actions?.[0].onClick();+ await vi.advanceTimersByTimeAsync(0);+ expect(reopened).toBeDefined();+ reopened?.edit('Edited after undo');+ await vi.advanceTimersByTimeAsync(600);+ expect(context.drafts.saveDraft).toHaveBeenLastCalledWith(+ expect.objectContaining({+ draft: expect.objectContaining({+ db_id: 'saved-id',+ thread_db_id: 'thread',+ }),+ })+ );+ } finally {+ root.dispose();+ reopened?.dispose();+ }+});diff --git a/apps/web/src/features/email-compose/primitives/draft-persistence.ts b/apps/web/src/features/email-compose/primitives/draft-persistence.tsnew file mode 100644index 0000000000..5de2377690--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/draft-persistence.ts@@ -0,0 +1,160 @@+import { v7 as uuidv7 } from 'uuid';+import {+ type DeleteEmailDraft,+ DraftPersistRejected,+ type DraftSaveResult,+ type EmailComposeFeedback,+ type EmailDraftStorage,+} from '../context/compose-capabilities';+import type { EmailDraft } from '../core/email-draft';+import type { DraftSession } from './draft-session';++/** Sent from another device: the server outcome supersedes the local draft. */+export const isAlreadySentRejection = (error: unknown) =>+ error instanceof DraftPersistRejected && error.code === 'DRAFT_ALREADY_SENT';++/**+ * A discard's delete. An already-sent verdict is not a failure: the reset+ * the caller performs next is exactly what that verdict asks for, so it is+ * announced and swallowed. Every other rejection propagates.+ */+export async function deleteDraftForDiscard(+ drafts: Pick<EmailDraftStorage, 'deleteDraft'>,+ input: DeleteEmailDraft,+ notices: Pick<EmailComposeFeedback, 'feedback'>,+ alreadySentMessage: string+): Promise<void> {+ try {+ await drafts.deleteDraft(input);+ } catch (error) {+ if (!isAlreadySentRejection(error)) throw error;+ notices.feedback.alert(alreadySentMessage);+ }+}++/**+ * One draft's save/delete workflow against its session, shared by the reply+ * and standalone controllers.+ *+ * Identity is local-first: handles are minted before the first dispatch so+ * every queued save of a draft resolves to one server row, even when the+ * responses arrive after an app restart. Only server-confirmed ids travel in+ * the draft; minted handles go apart because a REST save cannot resolve+ * them. An outcome that lands after the composer reset (send, discard, an+ * already-sent verdict on another save) belongs to a draft the user already+ * dropped and is ignored: adopting its ids or uploading against it — the+ * upload reads the live form, which may already hold the next draft's files+ * — would re-plant that draft into the fresh composer.+ */+export function createDraftPersistence(options: {+ session: DraftSession;+ drafts: Pick<EmailDraftStorage, 'saveDraft' | 'deleteDraft'>;+ attachments: {+ upload(+ draftId: string,+ inbox: { inboxId: string | undefined }+ ): Promise<void>;+ };+ /** A standalone compose mints its thread handle too; a reply saves into a known thread. */+ mintThreadHandle: boolean;+ onAlreadySent(): void;+}) {+ const { session } = options;++ // The session records deterministic rejections (latch, or drop on+ // already-sent); transport failures just reject and the next save may retry.+ const recordRejection = (error: unknown, epoch: number) => {+ if (!(error instanceof DraftPersistRejected) || session.isStale(epoch))+ return;+ session.dispatch({ type: 'rejected', epoch, code: error.code });+ if (error.code === 'DRAFT_ALREADY_SENT') options.onAlreadySent();+ };++ return {+ /** The draft has no content left: delete its row and drop its identity. */+ async remove(input: { inboxId?: string; completingThread?: boolean }) {+ const draftId = session.draftId();+ const epoch = session.epoch();+ if (draftId) {+ try {+ await options.drafts.deleteDraft({+ draftId,+ threadId: session.threadId(),+ ...input,+ });+ } catch (error) {+ recordRejection(error, epoch);+ throw error;+ }+ }+ if (session.isStale(epoch)) return;+ session.dispatch({ type: 'emptied' });+ },++ /**+ * Saves the draft and its local attachments. Resolves with the result,+ * or undefined when nothing was adopted: autosave is latched, or the+ * composer was reset while the save was on the wire.+ */+ async save(input: {+ draft: EmailDraft;+ inboxId?: string;+ completingThread?: boolean;+ }): Promise<DraftSaveResult | undefined> {+ // Latched: the content stays in the editor, but a rejected save must+ // never replay on its own — a doomed save would block the queue.+ if (!session.autosaveAllowed()) return;+ const previousThreadId = session.threadId();+ if (!session.draftId()) {+ session.dispatch({+ type: 'minted',+ draftId: uuidv7(),+ threadId: options.mintThreadHandle+ ? uuidv7()+ : (input.draft.thread_db_id ?? undefined),+ });+ }+ const identity = session.identity();+ const epoch = session.epoch();+ const confirmed = identity.kind === 'server' ? identity : undefined;+ let saved: DraftSaveResult;+ try {+ saved = await options.drafts.saveDraft({+ draft: {+ ...input.draft,+ db_id: confirmed?.draftId,+ thread_db_id: input.draft.thread_db_id ?? confirmed?.threadId,+ },+ clientHandles:+ identity.kind === 'handle'+ ? { draftId: identity.draftId, threadId: identity.threadId }+ : undefined,+ inboxId: input.inboxId,+ completingThread: input.completingThread,+ previousThreadId,+ });+ } catch (error) {+ recordRejection(error, epoch);+ throw error;+ }+ if (session.isStale(epoch)) return;+ session.dispatch({ type: 'saved', epoch, identity: saved });+ if (!saved.draftId) return;+ const inbox = { inboxId: input.inboxId };+ if (saved.persistence === 'queued') {+ // REST cannot resolve client handles. Keep local files for the next+ // committed save, which also waits for all uploads before sending.+ return saved;+ }+ await options.attachments.upload(saved.draftId, inbox);+ if (session.isStale(epoch)) return;+ return saved;+ },++ /** The id REST-only follow-ups (scheduling) may use after a save, else undefined. */+ confirmed: (draftId: string | undefined) =>+ session.serverConfirmed() && session.autosaveAllowed()+ ? draftId+ : undefined,+ };+}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.tsnew file mode 100644index 0000000000..9472f22a74--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts@@ -0,0 +1,406 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ DraftPersistRejected,+ type DraftSaveResult,+ type SaveEmailDraft,+} from '../context/compose-capabilities';+import { createComposeContext } from '../tests/capabilities';+import { mountEmailComposer } from '../tests/composer';+import { mountReplyComposer } from '../tests/reply';++/** A save the durable queue accepted under the composer's own handles. */+const queued = (input: SaveEmailDraft): DraftSaveResult => ({+ draftId: input.clientHandles?.draftId ?? input.draft.db_id ?? undefined,+ threadId:+ input.clientHandles?.threadId ?? input.draft.thread_db_id ?? 'thread',+ inboxId: 'inbox',+ persistence: 'queued',+});+const committed = (draftId = 'server-1'): DraftSaveResult => ({+ draftId,+ threadId: 'thread',+ inboxId: 'inbox',+ persistence: 'committed',+});+const savedInputs = (context: ReturnType<typeof createComposeContext>) =>+ vi.mocked(context.drafts.saveDraft).mock.calls.map(([input]) => input);++beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++describe('draft session: reply composer', () => {+ it('queues saves offline under one handle, refuses to send, then sends once a save commits', async () => {+ const context = createComposeContext();+ vi.mocked(context.connectivity.looksOffline).mockReturnValue(true);+ vi.mocked(context.drafts.saveDraft).mockImplementation(async (input) =>+ queued(input)+ );+ const state = mountReplyComposer(context);+ try {+ state.edit('Typed offline');+ await vi.advanceTimersByTimeAsync(600);+ state.edit('Typed offline, again');+ await vi.advanceTimersByTimeAsync(600);+ const [first, second] = savedInputs(context);+ // Minted handles travel apart from server ids, and every save of the+ // draft reuses them so replays converge on one server row.+ expect(first.draft.db_id).toBeUndefined();+ expect(first.clientHandles?.draftId).toBeTruthy();+ expect(second.clientHandles).toEqual(first.clientHandles);++ await state.sendEmail();+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(+ 'Failed to send email',+ { subtext: "You're offline" }+ );++ vi.mocked(context.connectivity.looksOffline).mockReturnValue(false);+ vi.mocked(context.drafts.saveDraft).mockImplementation(async () =>+ committed('server-1')+ );+ await state.sendEmail();+ expect(context.delivery.sendMessage).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ message: expect.objectContaining({ db_id: 'server-1' }),+ })+ );+ } finally {+ state.dispose();+ }+ });++ it('asks for a retry when the pre-send save only queued, and sends once it commits', async () => {+ const context = createComposeContext();+ vi.mocked(context.drafts.saveDraft)+ .mockImplementationOnce(async (input) => queued(input))+ .mockImplementationOnce(async () => committed('server-2'));+ const state = mountReplyComposer(context);+ try {+ await state.sendEmail();+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(+ 'Failed to send email',+ { subtext: 'Draft still syncing, try again' }+ );+ await state.sendEmail();+ // The retry reused the same handle; the confirmed server id went out.+ const [first, second] = savedInputs(context);+ expect(second.clientHandles).toEqual(first.clientHandles);+ expect(context.delivery.sendMessage).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ message: expect.objectContaining({ db_id: 'server-2' }),+ })+ );+ } finally {+ state.dispose();+ }+ });++ it('waits for an in-flight first save and sends with the id it confirmed', async () => {+ const context = createComposeContext();+ const first = Promise.withResolvers<DraftSaveResult>();+ vi.mocked(context.drafts.saveDraft)+ .mockReturnValueOnce(first.promise)+ .mockImplementationOnce(async () => committed('server-3'));+ const state = mountReplyComposer(context);+ try {+ state.edit('Quick reply');+ await vi.advanceTimersByTimeAsync(600);+ const send = state.sendEmail();+ await vi.advanceTimersByTimeAsync(0);+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ first.resolve(committed('server-3'));+ await send;+ expect(context.drafts.saveDraft).toHaveBeenCalledTimes(2);+ expect(savedInputs(context)[1].draft.db_id).toBe('server-3');+ expect(context.delivery.sendMessage).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ message: expect.objectContaining({ db_id: 'server-3' }),+ })+ );+ } finally {+ state.dispose();+ }+ });++ it('drops the draft and aborts the send when the pre-send save learns it was already sent', async () => {+ const context = createComposeContext();+ vi.mocked(context.drafts.saveDraft)+ .mockRejectedValueOnce(new DraftPersistRejected('DRAFT_ALREADY_SENT'))+ .mockImplementation(async () => committed('server-4'));+ const state = mountReplyComposer(context);+ try {+ await state.sendEmail();+ await vi.advanceTimersByTimeAsync(0);+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ expect(context.notices.feedback.alert).toHaveBeenCalledWith(+ 'This reply was already sent'+ );+ expect(state.savedDraftId()).toBeUndefined();+ // A fresh draft afterwards saves under new handles, not the sent id.+ state.edit('A new reply');+ await vi.advanceTimersByTimeAsync(600);+ const inputs = savedInputs(context);+ expect(inputs).toHaveLength(2);+ expect(inputs[1].draft.db_id).toBeUndefined();+ expect(inputs[1].clientHandles?.draftId).not.toEqual(+ inputs[0].clientHandles?.draftId+ );+ } finally {+ state.dispose();+ }+ });++ it('latches autosave after a rejection until the draft is discarded', async () => {+ const context = createComposeContext();+ vi.mocked(context.drafts.saveDraft)+ .mockRejectedValueOnce(new DraftPersistRejected('INVALID'))+ .mockImplementation(async () => committed('server-5'));+ const state = mountReplyComposer(context);+ try {+ state.edit('Rejected content');+ await vi.advanceTimersByTimeAsync(600);+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();+ state.edit('Still rejected content');+ await vi.advanceTimersByTimeAsync(600);+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();+ await state.deleteDraftAndReset();+ await vi.advanceTimersByTimeAsync(0);+ state.edit('Fresh content');+ await vi.advanceTimersByTimeAsync(600);+ expect(context.drafts.saveDraft).toHaveBeenCalledTimes(2);+ } finally {+ state.dispose();+ }+ });++ it('refuses to attach while offline with a blocking notice', async () => {+ const context = createComposeContext();+ vi.mocked(context.connectivity.looksOffline).mockReturnValue(true);+ const state = mountReplyComposer(context);+ try {+ await state.handleAddAttachments([new File(['bytes'], 'notes.txt')]);+ expect(context.notices.blockingNotice).toHaveBeenCalledOnce();+ expect(state.form.attachments.list()).toEqual([]);+ } finally {+ state.dispose();+ }+ });+});++describe('draft session: compose composer', () => {+ it.each(['pre-send', 'autosave'])(+ 'sends without a draft ID after a failed first %s save',+ async (firstSave) => {+ const context = createComposeContext();+ vi.mocked(context.drafts.saveDraft).mockRejectedValue(+ new Error('Draft save unavailable')+ );+ const root = mountEmailComposer(context);+ try {+ root.edit('Send even when draft saving fails');+ if (firstSave === 'autosave') {+ await vi.advanceTimersByTimeAsync(600);+ }+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);++ expect(savedInputs(context)[0].clientHandles?.draftId).toBeTruthy();+ expect(context.delivery.sendMessage).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ message: expect.objectContaining({+ db_id: undefined,+ subject: 'Review',+ body_text: expect.stringContaining(+ 'Send even when draft saving fails'+ ),+ }),+ })+ );+ expect(context.notices.feedback.failure).not.toHaveBeenCalled();+ } finally {+ root.dispose();+ }+ }+ );++ it('keeps queued drafts blocked after a later save fails until the server confirms an ID', async () => {+ const context = createComposeContext();+ vi.mocked(context.drafts.saveDraft)+ .mockImplementationOnce(async (input) => queued(input))+ .mockRejectedValueOnce(new Error('Draft save unavailable'))+ .mockImplementationOnce(async () => committed('server-compose'));+ const root = mountEmailComposer(context);+ try {+ root.edit('Wait for the queued draft');+ for (let attempt = 0; attempt < 2; attempt++) {+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(+ 'Failed to send email',+ { subtext: 'Draft still syncing, try again' }+ );+ }+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);+ expect(context.delivery.sendMessage).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ message: expect.objectContaining({ db_id: 'server-compose' }),+ })+ );+ const [first, second, third] = savedInputs(context);+ expect(second.clientHandles).toEqual(first.clientHandles);+ expect(third.clientHandles).toEqual(first.clientHandles);+ } finally {+ root.dispose();+ }+ });++ it('reuses a confirmed draft ID when its pre-send save fails', async () => {+ const context = createComposeContext();+ vi.mocked(context.drafts.saveDraft)+ .mockResolvedValueOnce(committed('existing-draft'))+ .mockRejectedValueOnce(new Error('Draft save unavailable'));+ const root = mountEmailComposer(context);+ try {+ root.edit('Already saved');+ await vi.advanceTimersByTimeAsync(600);+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);+ expect(context.delivery.sendMessage).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ message: expect.objectContaining({ db_id: 'existing-draft' }),+ })+ );+ } finally {+ root.dispose();+ }+ });++ it.each(['INVALID', 'DRAFT_ALREADY_SENT'] as const)(+ 'does not send a new draft rejected with %s',+ async (code) => {+ const context = createComposeContext();+ vi.mocked(context.drafts.saveDraft).mockRejectedValue(+ new DraftPersistRejected(code)+ );+ const root = mountEmailComposer(context);+ try {+ root.edit('Rejected draft');+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ } finally {+ root.dispose();+ }+ }+ );++ it.each(['save', 'upload'])(+ 'refuses to send an unuploaded attachment after a failed %s',+ async (failure) => {+ const context = createComposeContext();+ const file = new File(['bytes'], 'notes.txt');+ if (failure === 'save') {+ vi.mocked(context.drafts.saveDraft).mockRejectedValue(+ new Error('Draft save unavailable')+ );+ }+ vi.mocked(context.attachmentStorage.uploadAttachments).mockImplementation(+ async (input) => {+ input.onAttachmentUploadFailed?.(file);+ throw new Error('Upload failed');+ }+ );+ const root = mountEmailComposer(context);+ try {+ root.edit('With an attachment');+ await root.state.context.onAddAttachments([{ type: 'local', file }]);+ await vi.advanceTimersByTimeAsync(600);+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(10);+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(+ 'Failed to send email',+ { subtext: 'Attachment not uploaded' }+ );+ } finally {+ root.dispose();+ }+ }+ );+});++describe.each(['reply', 'compose'] as const)(+ 'saved %s draft ordering',+ (surface) => {+ const mount = (context: ReturnType<typeof createComposeContext>) => {+ if (surface === 'reply') {+ const root = mountReplyComposer(context);+ return {+ ...root,+ send: root.sendEmail,+ schedule: root.handleSendTimeChange,+ };+ }+ const root = mountEmailComposer(context);+ return {+ ...root,+ send: async () => {+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);+ },+ schedule: root.state.context.onSendTimeChange,+ };+ };++ it('does not send or schedule over a queued update to an existing server draft', async () => {+ const context = createComposeContext();+ vi.mocked(context.drafts.saveDraft)+ .mockResolvedValueOnce(committed('existing'))+ .mockImplementation(async (input) => queued(input));+ const root = mount(context);+ try {+ root.edit('Saved online');+ await vi.advanceTimersByTimeAsync(600);+ root.edit('Updated behind the queue');+ await root.send();+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(+ 'Failed to send email',+ { subtext: 'Draft still syncing, try again' }+ );+ await root.schedule?.(new Date('2027-01-01T12:00:00Z'));+ expect(context.delivery.schedule).not.toHaveBeenCalled();+ vi.mocked(context.drafts.saveDraft).mockResolvedValue(+ committed('existing')+ );+ await root.send();+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();+ } finally {+ root.dispose();+ }+ });++ it('does not send a known server draft after autosave has been rejected', async () => {+ const context = createComposeContext();+ vi.mocked(context.drafts.saveDraft)+ .mockResolvedValueOnce(committed('existing'))+ .mockRejectedValue(new DraftPersistRejected('UNAUTHORIZED'));+ const root = mount(context);+ try {+ root.edit('Saved online');+ await vi.advanceTimersByTimeAsync(600);+ root.edit('Access revoked');+ await vi.advanceTimersByTimeAsync(600);+ await root.send();+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ } finally {+ root.dispose();+ }+ });+ }+);diff --git a/apps/web/src/features/email-compose/primitives/draft-session.test.ts b/apps/web/src/features/email-compose/primitives/draft-session.test.tsnew file mode 100644index 0000000000..2a5ccacff0--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/draft-session.test.ts@@ -0,0 +1,213 @@+import { createRoot } from 'solid-js';+import { describe, expect, it } from 'vitest';+import {+ createDraftSession,+ type DraftSessionEvent,+ type DraftSessionState,+ initialDraftSession,+ reduceDraftSession,+} from './draft-session';++const none = initialDraftSession();+const seeded = initialDraftSession({ draftId: 'server-1', threadId: 't-1' });+const handle = reduceDraftSession(none, {+ type: 'minted',+ draftId: 'h-1',+ threadId: 'th-1',+});+const latched: DraftSessionState = {+ ...handle,+ policy: { kind: 'latched', code: 'INVALID' },+};++describe('reduceDraftSession', () => {+ it('seeds a server identity from an existing draft, none otherwise', () => {+ expect(seeded.identity).toEqual({+ kind: 'server',+ queued: false,+ draftId: 'server-1',+ threadId: 't-1',+ });+ expect(none.identity).toEqual({ kind: 'none' });+ expect(none.policy).toEqual({ kind: 'autosaving' });+ });++ it('mints handles only for a draft with no identity', () => {+ expect(handle.identity).toEqual({+ kind: 'handle',+ draftId: 'h-1',+ threadId: 'th-1',+ queued: false,+ });+ const minted = { type: 'minted', draftId: 'h-2' } as const;+ expect(reduceDraftSession(handle, minted)).toBe(handle);+ expect(reduceDraftSession(seeded, minted)).toBe(seeded);+ });++ it('a committed save confirms the server identity, keeping a known thread', () => {+ const next = reduceDraftSession(handle, {+ type: 'saved',+ epoch: handle.epoch,+ identity: { draftId: 'server-2', persistence: 'committed' },+ });+ expect(next.identity).toEqual({+ kind: 'server',+ queued: false,+ draftId: 'server-2',+ threadId: 'th-1',+ });+ // Absent persistence is a committed REST save.+ expect(+ reduceDraftSession(handle, {+ type: 'saved',+ epoch: handle.epoch,+ identity: { draftId: 'server-3', threadId: 't-9' },+ }).identity+ ).toEqual({+ kind: 'server',+ draftId: 'server-3',+ threadId: 't-9',+ queued: false,+ });+ });++ it('a queued save never confirms: handles stay handles, server ids stay', () => {+ expect(+ reduceDraftSession(handle, {+ type: 'saved',+ epoch: handle.epoch,+ identity: { draftId: 'h-1', persistence: 'queued' },+ }).identity+ ).toEqual({+ kind: 'handle',+ draftId: 'h-1',+ threadId: 'th-1',+ queued: true,+ });+ expect(+ reduceDraftSession(seeded, {+ type: 'saved',+ epoch: seeded.epoch,+ identity: { draftId: 'server-1', persistence: 'queued' },+ })+ ).toEqual({ ...seeded, identity: { ...seeded.identity, queued: true } });+ });++ it('invalidates pending writes when undo restores a different draft', () => {+ const restored = reduceDraftSession(handle, {+ type: 'seeded',+ draftId: 'restored',+ });+ const lateSave = reduceDraftSession(restored, {+ type: 'saved',+ epoch: handle.epoch,+ identity: { draftId: 'old-draft' },+ });+ expect(lateSave.identity).toMatchObject({ draftId: 'restored' });+ });++ it('ignores outcomes from before a reset', () => {+ const afterReset = reduceDraftSession(handle, { type: 'reset' });+ expect(afterReset.epoch).toBe(handle.epoch + 1);+ const stale: DraftSessionEvent[] = [+ {+ type: 'saved',+ epoch: handle.epoch,+ identity: { draftId: 'server-2', persistence: 'committed' },+ },+ { type: 'rejected', epoch: handle.epoch, code: 'INVALID' },+ { type: 'rejected', epoch: handle.epoch, code: 'DRAFT_ALREADY_SENT' },+ ];+ for (const event of stale) {+ expect(reduceDraftSession(afterReset, event)).toBe(afterReset);+ }+ });++ it('a deterministic rejection latches autosave and keeps the identity', () => {+ const next = reduceDraftSession(handle, {+ type: 'rejected',+ epoch: handle.epoch,+ code: 'UNAUTHORIZED',+ });+ expect(next.policy).toEqual({ kind: 'latched', code: 'UNAUTHORIZED' });+ expect(next.identity).toBe(handle.identity);+ expect(next.epoch).toBe(handle.epoch);+ });++ it('already-sent drops the draft like a reset', () => {+ const next = reduceDraftSession(seeded, {+ type: 'rejected',+ epoch: seeded.epoch,+ code: 'DRAFT_ALREADY_SENT',+ });+ expect(next).toEqual({+ identity: { kind: 'none' },+ policy: { kind: 'autosaving' },+ epoch: seeded.epoch + 1,+ });+ });++ it('emptied and reset start a fresh draft and lift the latch', () => {+ for (const type of ['emptied', 'reset'] as const) {+ const next = reduceDraftSession(latched, { type });+ expect(next.identity).toEqual({ kind: 'none' });+ expect(next.policy).toEqual({ kind: 'autosaving' });+ expect(next.epoch).toBe(latched.epoch + 1);+ }+ });++ it('nothing but emptied, reset, or already-sent leaves the latch', () => {+ const keepsLatch: DraftSessionEvent[] = [+ { type: 'minted', draftId: 'h-9' },+ {+ type: 'saved',+ epoch: latched.epoch,+ identity: { draftId: 'server-9', persistence: 'committed' },+ },+ {+ type: 'saved',+ epoch: latched.epoch,+ identity: { draftId: 'h-1', persistence: 'queued' },+ },+ { type: 'rejected', epoch: latched.epoch, code: 'INTERNAL' },+ ];+ for (const event of keepsLatch) {+ expect(reduceDraftSession(latched, event).policy.kind).toBe('latched');+ }+ });+});++describe('createDraftSession', () => {+ it('derives the send and autosave predicates from state', () => {+ createRoot((dispose) => {+ const session = createDraftSession();+ expect(session.serverConfirmed()).toBe(false);+ expect(session.autosaveAllowed()).toBe(true);+ session.dispatch({ type: 'minted', draftId: 'h-1', threadId: 'th-1' });+ const epoch = session.epoch();+ expect(session.draftId()).toBe('h-1');+ expect(session.serverConfirmed()).toBe(false);+ session.dispatch({+ type: 'saved',+ epoch,+ identity: { draftId: 'h-1', persistence: 'queued' },+ });+ expect(session.serverConfirmed()).toBe(false);+ session.dispatch({+ type: 'saved',+ epoch,+ identity: { draftId: 'server-1', persistence: 'committed' },+ });+ expect(session.serverConfirmed()).toBe(true);+ expect(session.draftId()).toBe('server-1');+ expect(session.threadId()).toBe('th-1');+ session.dispatch({ type: 'rejected', epoch, code: 'INVALID' });+ expect(session.autosaveAllowed()).toBe(false);+ session.dispatch({ type: 'reset' });+ expect(session.isStale(epoch)).toBe(true);+ expect(session.draftId()).toBeUndefined();+ expect(session.autosaveAllowed()).toBe(true);+ dispose();+ });+ });+});diff --git a/apps/web/src/features/email-compose/primitives/draft-session.ts b/apps/web/src/features/email-compose/primitives/draft-session.tsnew file mode 100644index 0000000000..f3f0cf4194--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/draft-session.ts@@ -0,0 +1,180 @@+import { createSignal } from 'solid-js';+import { match } from 'ts-pattern';+import type {+ DraftPersistFailureCode,+ DraftSaveResult,+} from '../context/compose-capabilities';++/**+ * What the composer knows about its draft's server row.+ *+ * `handle`: ids the composer minted; `queued` records whether a save under+ * them was durably queued. The server may not know them yet. `server`: ids a+ * committed save (or a fetched draft) confirmed, so REST-only actions — send,+ * schedule, attachment uploads — can resolve them.+ */+export type DraftIdentity =+ | { kind: 'none' }+ | { kind: 'handle'; draftId: string; threadId?: string; queued: boolean }+ | { kind: 'server'; draftId: string; threadId?: string; queued: boolean };++/**+ * Whether edits may autosave. A deterministic server rejection latches the+ * policy: the content stays in the editor, but the same save must never be+ * replayed on its own — a doomed save retried forever would block every+ * queued mutation in the app behind it.+ */+export type DraftSavePolicy =+ | { kind: 'autosaving' }+ | { kind: 'latched'; code: DraftPersistFailureCode };++export type DraftSessionState = {+ identity: DraftIdentity;+ policy: DraftSavePolicy;+ /**+ * Bumped whenever the composer drops its draft (send, discard, emptied,+ * already sent elsewhere). A continuation that captured an older epoch+ * belongs to a draft the user already left behind and must not adopt ids,+ * upload, refetch, or latch — see `isStale`.+ */+ epoch: number;+};++export type DraftSessionEvent =+ /** Mounted on (or restored to) a draft the server already holds. */+ | { type: 'seeded'; draftId?: string | null; threadId?: string | null }+ /** Client handles minted before the first dispatch of a new draft. */+ | { type: 'minted'; draftId: string; threadId?: string }+ /** A save resolved; `epoch` is the value captured before dispatch. */+ | {+ type: 'saved';+ epoch: number;+ identity: Pick<DraftSaveResult, 'draftId' | 'threadId' | 'persistence'>;+ }+ /** The server rejected a save or delete deterministically. */+ | { type: 'rejected'; epoch: number; code: DraftPersistFailureCode }+ /** The draft has no content left; its row was (or is being) deleted. */+ | { type: 'emptied' }+ /** The composer dropped its draft: sent, discarded, or superseded. */+ | { type: 'reset' };++const FRESH: Omit<DraftSessionState, 'epoch'> = {+ identity: { kind: 'none' },+ policy: { kind: 'autosaving' },+};++export function initialDraftSession(seed?: {+ draftId?: string | null;+ threadId?: string | null;+}): DraftSessionState {+ return reduceDraftSession(+ { ...FRESH, epoch: 0 },+ { type: 'seeded', ...seed }+ );+}++/** Pure transition; every rule the composers rely on lives here. */+export function reduceDraftSession(+ state: DraftSessionState,+ event: DraftSessionEvent+): DraftSessionState {+ return match(event)+ .returnType<DraftSessionState>()+ .with({ type: 'seeded' }, (event) => {+ return {+ ...state,+ identity: event.draftId+ ? {+ kind: 'server',+ queued: false,+ draftId: event.draftId,+ threadId: event.threadId ?? undefined,+ }+ : { kind: 'none' },+ policy: { kind: 'autosaving' },+ epoch: state.epoch + 1,+ };+ })+ .with({ type: 'minted' }, (event) => {+ if (state.identity.kind !== 'none') return state;+ return {+ ...state,+ identity: {+ kind: 'handle',+ draftId: event.draftId,+ threadId: event.threadId,+ queued: false,+ },+ };+ })+ .with({ type: 'saved' }, (event) => {+ if (event.epoch !== state.epoch) return state;+ const draftId = event.identity.draftId ?? currentDraftId(state);+ if (!draftId) return state;+ const threadId = event.identity.threadId ?? currentThreadId(state);+ if (event.identity.persistence === 'queued') {+ // Durable locally under the caller's handles; the server has not+ // confirmed them. A server id stays a server id.+ return state.identity.kind === 'server'+ ? { ...state, identity: { ...state.identity, queued: true } }+ : {+ ...state,+ identity: { kind: 'handle', draftId, threadId, queued: true },+ };+ }+ return {+ ...state,+ identity: { kind: 'server', draftId, threadId, queued: false },+ };+ })+ .with({ type: 'rejected' }, (event) => {+ if (event.epoch !== state.epoch) return state;+ if (event.code === 'DRAFT_ALREADY_SENT') {+ // Sent from another device: the server outcome supersedes the+ // local draft, which the composer drops.+ return { ...FRESH, epoch: state.epoch + 1 };+ }+ return { ...state, policy: { kind: 'latched', code: event.code } };+ })+ .with({ type: 'emptied' }, { type: 'reset' }, () => {+ // A fresh draft: nothing in flight belongs to it, and a rejection+ // latched against the previous content must not keep it from saving.+ return { ...FRESH, epoch: state.epoch + 1 };+ })+ .exhaustive();+}++function currentDraftId(state: DraftSessionState) {+ return state.identity.kind === 'none' ? undefined : state.identity.draftId;+}+function currentThreadId(state: DraftSessionState) {+ return state.identity.kind === 'none' ? undefined : state.identity.threadId;+}++export type DraftSession = ReturnType<typeof createDraftSession>;++/** Reactive holder for one composer's draft session. */+export function createDraftSession(seed?: {+ draftId?: string | null;+ threadId?: string | null;+}) {+ const [state, setState] = createSignal(initialDraftSession(seed));+ return {+ state,+ dispatch(event: DraftSessionEvent) {+ setState((current) => reduceDraftSession(current, event));+ },+ epoch: () => state().epoch,+ /** Whether `epoch`, captured before an await, predates a reset. */+ isStale: (epoch: number) => epoch !== state().epoch,+ identity: () => state().identity,+ draftId: () => currentDraftId(state()),+ threadId: () => currentThreadId(state()),+ /** The server holds the draft under these ids, so any transport can address it. */+ serverConfirmed: () => {+ const identity = state().identity;+ return identity.kind === 'server' && !identity.queued;+ },+ autosaveAllowed: () => state().policy.kind === 'autosaving',+ };+}diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.tsindex 6e9c77e2de..d16970233c 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts@@ -17,6 +17,7 @@ import type {EmailComposeAccounts,EmailComposeFeedback,EmailComposeHost,+ EmailConnectivity,EmailDelivery,EmailDraftStorage,PersistedEmailIdentity,@@ -40,13 +41,27 @@ import {prepareEmailBody,} from '../primitives/prepare-email-body';import { endUndoSend } from '../primitives/undo-send-claim';-import { createAttachmentPersistence } from './attachment-persistence';+import {+ createAttachmentPersistence,+ refuseAttachmentsOffline,+} from './attachment-persistence';import { createDraftAutosave } from './draft-autosave';+import {+ createDraftPersistence,+ deleteDraftForDiscard,+} from './draft-persistence';+import { createDraftSession } from './draft-session';import { createEmailSendSchedule } from './email-send-schedule';+import {+ refuseSend,+ sendRefusalAfterSave,+ sendRefusalBeforeSave,+} from './send-readiness';import { createEmailUndoStore } from './undo-store';type UndoComposeSnapshot = {draftId: string;+ threadId?: string;inboxId?: string;recipients: EmailFormRecipients;subject: string;@@ -63,6 +78,7 @@ export type EmailComposerOptions = {delivery: EmailDelivery;notices: EmailComposeFeedback;accounts: EmailComposeAccounts;+ connectivity: EmailConnectivity;viewerEmail: Accessor<string | undefined>;hasPaidAccess: Accessor<boolean>;recipients: Accessor<EmailRecipient[]>;@@ -128,16 +144,18 @@ export function createEmailComposer(props: EmailComposerOptions) {const [editor, setEditor] = createSignal<LexicalEditor | undefined>();const [content, setContent] = createSignal('');- const [currentDraftId, setCurrentDraftId] = createSignal<string | undefined>(+ // The draft's persisted identity — and whether the server has confirmed+ // it, which the REST-only send and schedule depend on. The thread it lives+ // under is part of it: switching the sending inbox re-homes the draft+ // server-side, so the previous thread's soup row must be dropped after+ // the save.+ const session = createDraftSession(initialDraftId+ ? { draftId: initialDraftId, threadId: props.draft?.thread_db_id }+ : undefined);-- // Thread the draft currently lives under; switching the sending inbox- // re-homes the draft server-side, so the previous thread's soup row must- // be dropped after the save.- const [currentThreadId, setCurrentThreadId] = createSignal<- string | undefined- >(props.draft?.thread_db_id);+ const currentDraftId = session.draftId;+ const currentThreadId = session.threadId;const attachmentPersistence = createAttachmentPersistence({services: props.attachmentStorage,@@ -152,6 +170,11 @@ export function createEmailComposer(props: EmailComposerOptions) {: undefined;if (restoredSnapshot) {+ session.dispatch({+ type: 'seeded',+ draftId: restoredSnapshot.draftId,+ threadId: restoredSnapshot.threadId,+ });form.setSelectedInbox(restoredSnapshot.inboxId);form.setRecipients('to', restoredSnapshot.recipients.to);form.setRecipients('cc', restoredSnapshot.recipients.cc);@@ -210,42 +233,34 @@ export function createEmailComposer(props: EmailComposerOptions) {};}+ const persistence = createDraftPersistence({+ session,+ drafts: props.drafts,+ attachments: attachmentPersistence,+ mintThreadHandle: true,+ onAlreadySent: () => {+ props.notices.feedback.alert('This email was already sent');+ // Discarding pauses the save that clearing schedules.+ setDiscarding(true);+ autosave.cancel();+ try {+ resetState();+ } finally {+ setDiscarding(false);+ }+ },+ });+async function persistDraft(- draftToSave: ReturnType<typeof collectDraft>,- saveInboxId: string | undefined+ draft: ReturnType<typeof collectDraft>,+ inboxId: string | undefined) {- if (!draftToSave) {- const draftId = currentDraftId();- if (draftId) {- await props.drafts.deleteDraft({- draftId: draftId,- threadId: currentThreadId(),- inboxId: saveInboxId,- });- }- setCurrentDraftId(undefined);+ if (!draft) {+ await persistence.remove({ inboxId });return;}-- const previousThreadId = currentThreadId();- const draftResponse = await props.drafts.saveDraft({- draft: {- ...draftToSave,- db_id: currentDraftId(),- },- inboxId: saveInboxId,- previousThreadId: previousThreadId,- });-- const newThreadId = draftResponse.threadId ?? undefined;- setCurrentThreadId(newThreadId);-- const draftId = draftResponse.draftId;- if (draftId) {- setCurrentDraftId(draftId);- await attachmentPersistence.upload(draftId, { inboxId: saveInboxId });- return draftId;- }+ const saved = await persistence.save({ draft, inboxId });+ return saved?.draftId;}// Edits since the composer opened; an untouched existing draft can be@@ -274,7 +289,9 @@ export function createEmailComposer(props: EmailComposerOptions) {// --- Attachment handling ---- const handleAddAttachments = (attachments: DraftFormAttachment[]) => {+ const handleAddAttachments = async (attachments: DraftFormAttachment[]) => {+ if (await refuseAttachmentsOffline(props.connectivity, props.notices))+ return;for (const attachment of attachments) {form.attachments.add(attachment);}@@ -425,30 +442,46 @@ export function createEmailComposer(props: EmailComposerOptions) {return;}+ const offline = sendRefusalBeforeSave(props.connectivity);+ if (offline) return refuseSend(props.notices, offline);+setSendPhase('preparing');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();} catch {// Draft save is best-effort; the send still works without one.}+ // Already sent from another device: the composer was reset mid-save.+ if (session.isStale(epochBeforeSave)) return;+ const identity = session.identity();+ const refusal = sendRefusalAfterSave({+ identity,+ autosaveAllowed: session.autosaveAllowed(),+ attachments: form.attachments.list(),+ // A failed REST save leaves unused handles; the send can still create the message.+ unqueuedHandleMaySend: true,+ });+ if (refusal) return refuseSend(props.notices, refusal);// Scheduling may have started while the draft save was pending.if (scheduling() || form.sendTime()) return;+ const draftId = identity.kind === 'server' ? identity.draftId : undefined;// Snapshot editor state before watermark so undo-send can restore itif (currentEditor) {const snapshotHtml = currentEditor.read(() =>$generateHtmlFromNodes(currentEditor));- const draftId = currentDraftId();if (draftId) {composeUndo.remember({inboxId: currentLink.id,draftId,+ threadId: currentThreadId(),recipients: structuredClone(unwrap(form.recipients())),subject: form.subject(),bodyHtml: snapshotHtml,@@ -490,7 +523,7 @@ export function createEmailComposer(props: EmailComposerOptions) {body_text: prepared.bodyText,body_html: prepared.bodyHtml,body_macro: bodyMacro,- db_id: currentDraftId(),+ db_id: draftId,// Backend includes the signature by default for new emails; only signal// an explicit dismiss. Omitting it falls through to the backend default.include_signature: includeSignature() ? undefined : false,@@ -499,6 +532,8 @@ export function createEmailComposer(props: EmailComposerOptions) {});completed = true;+ // The draft is sent: nothing still on the wire belongs to it.+ session.dispatch({ type: 'reset' });afterSend(result, currentLink.id);} finally {cleanupWatermark();@@ -521,7 +556,7 @@ export function createEmailComposer(props: EmailComposerOptions) {delivery: props.delivery,notices: props.notices,draftId: currentDraftId,- saveDraft: autosave.save,+ saveDraft: async () => persistence.confirmed(await autosave.save()),threadId: currentThreadId,inboxId: activeInboxId,sendTime: form.sendTime,@@ -543,7 +578,7 @@ export function createEmailComposer(props: EmailComposerOptions) {const resetState = () => {clearEmailBody(editor());setContent('');- setCurrentDraftId(undefined);+ session.dispatch({ type: 'reset' });form.clear();};@@ -557,11 +592,12 @@ export function createEmailComposer(props: EmailComposerOptions) {await autosave.settled().catch(() => {});const draftId = currentDraftId();if (draftId) {- await props.drafts.deleteDraft({- draftId,- threadId: currentThreadId(),- inboxId: activeInboxId(),- });+ await deleteDraftForDiscard(+ props.drafts,+ { draftId, threadId: currentThreadId(), inboxId: activeInboxId() },+ props.notices,+ 'This email was already sent'+ );}resetState();return true;diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.tsindex 9ecf4fdd89..3cbe831ae7 100644--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts@@ -28,6 +28,7 @@ import type {EmailAttachmentStorage,EmailComposeAccounts,EmailComposeFeedback,+ EmailConnectivity,EmailDelivery,EmailDraftStorage,EmailUndoHandle,@@ -38,8 +39,16 @@ import {convertContactInfoToEmailRecipient,convertEmailRecipientToContactInfo,} from '../core/recipient-conversion';-import { createAttachmentPersistence } from './attachment-persistence';+import {+ createAttachmentPersistence,+ refuseAttachmentsOffline,+} from './attachment-persistence';import { createDraftAutosave } from './draft-autosave';+import {+ createDraftPersistence,+ deleteDraftForDiscard,+} from './draft-persistence';+import { createDraftSession } from './draft-session';import type { DraftFormAttachment } from './email-form-state';import type { EmailFormContextValue, FormAccessKey } from './email-form-types';import { createEmailSendSchedule } from './email-send-schedule';@@ -53,6 +62,11 @@ import {} from './prepare-email-body';import { createReplyComposerFocus } from './reply-composer-focus';import { createReplyRecipientFields } from './reply-recipient-fields';+import {+ refuseSend,+ sendRefusalAfterSave,+ sendRefusalBeforeSave,+} from './send-readiness';import { endUndoSend } from './undo-send-claim';import { createEmailUndoStore } from './undo-store';@@ -81,6 +95,7 @@ export type ReplyComposerOptions = {delivery: EmailDelivery;notices: EmailComposeFeedback;accounts: EmailComposeAccounts;+ connectivity: EmailConnectivity;viewerEmail: Accessor<string | undefined>;hasPaidAccess: Accessor<boolean>;recordMention(sourceId: string, targetId: string): void;@@ -211,23 +226,22 @@ export function createReplyComposer(// remount case). It carries a just-undone send. Consumed below.const restoredSnapshot = replyUndo.takePending(undoKey);- // Switching inboxes can move a draft out of the displayed thread. Keep its- // persisted identity together for subsequent saves, discard, schedule and undo.- const [savedDraft, setSavedDraft] = createSignal<- | {- id: string;- threadId: string | undefined;- }- | undefined- >(+ // Switching inboxes can move a draft out of the displayed thread. The+ // session keeps the draft's persisted identity together for subsequent+ // saves, discard, schedule and undo — and whether the server has confirmed+ // it, which the REST-only send and schedule depend on.+ const session = createDraftSession(restoredSnapshot- ? { id: restoredSnapshot.draftId, threadId: restoredSnapshot.threadId }+ ? {+ draftId: restoredSnapshot.draftId,+ threadId: restoredSnapshot.threadId,+ }: draftSeed?.db_id- ? { id: draftSeed.db_id, threadId: draftSeed.thread_db_id }+ ? { draftId: draftSeed.db_id, threadId: draftSeed.thread_db_id }: undefined);- const savedDraftId = () => savedDraft()?.id;- const savedDraftThreadId = () => savedDraft()?.threadId;+ const savedDraftId = session.draftId;+ const savedDraftThreadId = session.threadId;// Consume the undo-send snapshot so a later composer mount doesn't restore// it again. Use bodyHtml as initialHtml for the editor, restore attachments@@ -264,7 +278,7 @@ export function createReplyComposer(const restoreMountedReply = (snapshot: UndoReplySnapshot) => {const draftId = snapshot.draftId;props.onEngaged?.();- setSavedDraft({ id: draftId, threadId: snapshot.threadId });+ session.dispatch({ type: 'seeded', draftId, threadId: snapshot.threadId });restoreEnvelope(snapshot);const currentEditor = editor();if (currentEditor && snapshot.bodyHtml) {@@ -417,23 +431,42 @@ export function createReplyComposer(inboxId: activeInboxId(),completingThread,});+ // Block the save that resetting schedules; restore on a timeout so a+ // stay-mounted input can autosave again afterwards.+ const withDeletionGuard = async (run: () => Promise<void> | void) => {+ setPendingDeletion(true);+ autosave.cancel();+ try {+ await run();+ } finally {+ setTimeout(() => {+ autosave.cancel();+ setPendingDeletion(false);+ }, 0);+ }+ };+ const persistence = createDraftPersistence({+ session,+ drafts: props.drafts,+ attachments: attachmentPersistence,+ mintThreadHandle: false,+ onAlreadySent: () => {+ props.notices.feedback.alert('This reply was already sent');+ void withDeletionGuard(() => {+ resetState();+ clearDraftState();+ });+ },+ });+async function persistDraft({- draft: draftToSave,+ draft,thread: currentThread,inboxId,completingThread,}: ReturnType<typeof captureSave>) {- if (!draftToSave) {- const draftId = savedDraftId();- if (draftId) {- await props.drafts.deleteDraft({- draftId,- threadId: savedDraftThreadId(),- inboxId,- completingThread,- });- }- setSavedDraft(undefined);+ if (!draft) {+ await persistence.remove({ inboxId, completingThread });return;}if (!currentThread) {@@ -442,42 +475,36 @@ export function createReplyComposer();return;}-- const draftResponse = await props.drafts.saveDraft({+ const saved = await persistence.save({draft: {- ...draftToSave,- db_id: savedDraftId(),+ ...draft,provider_thread_id: currentThread.provider_id,thread_db_id: currentThread.db_id,},inboxId,completingThread,- previousThreadId: savedDraftThreadId(),});-- const draftId = draftResponse.draftId;- if (draftId) {- setSavedDraft({- id: draftId,- threadId: draftResponse.threadId ?? undefined,- });- await attachmentPersistence.upload(draftId, { inboxId });-- const forwarded = form.attachments- .list()- .filter((attachment) => attachment.type === 'forwarded');- if (forwarded.length) {- await props.attachmentStorage.addForwardedAttachments({- draftId: draftId,- attachments: forwarded.map((a) => ({- attachmentId: a.attachmentId,- })),- inboxId,- });- }-- return draftId;+ if (!saved?.draftId) return;+ // Forwarded attachments wait for a committed save.+ if (saved.persistence !== 'queued') {+ await syncForwardedAttachments(saved.draftId, inboxId);}+ return saved.draftId;+ }++ async function syncForwardedAttachments(+ draftId: string,+ inboxId: string | undefined+ ) {+ const forwarded = form.attachments+ .list()+ .filter((attachment) => attachment.type === 'forwarded');+ if (!forwarded.length) return;+ await props.attachmentStorage.addForwardedAttachments({+ draftId,+ attachments: forwarded.map((a) => ({ attachmentId: a.attachmentId })),+ inboxId,+ });}const autosave = createDraftAutosave({@@ -595,11 +622,30 @@ export function createReplyComposer(// replying from search or the sent view) would be unarchived.const willMarkDone = markDone || currentThread.inbox_visible;+ const offline = sendRefusalBeforeSave(props.connectivity);+ if (offline) return refuseSend(props.notices, offline);+setSendPhase('preparing');try {// Ensure draft is saved before sending so undo-send always has a draft to restoreautosave.cancel();- await executeSaveDraft(willMarkDone);+ const epochBeforeSave = session.epoch();+ try {+ await executeSaveDraft(willMarkDone);+ } catch (error) {+ // A draft the server may not have must not be sent.+ props.notices.reportError(error);+ return refuseSend(props.notices, 'draft-not-saved');+ }+ // Already sent from another device: the composer was reset mid-save.+ if (session.isStale(epochBeforeSave)) return;+ const refusal = sendRefusalAfterSave({+ identity: session.identity(),+ autosaveAllowed: session.autosaveAllowed(),+ attachments: form.attachments.list(),+ unqueuedHandleMaySend: false,+ });+ if (refusal) return refuseSend(props.notices, refusal);// Snapshot editor state before watermark so undo-send can restore it.// Remember by draft so sends in separate composers cannot replace each other.@@ -761,8 +807,7 @@ export function createReplyComposer(}if (willMarkDone) {try {- // Stay on the sent thread: the explicit Mark done action is what- // advances to the next email, not sending a reply.+ // Sending a reply stays on the thread; explicit Mark done advances.props.onMarkDone?.({silent: true,onUndoHandle: (handle) => {@@ -795,7 +840,7 @@ export function createReplyComposer(const resetState = () => {clearEmailBody(editor());setBodyMacro('');- setSavedDraft(undefined);+ session.dispatch({ type: 'reset' });form.reset();};@@ -806,32 +851,22 @@ export function createReplyComposer(const deleteDraftAndReset = async () => {if (submitting() || pendingDeletion() || scheduling()) return;- // Keep Lexical's deferred reset notification from recreating a discarded draft.- setPendingDeletion(true);- autosave.cancel();- try {+ await withDeletionGuard(async () => {+ // A first save may still be creating the draft; delete its returned id.await autosave.settled().catch(() => {});const draftId = savedDraftId();if (draftId) {- await props.drafts.deleteDraft({- draftId,- threadId: savedDraftThreadId(),- inboxId: activeInboxId(),- });+ await deleteDraftForDiscard(+ props.drafts,+ { draftId, threadId: savedDraftThreadId(), inboxId: activeInboxId() },+ props.notices,+ 'This reply was already sent'+ );}resetState();form.setReplyAppended(false);clearDraftState();- } finally {- // Yield past any sync/microtask save scheduling triggered by resetState,- // then cancel the resulting timer and re-enable autosave. Runs on both- // success and error paths so a failed delete doesn't leave the user- // unable to save further edits.- setTimeout(() => {- autosave.cancel();- setPendingDeletion(false);- }, 0);- }+ });};const handleUserMention = (mention: UserMentionRecord) => {@@ -849,7 +884,9 @@ export function createReplyComposer(});};- const handleAddAttachments = (files: File[]) => {+ const handleAddAttachments = async (files: File[]) => {+ if (await refuseAttachmentsOffline(props.connectivity, props.notices))+ return;const currentAttachments = form.attachments.list();const attachmentsToAddByteSize = files.reduce((sum, f) => sum + f.size, 0);@@ -892,7 +929,7 @@ export function createReplyComposer(delivery: props.delivery,notices: props.notices,draftId: savedDraftId,- saveDraft: executeSaveDraft,+ saveDraft: async () => persistence.confirmed(await executeSaveDraft()),threadId: savedDraftThreadId,inboxId: activeInboxId,sendTime: form.sendTime,diff --git a/apps/web/src/features/email-compose/primitives/send-readiness.test.ts b/apps/web/src/features/email-compose/primitives/send-readiness.test.tsnew file mode 100644index 0000000000..6760ee3359--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/send-readiness.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it, vi } from 'vitest';+import type { DraftIdentity } from './draft-session';+import type { DraftFormAttachment } from './email-form-state';+import {+ refuseSend,+ sendRefusalAfterSave,+ sendRefusalBeforeSave,+} from './send-readiness';++const server: DraftIdentity = { kind: 'server', draftId: 's-1', queued: false };+const handle: DraftIdentity = { kind: 'handle', draftId: 'h-1', queued: false };++const uploaded = {+ type: 'local',+ attachmentId: 'a-1',+} as unknown as DraftFormAttachment;+const pending = { type: 'local' } as unknown as DraftFormAttachment;++const ready = {+ identity: server,+ autosaveAllowed: true,+ attachments: [uploaded],+ unqueuedHandleMaySend: false,+};++describe('sendRefusalBeforeSave', () => {+ it('refuses only while the device looks offline', () => {+ expect(sendRefusalBeforeSave({ looksOffline: () => true })).toBe('offline');+ expect(+ sendRefusalBeforeSave({ looksOffline: () => false })+ ).toBeUndefined();+ });+});++describe('sendRefusalAfterSave', () => {+ it('allows a confirmed server draft with uploaded attachments', () => {+ expect(sendRefusalAfterSave(ready)).toBeUndefined();+ });++ it('refuses while autosave is latched, whatever the identity', () => {+ expect(sendRefusalAfterSave({ ...ready, autosaveAllowed: false })).toBe(+ 'draft-not-confirmed'+ );+ expect(+ sendRefusalAfterSave({+ ...ready,+ identity: handle,+ autosaveAllowed: false,+ unqueuedHandleMaySend: true,+ })+ ).toBe('draft-not-confirmed');+ });++ it('refuses a server draft whose latest save is still queued', () => {+ expect(+ sendRefusalAfterSave({ ...ready, identity: { ...server, queued: true } })+ ).toBe('draft-not-confirmed');+ });++ it('refuses a queued handle, and an unqueued one unless the surface allows it', () => {+ expect(sendRefusalAfterSave({ ...ready, identity: handle })).toBe(+ 'draft-not-confirmed'+ );+ expect(+ sendRefusalAfterSave({+ ...ready,+ identity: handle,+ unqueuedHandleMaySend: true,+ })+ ).toBeUndefined();+ expect(+ sendRefusalAfterSave({+ ...ready,+ identity: { ...handle, queued: true },+ unqueuedHandleMaySend: true,+ })+ ).toBe('draft-not-confirmed');+ });++ it('refuses when a local attachment never received a record', () => {+ expect(+ sendRefusalAfterSave({ ...ready, attachments: [uploaded, pending] })+ ).toBe('attachment-not-uploaded');+ });++ it('checks identity before attachments', () => {+ expect(+ sendRefusalAfterSave({+ ...ready,+ identity: { ...server, queued: true },+ attachments: [pending],+ })+ ).toBe('draft-not-confirmed');+ });+});++describe('refuseSend', () => {+ it('shows one failure notice with the reason as subtext', () => {+ const failure = vi.fn();+ refuseSend(+ {+ feedback: {+ success: vi.fn(),+ failure,+ alert: vi.fn(),+ dismiss: vi.fn(),+ },+ blockingNotice: vi.fn(),+ reportError: vi.fn(),+ },+ 'attachment-not-uploaded'+ );+ expect(failure).toHaveBeenCalledWith('Failed to send email', {+ subtext: 'Attachment not uploaded',+ });+ });+});diff --git a/apps/web/src/features/email-compose/primitives/send-readiness.ts b/apps/web/src/features/email-compose/primitives/send-readiness.tsnew file mode 100644index 0000000000..d5b7b0a242--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/send-readiness.ts@@ -0,0 +1,70 @@+import type {+ EmailComposeFeedback,+ EmailConnectivity,+} from '../context/compose-capabilities';+import type { DraftIdentity } from './draft-session';+import type { DraftFormAttachment } from './email-form-state';++/**+ * Why an immediate send cannot proceed. Send is a REST call that resolves+ * server ids only and is never queued (it moves onto the durable queue in a+ * later change), so it needs the device online, a draft the server can+ * address, and every attachment uploaded.+ */+export type SendRefusal =+ | 'offline'+ | 'draft-not-saved'+ | 'draft-not-confirmed'+ | 'attachment-not-uploaded';++const SEND_REFUSAL_SUBTEXT: Record<SendRefusal, string> = {+ offline: "You're offline",+ 'draft-not-saved': 'Draft not saved',+ 'draft-not-confirmed': 'Draft still syncing, try again',+ 'attachment-not-uploaded': 'Attachment not uploaded',+};++export function refuseSend(notices: EmailComposeFeedback, reason: SendRefusal) {+ notices.feedback.failure('Failed to send email', {+ subtext: SEND_REFUSAL_SUBTEXT[reason],+ });+}++/** Offline, the pre-send save could only queue; refuse before it runs. */+export function sendRefusalBeforeSave(+ connectivity: EmailConnectivity+): SendRefusal | undefined {+ return connectivity.looksOffline() ? 'offline' : undefined;+}++/**+ * After the pre-send save: a queued-only handle cannot be addressed over+ * REST, and a local attachment without a record did not upload (its upload+ * already reported itself). A standalone compose may still send a draft+ * whose REST save failed before anything was queued or rejected.+ */+export function sendRefusalAfterSave(input: {+ identity: DraftIdentity;+ autosaveAllowed: boolean;+ attachments: readonly DraftFormAttachment[];+ unqueuedHandleMaySend: boolean;+}): SendRefusal | undefined {+ const { identity } = input;+ if (!input.autosaveAllowed) return 'draft-not-confirmed';+ if (identity.kind === 'server' && identity.queued)+ return 'draft-not-confirmed';+ if (+ identity.kind === 'handle' &&+ (!input.unqueuedHandleMaySend || identity.queued)+ ) {+ return 'draft-not-confirmed';+ }+ if (+ input.attachments.some(+ (attachment) => attachment.type === 'local' && !attachment.attachmentId+ )+ ) {+ return 'attachment-not-uploaded';+ }+ return undefined;+}diff --git a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts b/apps/web/src/features/email-compose/primitives/send-schedule.test.tsindex 5d2fa6c51b..ffdb8d091c 100644--- a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts+++ b/apps/web/src/features/email-compose/primitives/send-schedule.test.ts@@ -1,4 +1,4 @@-import { createMemo, createRoot, createSignal } from 'solid-js';+import { createSignal } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { message } from '../../email-message/tests/messages';import type {@@ -8,72 +8,14 @@ import type {import { decodeBase64Utf8 } from '../core/decode-base64';import { createComposeContext } from '../tests/capabilities';import { mountEmailComposer } from '../tests/composer';-import { createEmailEditor, setEmailEditorText } from '../tests/editor';-import { createEmailFormState } from './email-form-state';-import {- createReplyComposer,- type ReplyComposerOptions,-} from './reply-composer';--function replyComposer(- composeContext: EmailComposeContext,- replyingTo = () => message('parent'),- callbacks: Pick<ReplyComposerOptions, 'sideEffectOnSend' | 'onMarkDone'> = {}-) {- return createRoot((dispose) => {- const editor = createEmailEditor('Ready to send');- const parent = replyingTo();- const form = createEmailFormState(- {- viewerEmail: composeContext.viewerEmail,- inboxes: composeContext.accounts.inboxes,- },- { type: 'replying_to', messageId: parent.db_id },- { getMessageById: () => parent, getDraftForMessageReply: () => undefined }- );- const state = createReplyComposer(- {- ...callbacks,- ...composeContext,- focusAfterReplyRequest: () => true,- sourceEntityId: 'thread',- replyingTo,- session: {- thread: () => ({- db_id: 'thread',- link_id: 'inbox',- inbox_visible: false,- }),- recipientOptions: () => [],- isPersonalReply: () => false,- onDraftRemoved() {},- exitToThread: () => false,- replyRequest: { replyType: () => undefined, clear() {} },- },- },- () => editor,- { container: () => undefined, footer: () => undefined },- () => form- );- state.onContentChange('Ready to send');- return {- ...state,- sendActionDisabled: createMemo(state.sendActionDisabled),- dispose,- edit(text: string) {- setEmailEditorText(editor, text);- state.onContentChange(text);- },- };- });-}+import { mountReplyComposer } from '../tests/reply';function composer(kind: 'standalone' | 'reply',composeContext: EmailComposeContext) {if (kind === 'reply') {- const state = replyComposer(composeContext);+ const state = mountReplyComposer(composeContext);return {dispose: state.dispose,send: () => state.sendEmail(),@@ -94,7 +36,7 @@ describe('send and schedule ordering', () => {const context = createComposeContext();const pending = Promise.withResolvers<void>();vi.mocked(context.delivery.schedule).mockReturnValueOnce(pending.promise);- const state = replyComposer(context);+ const state = mountReplyComposer(context);const originalTo = [...state.form.recipients().to];const schedule = state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z')@@ -150,7 +92,7 @@ describe('send and schedule ordering', () => {.mockImplementationOnce((options) =>options.onUndoHandle({ id: 'second', undo: undoSecond, dispose() {} }));- const state = replyComposer(context, undefined, { onMarkDone });+ const state = mountReplyComposer(context, undefined, { onMarkDone });try {await state.sendEmail(true);const firstNotice = vi.mocked(context.notices.feedback.success).mock@@ -182,7 +124,7 @@ describe('send and schedule ordering', () => {await onUndone();});- const state = replyComposer(composeContext, undefined, {+ const state = mountReplyComposer(composeContext, undefined, {sideEffectOnSend: () => refresh,onMarkDone,});@@ -193,8 +135,6 @@ describe('send and schedule ordering', () => {.mocked(composeContext.notices.feedback.success).mock.calls.find(([text]) => text === 'Email sent');expect(onMarkDone).toHaveBeenCalledOnce();- // Sending marks the thread done in place; only the explicit Mark done- // action advances to the next email.expect(onMarkDone).toHaveBeenCalledWith(expect.objectContaining({ silent: true, navigate: false }));@@ -228,7 +168,7 @@ describe('send and schedule ordering', () => {throw failure;});- const state = replyComposer(composeContext);+ const state = mountReplyComposer(composeContext);try {await state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'));expect(composeContext.delivery.schedule).not.toHaveBeenCalled();@@ -246,12 +186,12 @@ describe('send and schedule ordering', () => {const { promise: sending, reject } =Promise.withResolvers<PersistedEmailIdentity>();vi.mocked(composeContext.delivery.sendMessage).mockReturnValueOnce(sending);- const first = replyComposer(composeContext);+ const first = mountReplyComposer(composeContext);first.edit('Older reply');const send = first.sendEmail();await vi.advanceTimersByTimeAsync(0);first.dispose();- const newer = replyComposer(composeContext);+ const newer = mountReplyComposer(composeContext);try {newer.form.setSubject('New subject');newer.edit('Newer reply');@@ -269,7 +209,7 @@ describe('send and schedule ordering', () => {const composeContext = createComposeContext();const failure = new Error('Refresh failed');const onMarkDone = vi.fn();- const state = replyComposer(composeContext, undefined, {+ const state = mountReplyComposer(composeContext, undefined, {sideEffectOnSend: async () => {throw failure;},@@ -293,7 +233,7 @@ describe('send and schedule ordering', () => {new Error('Offline'));const onMarkDone = vi.fn();- const state = replyComposer(composeContext, undefined, { onMarkDone });+ const state = mountReplyComposer(composeContext, undefined, { onMarkDone });try {state.edit('Keep my reply');await state.sendEmail(true);@@ -318,7 +258,7 @@ describe('send and schedule ordering', () => {Promise.withResolvers<PersistedEmailIdentity>();const composeContext = createComposeContext();vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(saving);- const state = replyComposer(composeContext);+ const state = mountReplyComposer(composeContext);state.edit('First version');await vi.advanceTimersByTimeAsync(500);state.edit('Final version');@@ -338,7 +278,7 @@ describe('send and schedule ordering', () => {it('flushes an unmounted editor only to its original reply target', async () => {const [target, setTarget] = createSignal(message('original'));const composeContext = createComposeContext();- const state = replyComposer(composeContext, target);+ const state = mountReplyComposer(composeContext, target);state.edit('Belongs to the original message');// Solid updates keyed parent props before disposing the previous child.setTarget(message('next'));@@ -359,7 +299,7 @@ describe('send and schedule ordering', () => {vi.mocked(composeContext.attachmentStorage.uploadAttachments).mockReturnValueOnce(uploading);- const state = replyComposer(composeContext);+ const state = mountReplyComposer(composeContext);try {state.form.setSelectedInbox('secondary');state.handleAddAttachments([new File(['attachment'], 'review.txt')]);@@ -387,7 +327,7 @@ describe('send and schedule ordering', () => {vi.mocked(composeContext.attachmentStorage.uploadAttachments).mockReturnValueOnce(uploading);- const state = replyComposer(composeContext);+ const state = mountReplyComposer(composeContext);try {state.handleAddAttachments([new File(['attachment'], 'review.txt')]);await vi.advanceTimersByTimeAsync(500);@@ -424,7 +364,7 @@ describe('send and schedule ordering', () => {vi.mocked(composeContext.drafts.deleteDraft).mockReturnValueOnce(pending);- const state = replyComposer(composeContext);+ const state = mountReplyComposer(composeContext);try {state.edit('Ready');await vi.advanceTimersByTimeAsync(500);@@ -460,7 +400,7 @@ describe('send and schedule ordering', () => {Promise.withResolvers<PersistedEmailIdentity>();const composeContext = createComposeContext();vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(saving);- const state = replyComposer(composeContext);+ const state = mountReplyComposer(composeContext);try {const attachment = {type: 'forwarded' as const,@@ -488,7 +428,7 @@ describe('send and schedule ordering', () => {Promise.withResolvers<PersistedEmailIdentity>();const composeContext = createComposeContext();vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(saving);- const state = replyComposer(composeContext);+ const state = mountReplyComposer(composeContext);try {const sending = state.sendEmail();await vi.advanceTimersByTimeAsync(0);@@ -529,7 +469,7 @@ describe('send and schedule ordering', () => {});const target = () => message(`cross-inbox-${remount}`);- let state = replyComposer(composeContext, target);+ let state = mountReplyComposer(composeContext, target);try {state.form.setSelectedInbox('secondary');state.form.setSubject('Custom reply subject');@@ -564,7 +504,7 @@ describe('send and schedule ordering', () => {}),}));- if (remount) state = replyComposer(composeContext, target);+ if (remount) state = mountReplyComposer(composeContext, target);await vi.advanceTimersByTimeAsync(0);expect(state.activeInboxId()).toBe('secondary');state.edit('Continued after undo');@@ -614,7 +554,7 @@ describe('send and schedule ordering', () => {threadId: 'thread-c',inboxId: 'c',});- const state = replyComposer(composeContext);+ const state = mountReplyComposer(composeContext);try {state.edit('Moving between inboxes');await vi.advanceTimersByTimeAsync(500);diff --git a/apps/web/src/features/email-compose/tests/capabilities.ts b/apps/web/src/features/email-compose/tests/capabilities.tsindex 8178f24d53..ff7a587a7e 100644--- a/apps/web/src/features/email-compose/tests/capabilities.ts+++ b/apps/web/src/features/email-compose/tests/capabilities.ts@@ -14,6 +14,7 @@ export function createComposeContext(): EmailComposeContext {primaryId: () => 'inbox',},viewerEmail: () => '[email protected]',+ connectivity: { looksOffline: vi.fn(() => false) },recipients: () => [],hasPaidAccess: () => true,presentation: {@@ -37,6 +38,7 @@ export function createComposeContext(): EmailComposeContext {alert: vi.fn(),dismiss: vi.fn(),},+ blockingNotice: vi.fn(async () => {}),reportError: vi.fn(),},drafts: {diff --git a/apps/web/src/features/email-compose/tests/composer.ts b/apps/web/src/features/email-compose/tests/composer.tsindex 5dec24511f..4e38c97394 100644--- a/apps/web/src/features/email-compose/tests/composer.ts+++ b/apps/web/src/features/email-compose/tests/composer.ts@@ -3,18 +3,23 @@ import type {EmailComposeContext,EmailComposeHost,} from '../context/compose-capabilities';-import { createEmailComposer } from '../primitives/email-composer';+import {+ createEmailComposer,+ type EmailComposerOptions,+} from '../primitives/email-composer';import { createEmailEditor, setEmailEditorText } from './editor';/** A blank, addressed composer with a real editor and the normal initialization callback. */export function mountEmailComposer(context: EmailComposeContext,- host?: EmailComposeHost+ host?: EmailComposeHost,+ seed?: Pick<EmailComposerOptions, 'draft' | 'draftId'>) {const root = createRoot((dispose) => ({dispose,state: createEmailComposer({...context,+ ...seed,initialTo: ['[email protected]'],host,}),diff --git a/apps/web/src/features/email-compose/tests/reply.ts b/apps/web/src/features/email-compose/tests/reply.tsnew file mode 100644index 0000000000..6d8176c336--- /dev/null+++ b/apps/web/src/features/email-compose/tests/reply.ts@@ -0,0 +1,63 @@+import { createMemo, createRoot } from 'solid-js';+import { message } from '../../email-message/tests/messages';+import type { EmailComposeContext } from '../context/compose-capabilities';+import { createEmailFormState } from '../primitives/email-form-state';+import {+ createReplyComposer,+ type ReplyComposerOptions,+} from '../primitives/reply-composer';+import { createEmailEditor, setEmailEditorText } from './editor';++/** A reply composer on a real editor, addressed to a thread of one message. */+export function mountReplyComposer(+ composeContext: EmailComposeContext,+ replyingTo = () => message('parent'),+ callbacks: Pick<ReplyComposerOptions, 'sideEffectOnSend' | 'onMarkDone'> = {}+) {+ return createRoot((dispose) => {+ const editor = createEmailEditor('Ready to send');+ const parent = replyingTo();+ const form = createEmailFormState(+ {+ viewerEmail: composeContext.viewerEmail,+ inboxes: composeContext.accounts.inboxes,+ },+ { type: 'replying_to', messageId: parent.db_id },+ { getMessageById: () => parent, getDraftForMessageReply: () => undefined }+ );+ const state = createReplyComposer(+ {+ ...callbacks,+ ...composeContext,+ focusAfterReplyRequest: () => true,+ sourceEntityId: 'thread',+ replyingTo,+ session: {+ thread: () => ({+ db_id: 'thread',+ link_id: 'inbox',+ inbox_visible: false,+ }),+ recipientOptions: () => [],+ isPersonalReply: () => false,+ onDraftRemoved() {},+ exitToThread: () => false,+ replyRequest: { replyType: () => undefined, clear() {} },+ },+ },+ () => editor,+ { container: () => undefined, footer: () => undefined },+ () => form+ );+ state.onContentChange('Ready to send');+ return {+ ...state,+ sendActionDisabled: createMemo(state.sendActionDisabled),+ dispose,+ edit(text: string) {+ setEmailEditorText(editor, text);+ state.onContentChange(text);+ },+ };+ });+}diff --git a/apps/web/src/features/email-compose/views/email-compose.tsx b/apps/web/src/features/email-compose/views/email-compose.tsxindex 580b5a050b..d450ef831f 100644--- a/apps/web/src/features/email-compose/views/email-compose.tsx+++ b/apps/web/src/features/email-compose/views/email-compose.tsx@@ -37,6 +37,7 @@ export function EmailComposeView(props: EmailComposeViewProps) {delivery: composeContext.delivery,notices: composeContext.notices,accounts: composeContext.accounts,+ connectivity: composeContext.connectivity,viewerEmail: composeContext.viewerEmail,hasPaidAccess: composeContext.hasPaidAccess,recipients: composeContext.recipients,diff --git a/apps/web/src/features/email-compose/views/reply-input.tsx b/apps/web/src/features/email-compose/views/reply-input.tsxindex d913360a79..833beed871 100644--- a/apps/web/src/features/email-compose/views/reply-input.tsx+++ b/apps/web/src/features/email-compose/views/reply-input.tsx@@ -42,6 +42,7 @@ type ReplyInputViewProps = Omit<| 'delivery'| 'notices'| 'accounts'+ | 'connectivity'| 'viewerEmail'| 'hasPaidAccess'| 'recordMention'@@ -66,6 +67,7 @@ export function ReplyInputView(props: ReplyInputViewProps) {delivery: composeContext.delivery,notices: composeContext.notices,accounts: composeContext.accounts,+ connectivity: composeContext.connectivity,viewerEmail: composeContext.viewerEmail,hasPaidAccess: composeContext.hasPaidAccess,recordMention: composeContext.recordMention,diff --git a/apps/web/src/features/email-thread/email-thread.tsx b/apps/web/src/features/email-thread/email-thread.tsxindex e487881ef3..6231c44c20 100644--- a/apps/web/src/features/email-thread/email-thread.tsx+++ b/apps/web/src/features/email-thread/email-thread.tsx@@ -36,7 +36,9 @@ export function EmailThread(props: EmailThreadProps) {const contacts = useContacts();const viewerEmail = useEmail();const user = useUserContext();- const compose = createEmailComposeContext();+ const compose = createEmailComposeContext({+ threadTransport: () => query.transport,+ });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.tsindex 871d8b4146..2e823aad7d 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@@ -33,6 +33,9 @@ describe('thread state with an injected source', () => {expect(state.drafts.getDraftForMessage('parent')).toEqual(newer);setSnapshot(thread([message('parent')]));expect(state.drafts.getDraftForMessage('parent')).toEqual(newer);+ const committed = { ...old, db_id: 'server-id' };+ setSnapshot(thread([message('parent'), committed]));+ expect(state.drafts.getDraftForMessage('parent')).toEqual(committed);state.drafts.deleteDraftForMessage('parent');setSnapshot(thread([message('parent'), newer]));expect(state.drafts.getDraftForMessage('parent')).toBeUndefined();diff --git a/apps/web/src/features/email-thread/primitives/thread-drafts.ts b/apps/web/src/features/email-thread/primitives/thread-drafts.tsindex ddb82b35e9..d760014cc8 100644--- a/apps/web/src/features/email-thread/primitives/thread-drafts.ts+++ b/apps/web/src/features/email-thread/primitives/thread-drafts.ts@@ -13,7 +13,8 @@ export function createThreadDrafts(>) {// The newest version of each reply draft seen across query snapshots,- // keyed by the replied-to message id. A cached snapshot populates this the+ // keyed by the replied-to message id. A server identity replacing a client+ // handle wins regardless of timestamp: client and server clocks can differ. A cached snapshot populates this the// moment it's available (the composer must not wait on the network), and a// later fetch upgrades an entry only when its updated_at is newer — so the// revalidation of a stale cache wins, but an out-of-order response can't@@ -33,8 +34,9 @@ export function createThreadDrafts(const nextDraft = map[messageId];if (!nextDraft ||- new Date(nextDraft.updated_at).getTime() <- new Date(prevDraft.updated_at).getTime()+ (nextDraft.db_id === prevDraft.db_id &&+ new Date(nextDraft.updated_at).getTime() <+ new Date(prevDraft.updated_at).getTime())) {map[messageId] = prevDraft;}diff --git a/apps/web/src/lib/core/util/connectivity.ts b/apps/web/src/lib/core/util/connectivity.tsnew file mode 100644index 0000000000..20ed341412--- /dev/null+++ b/apps/web/src/lib/core/util/connectivity.ts@@ -0,0 +1,17 @@+import { nativeNetworkStatus } from '@core/mobile/native-network-status';++/**+ * Best-effort "definitely offline" check across platforms: the native+ * network monitor on iOS, `navigator.onLine` elsewhere. Either may lag+ * reality — a false negative just means the guarded action attempts and+ * surfaces its own failure.+ */+export function deviceLooksOffline(): boolean {+ const native = nativeNetworkStatus();+ if (native !== 'unknown') return native === 'offline';+ // navigator.onLine decides only when the native monitor has no answer: it+ // reports false during native cold launches while the network is fine+ // (see useUserInfoQuery's networkMode), so it must not override an+ // 'online' native reading.+ return typeof navigator !== 'undefined' && navigator.onLine === false;+}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.tsindex 203cee829e..3c8bd525f6 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@@ -1,8 +1,10 @@+import { SaveEmailDraftDocument } from '@service-storage/graphql/generated/graphql';import {markGraphqlEmailThreadSeen,markGraphqlEmailThreadUnread,} from '@service-storage/graphql-email-read-state';import { executeGraphqlSetFavoriteMutation } from '@service-storage/graphql-favorites';+import { shouldRetryGraphqlMutation } from '@service-storage/graphql-mutation-retry';import {type Client,CombinedError,@@ -2344,6 +2346,87 @@ describe('normalizedCacheExchange', () => {});});+ it('retries a draft response failure with the same handles and commits after recovery', async () => {+ vi.useFakeTimers();+ try {+ const variables = {+ input: {+ draftId: 'draft-handle',+ threadDbId: 'thread-handle',+ subject: 'Saved',+ },+ };+ const saved = {+ saveEmailDraft: {+ draftId: 'server-draft',+ draft: {+ __typename: 'GraphqlSoupEmailMessage',+ id: 'server-draft',+ },+ thread: {+ __typename: 'GraphqlSoupEmailThread',+ id: 'server-thread',+ },+ },+ };+ const error = new CombinedError({+ graphQLErrors: [+ {+ message: 'attachment loading failed after commit',+ extensions: { code: 'INTERNAL', retryable: true },+ },+ ],+ });+ let attempts = 0;+ const { ops, results, forwarded } = harness(+ host,+ () => {+ attempts += 1;+ return attempts === 1+ ? { error, data: undefined }+ : { data: saved };+ },+ { shouldRetryMutation: shouldRetryGraphqlMutation }+ );+ ops.next(+ makeOperation(+ 'mutation',+ createRequest(SaveEmailDraftDocument, variables),+ makeMutationOp(1, saved).context+ )+ );+ 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(optimisticMutationDispositionOf(results[0])).toEqual({+ kind: 'queued',+ transactionId: 'txn-1',+ });+ await vi.advanceTimersByTimeAsync(1_000);++ expect(attempts).toBe(2);+ expect(forwarded.map((op) => op.variables)).toEqual([+ variables,+ variables,+ ]);+ expect(host.begins).toHaveLength(1);+ expect(host.commits).toEqual([+ expect.objectContaining({+ transactionId: 'txn-1',+ data: saved,+ }),+ ]);+ expect(host.rollbacks).toHaveLength(0);+ } finally {+ vi.useRealTimers();+ }+ });+it('accepts later local writes while a deferred offline head blocks the network', async () => {const error = new CombinedError({networkError: new Error('offline'),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.tsindex 5110a8c97e..6bc4ea1177 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@@ -964,8 +964,8 @@ export function normalizedCacheExchange(try {enqueue = await host.enqueueOptimisticMutation(args, claim);} catch (error) {- options.onCacheError?.(error, op);if (isAdmittedEnqueueUncertainError(error)) {+ options.onCacheError?.(error, op);// The old-scope queue may already contain the side effect. It is// unsafe to forward or retry without a coordinator fence.return uncertainEnqueueResult(op, error);@@ -974,9 +974,22 @@ export function normalizedCacheExchange(// not expose a partial relation move: retain entity optimism and// the post-success revalidation descriptors instead.if (args.linkPatches.length === 0) {+ options.onCacheError?.(error, op);enqueueForward(op);return undefined;}+ // Deliberately loud: this fallback is durable but invisible until+ // reconnect — the mutation's optimistic list membership silently+ // becomes eventual. A systematic rejection (schema drift, a patch+ // path the cache cannot resolve) looks identical to a transient+ // race without this trace, and production wires no onCacheError.+ const degraded = new Error(+ 'optimistic link patches rejected at enqueue; degrading to ' ++ `post-commit revalidations for ${args.operationName ?? 'mutation'}`,+ { cause: error }+ );+ console.warn(`[graphql-cache] ${degraded.message}`, error);+ options.onCacheError?.(degraded, op);try {enqueue = await host.enqueueOptimisticMutation({diff --git a/apps/web/src/lib/queries/email/draft-queue.ts b/apps/web/src/lib/queries/email/draft-queue.tsnew file mode 100644index 0000000000..0ff802f2ea--- /dev/null+++ b/apps/web/src/lib/queries/email/draft-queue.ts@@ -0,0 +1,183 @@+import { toast } from '@core/component/Toast/Toast';+import {+ enableGraphqlSoup,+ isFeatureEnabled,+} from '@core/constant/featureFlags';+import {+ readRecordsByKeys,+ selectRecords,+} from '@graphql-cache/exchange/record-selection';+import { Telemetry } from '@macro-inc/observability';+import { EmailThreadMessageFieldsFragmentDoc } from '@service-storage/graphql/generated/graphql';+import {+ getGraphqlCacheHost,+ getGraphqlSoupClient,+ graphqlCacheEnabled,+} from '@service-storage/graphql-soup';+import { queryClient } from '../client';+import {+ invalidateAllSoup,+ invalidateSoupEntity,+ refetchSoupEntity,+} from '../soup/cache';+import { markThreadDraftSaved } from './draft-cache';+import {+ executeGraphqlDeleteEmailDraft,+ executeGraphqlSaveEmailDraft,+ type GraphqlSaveEmailDraftArgs,+ type SaveEmailDraftFailureCode,+} from './graphql/draft';+import { emailKeys } from './keys';+import { fetchAndCacheThread, type ThreadQueryTransport } from './thread';++/**+ * Whether a surface's draft writes ride the durable GraphQL mutation queue,+ * where offline writes persist locally and replay as idempotent upserts+ * keyed by client handles.+ *+ * A write must use the transport the surface's thread read used: a queued+ * save against a REST-read thread has no cached page for its optimistic+ * patch, so the draft would be durable but invisible offline. Replies follow+ * their thread query's transport; a surface without one follows the soup+ * flag. The uncached fallback client has no queue, so REST remains the+ * fallback there.+ */+export function draftQueueActive(+ threadTransport?: ThreadQueryTransport+): boolean {+ if (!graphqlCacheEnabled()) return false;+ return threadTransport+ ? threadTransport === 'graphql'+ : isFeatureEnabled(enableGraphqlSoup);+}++/** A server rejection of a draft write; autosave never retries these. */+export type DraftWriteRejection = Exclude<SaveEmailDraftFailureCode, 'NETWORK'>;++export type QueuedDraftSave =+ | { kind: 'committed'; draftId: string; threadId: string }+ /** Durably accepted under the caller's handles; the server may not know them yet. */+ | { kind: 'queued' }+ | { kind: 'rejected'; code: DraftWriteRejection };++export type QueuedDraftDelete =+ | { kind: 'committed' | 'queued' }+ | { kind: 'rejected'; code: DraftWriteRejection };++const reportError = (error: unknown) =>+ Telemetry.error(error instanceof Error ? error : new Error(String(error)));++/**+ * Notices and cache repair for a failed write, matching the REST mutations'+ * onError. A transport failure throws — the write was never enqueued and the+ * next save may retry it. A draft sent from another device gets its thread+ * refreshed; the caller drops the local draft.+ */+function rejection(+ code: SaveEmailDraftFailureCode,+ message: string,+ threadId: string+): DraftWriteRejection {+ if (code === 'NETWORK') {+ toast.failure(message);+ throw new Error(`${message}: network`);+ }+ if (code === 'DRAFT_ALREADY_SENT') {+ markThreadDraftSaved(threadId);+ invalidateSoupEntity(threadId);+ void refetchSoupEntity(threadId, 'emailThread').catch(reportError);+ void fetchAndCacheThread(threadId);+ } else {+ toast.failure(message);+ reportError(new Error(`${message}: ${code}`));+ }+ return code;+}++/** Saves over the queue; a commit mirrors useSaveDraftMutation's cache effects. */+export async function saveEmailDraftQueued(input: {+ args: GraphqlSaveEmailDraftArgs;+ completingThread?: boolean;+ previousThreadId?: string;+}): Promise<QueuedDraftSave> {+ const client = getGraphqlSoupClient();+ const host = getGraphqlCacheHost();+ const cached = host+ ? await readRecordsByKeys(+ host,+ selectRecords(EmailThreadMessageFieldsFragmentDoc),+ [`GraphqlSoupEmailMessage:${input.args.draftId}`]+ )+ : undefined;+ const outcome = await executeGraphqlSaveEmailDraft(client, {+ ...input.args,+ existingDraft: cached?.records[0]?.record,+ });+ if (outcome.kind === 'failed') {+ return {+ kind: 'rejected',+ code: rejection(+ outcome.code,+ 'Failed to save draft',+ input.args.threadDbId+ ),+ };+ }+ if (outcome.kind === 'queued') return { kind: 'queued' };+ try {+ markThreadDraftSaved(outcome.threadId);+ if (input.previousThreadId && input.previousThreadId !== outcome.threadId) {+ markThreadDraftSaved(input.previousThreadId);+ invalidateSoupEntity(input.previousThreadId);+ void refetchSoupEntity(input.previousThreadId, 'emailThread').catch(+ reportError+ );+ }+ void queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });+ if (!input.completingThread) {+ void refetchSoupEntity(outcome.threadId, 'emailThread').catch(+ reportError+ );+ }+ void queryClient.invalidateQueries({+ queryKey: emailKeys.threadMessages(outcome.threadId).queryKey,+ });+ } catch (error) {+ reportError(error);+ }+ return {+ kind: 'committed',+ draftId: outcome.draftId,+ threadId: outcome.threadId,+ };+}++/** Deletes over the queue; a commit mirrors useDeleteDraftMutation's cache effects. */+export async function deleteEmailDraftQueued(input: {+ draftId: string;+ threadId: string;+ completingThread?: boolean;+}): Promise<QueuedDraftDelete> {+ const outcome = await executeGraphqlDeleteEmailDraft(getGraphqlSoupClient(), {+ draftId: input.draftId,+ threadDbId: input.threadId,+ });+ if (outcome.kind === 'failed') {+ return {+ kind: 'rejected',+ code: rejection(outcome.code, 'Failed to delete draft', input.threadId),+ };+ }+ if (outcome.kind === 'queued') return { kind: 'queued' };+ try {+ markThreadDraftSaved(input.threadId);+ void queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });+ if (!input.completingThread) {+ void refetchSoupEntity(input.threadId, 'emailThread').catch(reportError);+ invalidateAllSoup();+ }+ } catch (error) {+ reportError(error);+ }+ return { kind: 'committed' };+}diff --git a/apps/web/src/lib/queries/email/graphql/draft.test.ts b/apps/web/src/lib/queries/email/graphql/draft.test.tsnew file mode 100644index 0000000000..ebeb56db0d--- /dev/null+++ b/apps/web/src/lib/queries/email/graphql/draft.test.ts@@ -0,0 +1,99 @@+import { optimisticContextOf } from '@graphql-cache/exchange/optimistic';+import type { SaveEmailDraftMutation } from '@service-storage/graphql/generated/graphql';+import { createClient, type Operation } from '@urql/core';+import { describe, expect, it } from 'vitest';+import { map, pipe } from 'wonka';+import {+ executeGraphqlSaveEmailDraft,+ type GraphqlSaveEmailDraftArgs,+} from './draft';++const args: GraphqlSaveEmailDraftArgs = {+ draftId: '01991e2a-3111-7000-8000-000000000001',+ threadDbId: 'thread',+ senderLinkId: 'inbox',+ senderEmail: '[email protected]',+ subject: 'Updated subject',+ optimisticBodyHtml: '<p>Updated body</p>',+};+function queuedClient() {+ const operations: Operation[] = [];+ const client = createClient({+ url: 'http://example.test/graphql',+ exchanges: [+ () => (source) =>+ pipe(+ source,+ map((operation) => {+ operations.push(operation);+ return {+ operation,+ stale: false,+ hasNext: false,+ extensions: {+ normalizedCacheMutationDisposition: {+ kind: 'queued',+ transactionId: 'queued',+ },+ },+ };+ })+ ),+ ],+ });+ return { client, operations };+}++describe('optimistic draft saves', () => {+ it('preserves attachments and scheduling through offline body edits and strips client state from the wire', async () => {+ const { client, operations } = queuedClient();+ await expect(executeGraphqlSaveEmailDraft(client, args)).resolves.toEqual({+ kind: 'queued',+ transactionId: 'queued',+ });+ const first = optimisticContextOf(operations[0])+ ?.optimisticResponse as SaveEmailDraftMutation;+ const existing = {+ ...first.saveEmailDraft.draft,+ createdAt: '2026-01-01T00:00:00Z',+ scheduledSendTime: '2027-01-01T12:00:00Z',+ hasAttachments: true,+ attachmentsDraft: [+ {+ __typename: 'GraphqlSoupEmailDraftAttachment' as const,+ id: 'attachment',+ draftId: String(args.draftId),+ fileName: 'notes.txt',+ contentType: 'text/plain',+ sha: 'sha',+ size: 5,+ s3Key: 'key',+ },+ ],+ };+ await executeGraphqlSaveEmailDraft(client, {+ ...args,+ existingDraft: existing,+ });+ const variables = operations[1].variables;+ const optimistic = optimisticContextOf(operations[1])?.optimisticResponse;+ expect(variables).toEqual({+ input: {+ draftId: args.draftId,+ threadDbId: 'thread',+ subject: 'Updated subject',+ },+ });+ expect(optimistic).toMatchObject({+ saveEmailDraft: {+ draft: {+ bodyHtmlSanitized: '<p>Updated body</p>',+ attachmentsDraft: existing.attachmentsDraft,+ hasAttachments: true,+ createdAt: existing.createdAt,+ scheduledSendTime: existing.scheduledSendTime,+ },+ },+ });+ });+});diff --git a/apps/web/src/lib/queries/email/graphql/draft.ts b/apps/web/src/lib/queries/email/graphql/draft.tsnew file mode 100644index 0000000000..404492b76e--- /dev/null+++ b/apps/web/src/lib/queries/email/graphql/draft.ts@@ -0,0 +1,397 @@+import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';+import {+ executeOptimisticMutation,+ optimisticMutationDispositionOf,+ prependUnique,+ remove,+ select,+ update,+} from '@graphql-cache/exchange/optimistic';+import {+ DeleteEmailDraftDocument,+ type DeleteEmailDraftMutation,+ type DeleteEmailDraftMutationVariables,+ EmailThreadPageDocument,+ type EmailThreadPageQuery,+ type EmailThreadPageQueryVariables,+ type SaveEmailDraftContactInput,+ SaveEmailDraftDocument,+ type SaveEmailDraftInput,+ type SaveEmailDraftMutation,+ type SaveEmailDraftMutationVariables,+} from '@service-storage/graphql/generated/graphql';+import {+ type AnyVariables,+ type Client,+ CombinedError,+ type OperationResult,+} from '@urql/core';++/**+ * Input for a durable GraphQL draft save. `draftId` is the draft's handle —+ * a client-minted id (or a server id from a fetched draft) that the server+ * resolves through a caller-scoped mapping to a server-minted row, so saves+ * queued offline replay as idempotent upserts without the handle ever+ * becoming a primary key. `threadDbId` is required: this path covers reply+ * drafts, whose thread is always known.+ *+ * The `sender*` and `optimistic*` fields are client-only — they feed the+ * optimistic draft entity and are stripped from the mutation variables.+ */+export type GraphqlSaveEmailDraftArgs = Omit<+ SaveEmailDraftInput,+ 'threadDbId'+> & {+ threadDbId: string;+ /** Sending inbox id for the optimistic entity's `linkId` — the input's+ * `linkId` is deliberately absent when sending from the primary inbox. */+ senderLinkId: string;+ /** Sending address for the optimistic entity's `from`. */+ senderEmail: string;+ /** Plain (non-base64) editor HTML for the optimistic entity's+ * `bodyHtmlSanitized` — responses carry that field unencoded. Unsanitized+ * until the first commit; own-content only, composed locally. */+ optimisticBodyHtml: string | null;+ /** Preserve persisted fields this body/envelope save does not modify. */+ existingDraft?: OptimisticDraftEntity;+};++/** Maps a REST-shaped contact to the mutation's input shape. */+export function draftContactInput(contact: {+ email: string;+ name?: string | null;+ photo_url?: string | null;+}): SaveEmailDraftContactInput {+ return {+ email: contact.email,+ name: contact.name,+ photoUrl: contact.photo_url,+ };+}++/** Machine-readable failure codes set by the resolver's error taxonomy. */+export type SaveEmailDraftFailureCode =+ | 'DRAFT_ALREADY_SENT'+ | 'NOT_FOUND'+ | 'INBOX_NOT_FOUND'+ | 'UNAUTHORIZED'+ | 'INVALID'+ | 'INTERNAL'+ | 'NETWORK';++/**+ * Caller-facing outcome of one draft save. Only a committed save carries a+ * server-confirmed draft ID — a queued save has not reached the server, and+ * its eventual settlement arrives through the cache host, not this promise.+ */+export type SaveEmailDraftOutcome =+ | { kind: 'committed'; draftId: string; threadId: string }+ | { kind: 'queued'; transactionId: string }+ | { kind: 'failed'; code: SaveEmailDraftFailureCode; error: CombinedError };++function failureCode(error: CombinedError): SaveEmailDraftFailureCode {+ if (error.networkError) return 'NETWORK';+ const code = error.graphQLErrors[0]?.extensions?.code;+ switch (code) {+ case 'DRAFT_ALREADY_SENT':+ case 'NOT_FOUND':+ case 'INBOX_NOT_FOUND':+ case 'UNAUTHORIZED':+ case 'INVALID':+ return code;+ default:+ return 'INTERNAL';+ }+}++/**+ * The queued / failed / no-data disposition shared by the draft mutations;+ * a resolved payload is the caller's to shape.+ */+function settleDraftMutation<TData, TVariables extends AnyVariables, Payload>(+ result: OperationResult<TData, TVariables>,+ payload: Payload | null | undefined,+ missingDataMessage: string+):+ | { kind: 'queued'; transactionId: string }+ | { kind: 'failed'; code: SaveEmailDraftFailureCode; error: CombinedError }+ | { kind: 'resolved'; payload: Payload } {+ const disposition = optimisticMutationDispositionOf(result);+ if (disposition?.kind === 'queued') {+ return { kind: 'queued', transactionId: disposition.transactionId };+ }+ if (result.error) {+ return {+ kind: 'failed',+ code: failureCode(result.error),+ error: result.error,+ };+ }+ if (!payload) {+ return {+ kind: 'failed',+ code: 'INTERNAL',+ error: new CombinedError({+ graphQLErrors: [new Error(missingDataMessage)],+ }),+ };+ }+ return { kind: 'resolved', payload };+}++type OptimisticDraftEntity = SaveEmailDraftMutation['saveEmailDraft']['draft'];+type OptimisticContact = OptimisticDraftEntity['from'];++function optimisticContact(+ contact: SaveEmailDraftContactInput+): NonNullable<OptimisticContact> {+ return {+ email: contact.email,+ name: contact.name ?? null,+ photoUrl: contact.photoUrl ?? null,+ };+}++/**+ * Fabricates the draft as a complete message entity for the optimistic+ * layer. Completeness is the invariant: the cache serves a query only when+ * every selected field of every entity resolves, so a missing field here+ * would turn the whole thread-page read into a miss — offline, that shows+ * an unloadable thread instead of one with the draft. The mutation document+ * selects the same `EmailThreadMessageFields` fragment the thread page+ * reads, so fragment drift surfaces as a compile error in this function.+ *+ * The entity is keyed by the handle; a first save's committed response+ * arrives under the server-minted id instead. The engine skips the now+ * record-less link patch at settlement (never planting a dangling ref), so+ * the draft is briefly absent from the page until the revalidation lands —+ * subsequent saves use the adopted server id and match exactly.+ */+function optimisticDraftEntity(+ args: GraphqlSaveEmailDraftArgs+): OptimisticDraftEntity {+ const now = new Date().toISOString();+ const existing = args.existingDraft;+ return {+ __typename: 'GraphqlSoupEmailMessage',+ id: String(args.draftId),+ providerId: args.providerId ?? null,+ threadId: args.threadDbId,+ replyingToId: args.replyingToId != null ? String(args.replyingToId) : null,+ linkId: args.senderLinkId,+ subject: args.subject,+ snippet: existing?.snippet ?? null,+ internalDateTs: existing?.internalDateTs ?? null,+ sentAt: existing?.sentAt ?? null,+ isRead: true,+ isStarred: existing?.isStarred ?? false,+ isSent: false,+ isDraft: true,+ hasAttachments: existing?.hasAttachments ?? false,+ scheduledSendTime: args.sendTime ?? existing?.scheduledSendTime ?? null,+ bodyText: args.bodyText ?? null,+ bodyHtmlSanitized: args.optimisticBodyHtml,+ bodyMacro: args.bodyMacro ?? null,+ bodyReplyless: null,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,+ from: { email: args.senderEmail, name: null, photoUrl: null },+ to: (args.to ?? []).map(optimisticContact),+ cc: (args.cc ?? []).map(optimisticContact),+ bcc: (args.bcc ?? []).map(optimisticContact),+ labels: existing?.labels ?? [],+ attachments: existing?.attachments ?? [],+ attachmentsDraft: existing?.attachmentsDraft ?? [],+ attachmentsForwarded: existing?.attachmentsForwarded ?? [],+ };+}++/**+ * Execute a draft save with a durable optimistic transaction. Offline (or+ * behind a blocked queue head) the mutation persists locally and replays on+ * reconnect; until it settles, the optimistic layer holds the draft as a+ * full message entity spliced into the thread page's message list — so a+ * reopened composer (or a relaunched app) sees the draft through the+ * ordinary thread read. On commit the layer is replaced by the server's+ * records, and the persisted thread-page revalidation reconciles list+ * membership and any attachment state this record cannot know.+ */+export async function executeGraphqlSaveEmailDraft(+ client: Client,+ args: GraphqlSaveEmailDraftArgs+): Promise<SaveEmailDraftOutcome> {+ // Strip the client-only fields; only schema fields may reach the wire.+ const {+ senderLinkId: _senderLinkId,+ senderEmail: _senderEmail,+ optimisticBodyHtml: _optimisticBodyHtml,+ existingDraft: _existingDraft,+ ...input+ } = args;+ const variables: SaveEmailDraftMutationVariables = { input };+ const threadPageVariables: EmailThreadPageQueryVariables = {+ threadId: args.threadDbId,+ offset: 0,+ limit: DEFAULT_THREAD_MESSAGES_LIMIT,+ };+ const optimisticData: SaveEmailDraftMutation = {+ saveEmailDraft: {+ draftId: String(args.draftId),+ draft: optimisticDraftEntity(args),+ thread: {+ __typename: 'GraphqlSoupEmailThread',+ id: args.threadDbId,+ updatedAt: new Date().toISOString(),+ },+ },+ };++ const result = await executeOptimisticMutation(+ client,+ SaveEmailDraftDocument,+ variables,+ optimisticData,+ {+ // The draft handle is the coalescing key: a newer save of the same+ // draft safely replaces an older queued one (saves are full-state+ // snapshots), so an offline typing session holds one queue row per+ // draft instead of one per debounce tick. The delete reuses the key —+ // a discard supersedes any still-queued save.+ uuid: String(args.draftId),+ // Splice the optimistic entity into the thread page's message list so+ // draftMap sees it. Idempotent; reapplied at commit; a non-resolving+ // path is skipped and recovered by the revalidation below.+ updates: [+ update(+ select<EmailThreadPageQuery, EmailThreadPageQueryVariables>(+ EmailThreadPageDocument,+ threadPageVariables+ )+ .field('user')+ .field('emailThread')+ .field('messages'),+ prependUnique({+ __typename: 'GraphqlSoupEmailMessage',+ id: String(args.draftId),+ })+ ),+ ],+ revalidations: [+ {+ document: EmailThreadPageDocument,+ variables: threadPageVariables,+ },+ ],+ }+ ).toPromise();++ const settled = settleDraftMutation(+ result,+ result.data?.saveEmailDraft,+ 'draft save returned no data'+ );+ if (settled.kind !== 'resolved') return settled;+ return {+ kind: 'committed',+ draftId: settled.payload.draftId,+ threadId: settled.payload.thread.id,+ };+}++/** Input for a durable GraphQL draft delete. */+export type GraphqlDeleteEmailDraftArgs = {+ /** The draft to delete, by its client-generated id. */+ draftId: string;+ /** Thread the draft lives in — targets the optimistic removal from the+ * thread page's message list and the post-commit revalidation. */+ threadDbId: string;+};++/**+ * Caller-facing outcome of one draft delete. `committed.deleted` is false+ * when the server found nothing to delete — the delete is idempotent, so+ * that is success, not an error.+ */+export type DeleteEmailDraftOutcome =+ | { kind: 'committed'; deleted: boolean; threadDeleted: boolean }+ | { kind: 'queued'; transactionId: string }+ | { kind: 'failed'; code: SaveEmailDraftFailureCode; error: CombinedError };++/**+ * Execute a draft delete with a durable optimistic transaction. Offline the+ * mutation persists locally and replays on reconnect — strictly after any+ * queued saves of the same draft, so save-then-discard converges to no+ * draft. Until it settles, the optimistic layer removes the draft from the+ * thread page's message list, so a reopened thread (or relaunched app) no+ * longer shows it. The server delete is idempotent: replaying after the+ * draft is already gone succeeds as a no-op.+ */+export async function executeGraphqlDeleteEmailDraft(+ client: Client,+ args: GraphqlDeleteEmailDraftArgs+): Promise<DeleteEmailDraftOutcome> {+ const variables: DeleteEmailDraftMutationVariables = {+ input: { draftId: args.draftId },+ };+ const threadPageVariables: EmailThreadPageQueryVariables = {+ threadId: args.threadDbId,+ offset: 0,+ limit: DEFAULT_THREAD_MESSAGES_LIMIT,+ };+ const optimisticData: DeleteEmailDraftMutation = {+ deleteEmailDraft: {+ draftId: args.draftId,+ deleted: true,+ threadDeleted: false,+ },+ };++ const result = await executeOptimisticMutation(+ client,+ DeleteEmailDraftDocument,+ variables,+ optimisticData,+ {+ // Same coalescing key as the draft's saves: a discard supersedes any+ // 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.draftId,+ // Drop the draft from the thread page's message list so draftMap+ // stops seeing it. Idempotent; reapplied at commit; a non-resolving+ // path is skipped and recovered by the revalidation below.+ updates: [+ update(+ select<EmailThreadPageQuery, EmailThreadPageQueryVariables>(+ EmailThreadPageDocument,+ threadPageVariables+ )+ .field('user')+ .field('emailThread')+ .field('messages'),+ remove({+ __typename: 'GraphqlSoupEmailMessage',+ id: args.draftId,+ })+ ),+ ],+ revalidations: [+ {+ document: EmailThreadPageDocument,+ variables: threadPageVariables,+ },+ ],+ }+ ).toPromise();++ const settled = settleDraftMutation(+ result,+ result.data?.deleteEmailDraft,+ 'draft delete returned no data'+ );+ if (settled.kind !== 'resolved') return settled;+ return {+ kind: 'committed',+ deleted: settled.payload.deleted,+ threadDeleted: settled.payload.threadDeleted,+ };+}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.tsnew file mode 100644index 0000000000..ddc77d6761--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.test.ts@@ -0,0 +1,82 @@+import { CombinedError } from '@urql/core';+import { describe, expect, it } from 'vitest';+import { shouldRetryGraphqlMutation } from './graphql-mutation-retry';++describe('GraphQL mutation retries', () => {+ it.each([+ [400, false],+ [401, false],+ [403, false],+ [404, false],+ [429, false],+ [200, false],+ [500, true],+ [503, true],+ ])('handles a network error with HTTP %s', (status, expected) => {+ expect(+ shouldRetryGraphqlMutation(+ new CombinedError({+ networkError: new Error('request failed'),+ response: new Response(null, { status }),+ })+ )+ ).toBe(expected);+ });++ it('requires a network error to retry an HTTP response', () => {+ expect(+ shouldRetryGraphqlMutation(+ new CombinedError({+ response: new Response(null, { status: 503 }),+ })+ )+ ).toBe(false);+ });++ it('honors explicit GraphQL retry metadata on an HTTP error', () => {+ expect(+ shouldRetryGraphqlMutation(+ new CombinedError({+ graphQLErrors: [+ { message: 'read failed', extensions: { retryable: true } },+ ],+ response: new Response(null, { status: 400 }),+ })+ )+ ).toBe(true);+ });++ it('keeps transport failures retryable', () => {+ expect(+ shouldRetryGraphqlMutation(+ new CombinedError({ networkError: new Error('connection lost') })+ )+ ).toBe(true);+ });++ it.each(['INVALID', 'UNAUTHORIZED', 'DRAFT_ALREADY_SENT', 'INTERNAL'])(+ 'does not retry %s without explicit server permission',+ (code) => {+ expect(+ shouldRetryGraphqlMutation(+ new CombinedError({+ graphQLErrors: [{ message: 'failed', extensions: { code } }],+ })+ )+ ).toBe(false);+ }+ );++ it('does not retry a response that also contains a permanent rejection', () => {+ expect(+ shouldRetryGraphqlMutation(+ new CombinedError({+ graphQLErrors: [+ { message: 'read failed', extensions: { retryable: true } },+ { message: 'forbidden', extensions: { code: 'UNAUTHORIZED' } },+ ],+ })+ )+ ).toBe(false);+ });+});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.tsnew file mode 100644index 0000000000..8099e3a755--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.ts@@ -0,0 +1,12 @@+import type { CombinedError } from '@urql/core';++/** Keep uncertain writes queued; application errors require explicit server opt-in. */+export function shouldRetryGraphqlMutation(error: CombinedError): boolean {+ if (error.graphQLErrors.length > 0) {+ return error.graphQLErrors.every(+ (error) => error.extensions.retryable === true+ );+ }+ const status = error.response?.status;+ return error.networkError != null && (status == null || status >= 500);+}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.tsindex dcb6dad01d..52d2f4e741 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@@ -70,6 +70,7 @@ import {type SoupPropertyFieldsFragment,type SoupQuery,} from './graphql/generated/graphql';+import { shouldRetryGraphqlMutation } from './graphql-mutation-retry';import {createGraphqlSoupSubscriptionsLifecycle,createGraphqlSoupWebSocketUrlResolver,@@ -490,9 +491,9 @@ export function getGraphqlSoupClient(): Client {extractIdentity: (data) =>(data as Partial<SoupQuery | GroupSoupQuery> | undefined)?.user?.id,- // Transport failures remain queued with their optimistic layer;- // GraphQL application errors are permanent and roll back.- shouldRetryMutation: (error) => error.networkError != null,+ // Preserve the optimistic layer on transport failures and on+ // application failures the server explicitly allows us to retry.+ shouldRetryMutation: shouldRetryGraphqlMutation,}),graphqlSoupSubscriptionExchange(graphqlWsClient),fetchExchange,diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/email-draft.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/email-draft.graphqlnew file mode 100644index 0000000000..09c2958bfd--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/graphql/email-draft.graphql@@ -0,0 +1,21 @@+mutation SaveEmailDraft($input: SaveEmailDraftInput!) {+ saveEmailDraft(input: $input) {+ draftId+ draft {+ ...EmailThreadMessageFields+ }+ thread {+ __typename+ id+ updatedAt+ }+ }+}++mutation DeleteEmailDraft($input: DeleteEmailDraftInput!) {+ deleteEmailDraft(input: $input) {+ draftId+ deleted+ threadDeleted+ }+}diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.tsindex a80c27a132..1be83e2ac8 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts@@ -37,6 +37,18 @@ export type ChannelSharePolicyInput = {operation: GraphqlSharePolicyOperation;};+/** Input for deleting an email draft. */+export type DeleteEmailDraftInput = {+ /**+ * Draft handle to delete: a client-generated ID or a server ID, resolved+ * like a save's. A handle that is already gone (or was never bound — a+ * discard can replay before its draft's first save ever committed)+ * deletes nothing and still succeeds, so a delete queued offline lands+ * cleanly however late it replays.+ */+ draftId: string | number;+};+/** One entity duplication in a batch. */export type DuplicateEntityInput = {/** Optional display name for the new entity. */@@ -1134,6 +1146,73 @@ export type ReorderFavoritesInput = {favorites: Array<EntityRefInput>;};+/** One recipient of an email draft. */+export type SaveEmailDraftContactInput = {+ /** Recipient email address. */+ email: string;+ /** Recipient display name, when known. */+ name?: string | null | undefined;+ /** Recipient photo URL, when known. */+ photoUrl?: string | null | undefined;+};++/**+ * Input for creating or updating an email draft.+ *+ * The draft ID is a client-generated handle so a save queued offline stays+ * an idempotent upsert when it replays later — possibly after an app+ * restart, possibly more than once. Handles are untrusted input and never+ * become primary keys: the server resolves them through a caller-scoped+ * mapping to server-minted rows. Thread identifiers are hints: the server+ * derives authoritative thread linkage from the reply target or the+ * existing draft.+ */+export type SaveEmailDraftInput = {+ /** Bcc recipients. */+ bcc?: Array<SaveEmailDraftContactInput> | null | undefined;+ /**+ * HTML body, base64 URL-safe (no padding) encoded; the server decodes+ * and sanitizes it before storing.+ */+ bodyHtml?: string | null | undefined;+ /** Macro body. */+ bodyMacro?: string | null | undefined;+ /** Plain text body. */+ bodyText?: string | null | undefined;+ /** Cc recipients. */+ cc?: Array<SaveEmailDraftContactInput> | null | undefined;+ /**+ * Draft handle: a client-generated ID, or a server ID from a fetched+ * draft. Resolved scoped to the caller's inboxes, and bound to the+ * server row the save settles on, so replays converge on one draft.+ */+ draftId: string | number;+ /**+ * Sending inbox. Absent means the caller's primary inbox. Carried as a+ * variable (not a header) so queued offline saves replay with it.+ */+ linkId?: string | number | null | undefined;+ /** Provider-assigned draft ID, when the draft already exists upstream. */+ providerId?: string | null | undefined;+ /** Provider-assigned thread ID hint. */+ providerThreadId?: string | null | undefined;+ /** Message this draft replies to, when it is a reply. */+ replyingToId?: string | number | null | undefined;+ /** Scheduled send time (RFC 3339), when the draft is scheduled. */+ sendTime?: string | null | undefined;+ /** Draft subject line. */+ subject: string;+ /**+ * Thread handle. For replies this is a hint the server may override.+ * For compose drafts (no reply target) it is client-generated: an+ * unresolvable handle gets a fresh server-minted thread and is bound+ * to it, so saves queued offline replay against one thread.+ */+ threadDbId?: string | number | null | undefined;+ /** To recipients. */+ to?: Array<SaveEmailDraftContactInput> | null | undefined;+};+/** Input for assigning or updating an entity property. */export type SetEntityPropertyInput = {/** Identifier of the entity receiving the property. */@@ -1724,6 +1803,20 @@ export type UpdateNotificationsForEntityMutation = { updateNotificationsForEntit| { __typename: 'GraphqlTaskAssignedMetadata', taskAssignedTaskId: string, taskAssignedTaskName: string | null, taskAssignedSubType: GraphqlNotificationDocumentSubType | null, taskAssignedAssignedBy: string, taskAssignedSenderProfilePictureUrl: string | null }}> };+export type SaveEmailDraftMutationVariables = Exact<{+ input: SaveEmailDraftInput;+}>;+++export type SaveEmailDraftMutation = { saveEmailDraft: { draftId: string, draft: { __typename: 'GraphqlSoupEmailMessage', id: string, providerId: string | null, threadId: string, replyingToId: string | null, linkId: string, subject: string | null, snippet: string | null, internalDateTs: string | null, sentAt: string | null, isRead: boolean, isStarred: boolean, isSent: boolean, isDraft: boolean, hasAttachments: boolean, scheduledSendTime: string | null, bodyText: string | null, bodyHtmlSanitized: string | null, bodyMacro: string | null, bodyReplyless: string | null, createdAt: string, updatedAt: string, from: { email: string, name: string | null, photoUrl: string | null } | null, to: Array<{ email: string, name: string | null, photoUrl: string | null }>, cc: Array<{ email: string, name: string | null, photoUrl: string | null }>, bcc: Array<{ email: string, name: string | null, photoUrl: string | null }>, labels: Array<{ providerLabelId: string, name: string }>, attachments: Array<{ __typename: 'GraphqlSoupEmailMessageAttachment', id: string, providerId: string | null, filename: string | null, mimeType: string | null, sizeBytes: number | null, sfsId: string | null, contentId: string | null }>, attachmentsDraft: Array<{ __typename: 'GraphqlSoupEmailDraftAttachment', id: string, draftId: string, fileName: string, contentType: string, sha: string, size: number, s3Key: string }>, attachmentsForwarded: Array<{ __typename: 'GraphqlSoupEmailForwardedAttachment', attachmentId: string, draftId: string, providerAttachmentId: string | null, messageProviderId: string, filename: string | null, mimeType: string | null, sizeBytes: number | null }> }, thread: { __typename: 'GraphqlSoupEmailThread', id: string, updatedAt: string } } };++export type DeleteEmailDraftMutationVariables = Exact<{+ input: DeleteEmailDraftInput;+}>;+++export type DeleteEmailDraftMutation = { deleteEmailDraft: { draftId: string, deleted: boolean, threadDeleted: boolean } };+export type EmailReadStateFieldsFragment = { __typename: 'GraphqlSoupEmailThread', id: string, isRead: boolean };export type MarkEmailThreadSeenMutationVariables = Exact<{@@ -11344,6 +11437,8 @@ export const AgentSessionMentionsDocument = {"kind":"Document","definitions":[{"export const RecordChannelActivityDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RecordChannelActivity"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"RecordChannelActivityInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordChannelActivity"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}}]}}]}}]} as unknown as DocumentNode<RecordChannelActivityMutation, RecordChannelActivityMutationVariables>;export const UpdateNotificationsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateNotifications"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateNotificationsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateNotifications"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotifEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDocumentMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentMentionDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlMentionedInDocumentCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentMentionId"},"name":{"kind":"Name","value":"mentionId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRepliedToDocumentCommentThreadMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCommentedOnDocumentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelInviteMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelInviteInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageSendMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelReplyMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyUserId"},"name":{"kind":"Name","value":"userId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadParentSenderId"},"name":{"kind":"Name","value":"threadParentSenderId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCallStartedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"callStartedChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"callStartedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNewEmailMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"newEmailSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailToEmail"},"name":{"kind":"Name","value":"toEmail"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSubject"},"name":{"kind":"Name","value":"subject"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSnippet"},"name":{"kind":"Name","value":"snippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInboxReauthRequiredMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inboxReauthRequiredEmailAddress"},"name":{"kind":"Name","value":"emailAddress"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInviteToTeamMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamName"},"name":{"kind":"Name","value":"teamName"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamInviteId"},"name":{"kind":"Name","value":"teamInviteId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamRole"},"name":{"kind":"Name","value":"role"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskAssignedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskId"},"name":{"kind":"Name","value":"taskId"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskName"},"name":{"kind":"Name","value":"taskName"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedAssignedBy"},"name":{"kind":"Name","value":"assignedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"reminderReminderId"},"name":{"kind":"Name","value":"reminderId"}},{"kind":"Field","alias":{"kind":"Name","value":"reminderDescription"},"name":{"kind":"Name","value":"description"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCalendarEventReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEventId"},"name":{"kind":"Name","value":"eventId"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderOccurrenceKey"},"name":{"kind":"Name","value":"occurrenceKey"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartsAt"},"name":{"kind":"Name","value":"startsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEndsAt"},"name":{"kind":"Name","value":"endsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartDate"},"name":{"kind":"Name","value":"startDate"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTimeZone"},"name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderMinutesBefore"},"name":{"kind":"Name","value":"minutesBefore"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAiResponseMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"aiResponseSummary"},"name":{"kind":"Name","value":"summary"}},{"kind":"Field","alias":{"kind":"Name","value":"aiResponseMessageId"},"name":{"kind":"Name","value":"messageId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrStatusChangedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedStatus"},"name":{"kind":"Name","value":"status"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedAction"},"name":{"kind":"Name","value":"action"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedPreviousStatus"},"name":{"kind":"Name","value":"previousStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedHeadBranch"},"name":{"kind":"Name","value":"headBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedBaseBranch"},"name":{"kind":"Name","value":"baseBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedMergedAt"},"name":{"kind":"Name","value":"mergedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCheckRunMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckRunGithubId"},"name":{"kind":"Name","value":"checkRunGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckName"},"name":{"kind":"Name","value":"checkName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckStatus"},"name":{"kind":"Name","value":"checkStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunConclusion"},"name":{"kind":"Name","value":"conclusion"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckUrl"},"name":{"kind":"Name","value":"checkUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCompletedAt"},"name":{"kind":"Name","value":"completedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubReviewRequestedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubLogin"},"name":{"kind":"Name","value":"requestedReviewerGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubUserId"},"name":{"kind":"Name","value":"requestedReviewerGithubUserId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentKind"},"name":{"kind":"Name","value":"commentKind"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentSnippet"},"name":{"kind":"Name","value":"commentSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionLocation"},"name":{"kind":"Name","value":"location"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTextSnippet"},"name":{"kind":"Name","value":"textSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrReviewMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewGithubId"},"name":{"kind":"Name","value":"reviewGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewUrl"},"name":{"kind":"Name","value":"reviewUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewSnippet"},"name":{"kind":"Name","value":"reviewSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionSettledMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledActor"},"name":{"kind":"Name","value":"actor"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledStopReason"},"name":{"kind":"Name","value":"stopReason"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledExcerpt"},"name":{"kind":"Name","value":"excerpt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionWaitingForInputMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputQuestion"},"name":{"kind":"Name","value":"question"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionMentionedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedMentionedBy"},"name":{"kind":"Name","value":"mentionedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedActionId"},"name":{"kind":"Name","value":"actionId"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationMetadataFields"}}]}}]}}]} as unknown as DocumentNode<UpdateNotificationsMutation, UpdateNotificationsMutationVariables>;export const UpdateNotificationsForEntityDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateNotificationsForEntity"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateNotificationsForEntityInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateNotificationsForEntity"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotifEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDocumentMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentMentionDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlMentionedInDocumentCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentMentionId"},"name":{"kind":"Name","value":"mentionId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRepliedToDocumentCommentThreadMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCommentedOnDocumentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelInviteMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelInviteInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageSendMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelReplyMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyUserId"},"name":{"kind":"Name","value":"userId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadParentSenderId"},"name":{"kind":"Name","value":"threadParentSenderId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCallStartedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"callStartedChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"callStartedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNewEmailMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"newEmailSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailToEmail"},"name":{"kind":"Name","value":"toEmail"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSubject"},"name":{"kind":"Name","value":"subject"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSnippet"},"name":{"kind":"Name","value":"snippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInboxReauthRequiredMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inboxReauthRequiredEmailAddress"},"name":{"kind":"Name","value":"emailAddress"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInviteToTeamMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamName"},"name":{"kind":"Name","value":"teamName"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamInviteId"},"name":{"kind":"Name","value":"teamInviteId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamRole"},"name":{"kind":"Name","value":"role"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskAssignedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskId"},"name":{"kind":"Name","value":"taskId"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskName"},"name":{"kind":"Name","value":"taskName"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedAssignedBy"},"name":{"kind":"Name","value":"assignedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"reminderReminderId"},"name":{"kind":"Name","value":"reminderId"}},{"kind":"Field","alias":{"kind":"Name","value":"reminderDescription"},"name":{"kind":"Name","value":"description"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCalendarEventReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEventId"},"name":{"kind":"Name","value":"eventId"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderOccurrenceKey"},"name":{"kind":"Name","value":"occurrenceKey"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartsAt"},"name":{"kind":"Name","value":"startsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEndsAt"},"name":{"kind":"Name","value":"endsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartDate"},"name":{"kind":"Name","value":"startDate"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTimeZone"},"name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderMinutesBefore"},"name":{"kind":"Name","value":"minutesBefore"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAiResponseMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"aiResponseSummary"},"name":{"kind":"Name","value":"summary"}},{"kind":"Field","alias":{"kind":"Name","value":"aiResponseMessageId"},"name":{"kind":"Name","value":"messageId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrStatusChangedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedStatus"},"name":{"kind":"Name","value":"status"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedAction"},"name":{"kind":"Name","value":"action"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedPreviousStatus"},"name":{"kind":"Name","value":"previousStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedHeadBranch"},"name":{"kind":"Name","value":"headBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedBaseBranch"},"name":{"kind":"Name","value":"baseBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedMergedAt"},"name":{"kind":"Name","value":"mergedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCheckRunMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckRunGithubId"},"name":{"kind":"Name","value":"checkRunGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckName"},"name":{"kind":"Name","value":"checkName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckStatus"},"name":{"kind":"Name","value":"checkStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunConclusion"},"name":{"kind":"Name","value":"conclusion"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckUrl"},"name":{"kind":"Name","value":"checkUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCompletedAt"},"name":{"kind":"Name","value":"completedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubReviewRequestedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubLogin"},"name":{"kind":"Name","value":"requestedReviewerGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubUserId"},"name":{"kind":"Name","value":"requestedReviewerGithubUserId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentKind"},"name":{"kind":"Name","value":"commentKind"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentSnippet"},"name":{"kind":"Name","value":"commentSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionLocation"},"name":{"kind":"Name","value":"location"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTextSnippet"},"name":{"kind":"Name","value":"textSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrReviewMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewGithubId"},"name":{"kind":"Name","value":"reviewGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewUrl"},"name":{"kind":"Name","value":"reviewUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewSnippet"},"name":{"kind":"Name","value":"reviewSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionSettledMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledActor"},"name":{"kind":"Name","value":"actor"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledStopReason"},"name":{"kind":"Name","value":"stopReason"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledExcerpt"},"name":{"kind":"Name","value":"excerpt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionWaitingForInputMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputQuestion"},"name":{"kind":"Name","value":"question"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionMentionedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedMentionedBy"},"name":{"kind":"Name","value":"mentionedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedActionId"},"name":{"kind":"Name","value":"actionId"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationMetadataFields"}}]}}]}}]} as unknown as DocumentNode<UpdateNotificationsForEntityMutation, UpdateNotificationsForEntityMutationVariables>;+export const SaveEmailDraftDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SaveEmailDraft"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SaveEmailDraftInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"saveEmailDraft"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"draft"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"EmailThreadMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"thread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"EmailThreadMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"replyingToId"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"internalDateTs"}},{"kind":"Field","name":{"kind":"Name","value":"sentAt"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isStarred"}},{"kind":"Field","name":{"kind":"Name","value":"isSent"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","name":{"kind":"Name","value":"scheduledSendTime"}},{"kind":"Field","name":{"kind":"Name","value":"from"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"to"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bcc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bodyText"}},{"kind":"Field","name":{"kind":"Name","value":"bodyHtmlSanitized"}},{"kind":"Field","name":{"kind":"Name","value":"bodyMacro"}},{"kind":"Field","name":{"kind":"Name","value":"bodyReplyless"}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"sfsId"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachmentsDraft"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"fileName"}},{"kind":"Field","name":{"kind":"Name","value":"contentType"}},{"kind":"Field","name":{"kind":"Name","value":"sha"}},{"kind":"Field","name":{"kind":"Name","value":"size"}},{"kind":"Field","name":{"kind":"Name","value":"s3Key"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachmentsForwarded"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"attachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"messageProviderId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<SaveEmailDraftMutation, SaveEmailDraftMutationVariables>;+export const DeleteEmailDraftDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteEmailDraft"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"DeleteEmailDraftInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteEmailDraft"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"deleted"}},{"kind":"Field","name":{"kind":"Name","value":"threadDeleted"}}]}}]}}]} as unknown as DocumentNode<DeleteEmailDraftMutation, DeleteEmailDraftMutationVariables>;export const MarkEmailThreadSeenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MarkEmailThreadSeen"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"MarkEmailThreadSeenInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"markEmailThreadSeen"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"EmailReadStateFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"EmailReadStateFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}}]}}]} as unknown as DocumentNode<MarkEmailThreadSeenMutation, MarkEmailThreadSeenMutationVariables>;export const MarkEmailThreadUnreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MarkEmailThreadUnread"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"MarkEmailThreadUnreadInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"markEmailThreadUnread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"EmailReadStateFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"EmailReadStateFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}}]}}]} as unknown as DocumentNode<MarkEmailThreadUnreadMutation, MarkEmailThreadUnreadMutationVariables>;export const EmailThreadPageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"EmailThreadPage"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"offset"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"limit"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"emailThread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}]}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"EmailThreadPageFields"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"EmailThreadMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"replyingToId"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"internalDateTs"}},{"kind":"Field","name":{"kind":"Name","value":"sentAt"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isStarred"}},{"kind":"Field","name":{"kind":"Name","value":"isSent"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","name":{"kind":"Name","value":"scheduledSendTime"}},{"kind":"Field","name":{"kind":"Name","value":"from"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"to"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bcc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bodyText"}},{"kind":"Field","name":{"kind":"Name","value":"bodyHtmlSanitized"}},{"kind":"Field","name":{"kind":"Name","value":"bodyMacro"}},{"kind":"Field","name":{"kind":"Name","value":"bodyReplyless"}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"sfsId"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachmentsDraft"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"fileName"}},{"kind":"Field","name":{"kind":"Name","value":"contentType"}},{"kind":"Field","name":{"kind":"Name","value":"sha"}},{"kind":"Field","name":{"kind":"Name","value":"size"}},{"kind":"Field","name":{"kind":"Name","value":"s3Key"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachmentsForwarded"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"attachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"messageProviderId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"EmailThreadPageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"latestInboundMessageTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewerPermission"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAccessLevelPermission"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"accessLevel"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"messages"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"offset"},"value":{"kind":"Variable","name":{"kind":"Name","value":"offset"}}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"Variable","name":{"kind":"Name","value":"limit"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"EmailThreadMessageFields"}}]}}]}}]} as unknown as DocumentNode<EmailThreadPageQuery, EmailThreadPageQueryVariables>;diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rsindex b0d4fcf0a7..b92ea2566f 100644--- a/crates/client/cache-core/src/engine.rs+++ b/crates/client/cache-core/src/engine.rs@@ -2109,9 +2109,18 @@ impl<S: Storage> Engine<S> {let composed = effective_records(&bases, layers, &candidates);let mut effective = present_records(composed);merge_updates_into_effective(&mut effective, pending_updates);+ // Inserted references validate against a loaded record, so a+ // patch referencing a durable entity absent from the updates+ // must pull that entity's base in too. A genuinely record-less+ // key stays absent after loading and the filter below stops the+ // loop from retrying it.let missing: BTreeSet<_> = patches.iter().filter_map(|patch| missing_patch_record(&effective, patch))+ .chain(patches.iter().filter_map(|patch| {+ let inserted = patch.operation.inserted_entity_key()?;+ (!effective.contains_key(inserted)).then(|| inserted.clone())+ })).filter(|key| !candidates.contains(key)).collect();if missing.is_empty() {diff --git a/crates/client/cache-core/src/link_patch.rs b/crates/client/cache-core/src/link_patch.rsindex d38a8c9001..76f1a1d114 100644--- a/crates/client/cache-core/src/link_patch.rs+++ b/crates/client/cache-core/src/link_patch.rs@@ -114,6 +114,20 @@ impl LinkOperation {| Self::UpsertEmbeddedLink { entity_key, .. } => entity_key.borrowed(),}}++ /// The entity key this operation INSERTS a reference to, when it does.+ /// Inserted references must resolve to a normalized record: applying one+ /// against a record-less key would plant a dangling reference that turns+ /// every read of the containing query into a miss. Removals need no+ /// record — removing an absent reference is a natural no-op.+ pub fn inserted_entity_key(&self) -> Option<&EntityKey<'static>> {+ match self {+ Self::PrependUnique { entity_key } | Self::UpsertEmbeddedLink { entity_key, .. } => {+ Some(entity_key)+ }+ Self::Remove { .. } | Self::RemoveEmbeddedLink { .. } => None,+ }+ }}/// A query that should be fetched after a successful mutation settlement.@@ -172,6 +186,11 @@ pub enum LinkPatchError {/// The selected normalized record is absent.#[error("link update record `{0}` is missing")]MissingParent(EntityKey<'static>),+ /// An inserted reference targets an entity with no normalized record.+ /// Applying it would plant a dangling reference, so at settlement (skip+ /// mode) such a patch is dropped and recovered by its revalidation.+ #[error("link update inserts a reference to record-less entity `{0}`")]+ MissingLinkedRecord(EntityKey<'static>),/// The selected record field is absent.#[error("link update field `{field}` is missing on `{parent}`")]MissingField { parent: String, field: String },@@ -396,6 +415,11 @@ fn apply_one(patch: &OptimisticLinkPatch,) -> Result<(), LinkPatchError> {let resolved = resolve_target(effective, patch)?;+ if let Some(inserted) = patch.operation.inserted_entity_key()+ && !effective.contains_key(inserted)+ {+ return Err(LinkPatchError::MissingLinkedRecord(inserted.clone()));+ }let record = effective.get_mut(&resolved.parent_entity_key).ok_or_else(|| LinkPatchError::MissingParent(resolved.parent_entity_key.clone()))?;@@ -1076,6 +1100,18 @@ mod tests {(parent, record)}+ /// Record for the entity the fixtures link to. Inserted references+ /// validate against a loaded record, and the engine loads inserted+ /// keys' bases before applying, so fixtures must carry it too.+ fn linked_item() -> (EntityKey<'static>, Record) {+ (+ EntityKey("GraphqlSoupItem:task-1".into()),+ Record {+ fields: BTreeMap::from([("id".into(), CacheValue::String("task-1".into()))]),+ },+ )+ }+fn patch(bin: &str, operation: LinkOperation) -> OptimisticLinkPatch {OptimisticLinkPatch {query: QUERY.into(),@@ -1241,6 +1277,7 @@ mod tests {#[test]fn remove_and_prepend_compose_without_touching_unrelated_values() {let (parent, initial) = record();+ let (item_key, item_record) = linked_item();let mut effective = HashMap::from([(EntityKey::root(),@@ -1249,6 +1286,7 @@ mod tests {},),(parent.clone(), initial.clone()),+ (item_key, item_record),]);let mut updates = RecordUpdates::new();apply_link_patches(@@ -1296,9 +1334,71 @@ mod tests {assert_eq!(updates.len(), 1);}+ #[test]+ fn inserted_reference_requires_a_record() {+ let (parent, initial) = record();+ let base = HashMap::from([+ (+ EntityKey::root(),+ Record {+ fields: BTreeMap::from([("user".into(), CacheValue::Ref(parent.clone()))]),+ },+ ),+ (parent.clone(), initial.clone()),+ ]);+ let ghost = patch(+ "completed",+ LinkOperation::PrependUnique {+ entity_key: EntityKey("GraphqlSoupItem:ghost".into()),+ },+ );++ // Strict mode rejects the whole set: applying would plant a+ // dangling reference and turn later reads into misses.+ let mut effective = base.clone();+ let mut updates = RecordUpdates::new();+ assert_eq!(+ apply_link_patches(+ &mut effective,+ &mut updates,+ std::slice::from_ref(&ghost),+ false+ )+ .unwrap_err(),+ LinkPatchError::MissingLinkedRecord(EntityKey("GraphqlSoupItem:ghost".into()))+ );+ assert_eq!(effective.get(&parent), Some(&initial));+ assert!(updates.is_empty());++ // Skip mode (settlement, hydration) drops the not-applicable patch+ // and leaves the base untouched for the revalidation to repair.+ let mut effective = base;+ let mut updates = RecordUpdates::new();+ apply_link_patches(&mut effective, &mut updates, &[ghost], true).unwrap();+ assert_eq!(effective.get(&parent), Some(&initial));+ assert!(updates.is_empty());++ // Removing a record-less reference stays a natural no-op: a delete+ // must never require its target to still exist.+ let mut updates = RecordUpdates::new();+ apply_link_patches(+ &mut effective,+ &mut updates,+ &[patch(+ "in-progress",+ LinkOperation::Remove {+ entity_key: EntityKey("GraphqlSoupItem:ghost".into()),+ },+ )],+ false,+ )+ .unwrap();+ }+#[test]fn embedded_link_changes_create_bins_and_adjust_counts_once() {let (parent, initial) = record();+ let (item_key, item_record) = linked_item();let mut effective = HashMap::from([(EntityKey::root(),@@ -1307,6 +1407,7 @@ mod tests {},),(parent.clone(), initial),+ (item_key, item_record),]);let mut updates = RecordUpdates::new();let urgent = upsert_bin_patch("urgent");diff --git a/crates/client/cache-core/tests/email_draft_optimistic.rs b/crates/client/cache-core/tests/email_draft_optimistic.rsnew file mode 100644index 0000000000..02b6b8961c--- /dev/null+++ b/crates/client/cache-core/tests/email_draft_optimistic.rs@@ -0,0 +1,698 @@+//! Reproduces the frontend's offline draft-save flow: a cached email thread+//! page, then a queued SaveEmailDraft optimistic write that fabricates the+//! draft entity and splices it into the page's message list. The page read+//! must show the draft while the mutation is still queued — this is what+//! makes an offline-composed reply visible after leaving and reopening the+//! thread.+//!+//! Also covers settlement: committing under the same id keeps the page+//! readable with the draft in place, while committing under a different+//! (server-alias) id skips the now record-less patch — the page stays+//! readable without the draft until the revalidation lands. The skip is+//! what makes the client-id-as-lookup-column design safe.++use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult};+use cache_core::link_patch::{LinkOperation, LinkPathSegment, OptimisticLinkPatch};+use cache_core::queue::{MutationClaimRequest, MutationClaimToken};+use cache_core::store::InMemoryStorage;+use cache_core::value::EntityKey;+use pollster::block_on;+use serde_json::{Value as Json, json};++/// Shared by the page query and the mutation so a field added to one selection+/// is added to both; the test exists to cover exactly that pairing.+macro_rules! message_fields_fragment {+ () => {+ r#"fragment EmailThreadMessageFields on GraphqlSoupEmailMessage {+ __typename+ id+ providerId+ threadId+ replyingToId+ linkId+ subject+ snippet+ internalDateTs+ sentAt+ isRead+ isStarred+ isSent+ isDraft+ hasAttachments+ scheduledSendTime+ from {+ name+ photoUrl+ }+ to {+ name+ photoUrl+ }+ cc {+ name+ photoUrl+ }+ bcc {+ name+ photoUrl+ }+ labels {+ providerLabelId+ name+ }+ bodyText+ bodyHtmlSanitized+ bodyMacro+ bodyReplyless+ attachments {+ __typename+ id+ providerId+ filename+ mimeType+ sizeBytes+ sfsId+ contentId+ }+ attachmentsDraft {+ __typename+ id+ draftId+ fileName+ contentType+ sha+ size+ s3Key+ }+ attachmentsForwarded {+ __typename+ attachmentId+ draftId+ providerAttachmentId+ messageProviderId+ filename+ mimeType+ sizeBytes+ }+ createdAt+ updatedAt+}"#+ };+}++const PAGE_QUERY: &str = concat!(+ r#"+query EmailThreadPage($threadId: ID!, $offset: Int!, $limit: Int!) {+ user {+ id+ emailThread(input: { threadId: $threadId }) {+ ...EmailThreadPageFields+ }+ }+}++fragment EmailThreadPageFields on GraphqlSoupEmailThread {+ __typename+ id+ providerId+ linkId+ inboxVisible+ isRead+ projectId+ latestInboundMessageTs+ createdAt+ updatedAt+ viewerPermission {+ __typename+ ... on GraphqlAccessLevelPermission {+ accessLevel+ }+ }+ labels {+ __typename+ id+ linkId+ providerLabelId+ name+ createdAt+ messageListVisibility+ labelListVisibility+ type+ }+ messages(offset: $offset, limit: $limit) {+ ...EmailThreadMessageFields+ }+}++"#,+ message_fields_fragment!(),+);++const MUTATION: &str = concat!(+ r#"+mutation SaveEmailDraft($input: SaveEmailDraftInput!) {+ saveEmailDraft(input: $input) {+ draftId+ draft {+ ...EmailThreadMessageFields+ }+ thread {+ __typename+ id+ updatedAt+ }+ }+}++"#,+ message_fields_fragment!(),+);++fn page_variables() -> serde_json::Map<String, Json> {+ match json!({ "threadId": "thread-1", "offset": 0, "limit": 20 }) {+ Json::Object(map) => map,+ _ => unreachable!(),+ }+}++fn message(id: &str, is_draft: bool, body: &str) -> Json {+ json!({+ "__typename": "GraphqlSoupEmailMessage",+ "id": id,+ "providerId": null,+ "threadId": "thread-1",+ "replyingToId": if is_draft { json!("msg-1") } else { Json::Null },+ "linkId": "link-1",+ "subject": "Subject",+ "snippet": null,+ "internalDateTs": null,+ "sentAt": null,+ "isRead": true,+ "isStarred": false,+ "isSent": !is_draft,+ "isDraft": is_draft,+ "hasAttachments": false,+ "scheduledSendTime": null,+ "from": { "email": "[email protected]", "name": null, "photoUrl": null },+ "to": [{ "email": "[email protected]", "name": null, "photoUrl": null }],+ "cc": [],+ "bcc": [],+ "labels": [],+ "bodyText": null,+ "bodyHtmlSanitized": body,+ "bodyMacro": null,+ "bodyReplyless": null,+ "attachments": [],+ "attachmentsDraft": [],+ "attachmentsForwarded": [],+ "createdAt": "2026-08-27T00:00:00Z",+ "updatedAt": "2026-08-27T00:00:00Z"+ })+}++fn thread_page() -> Json {+ json!({+ "user": {+ "id": "user-1",+ "emailThread": {+ "__typename": "GraphqlSoupEmailThread",+ "id": "thread-1",+ "providerId": null,+ "linkId": "link-1",+ "inboxVisible": true,+ "isRead": true,+ "projectId": null,+ "latestInboundMessageTs": null,+ "createdAt": "2026-08-26T00:00:00Z",+ "updatedAt": "2026-08-27T00:00:00Z",+ "viewerPermission": {+ "__typename": "GraphqlAccessLevelPermission",+ "accessLevel": "OWNER"+ },+ "labels": [],+ "messages": [message("msg-1", false, "<p>original</p>")]+ }+ }+ })+}++fn mutation_variables() -> serde_json::Map<String, Json> {+ let value = json!({+ "input": {+ "draftId": "draft-1",+ "threadDbId": "thread-1",+ "replyingToId": "msg-1",+ "subject": "Subject",+ "to": [{ "email": "[email protected]" }],+ "bodyHtml": "PHA-b2ZmbGluZTwvcD4"+ }+ });+ match value {+ Json::Object(map) => map,+ _ => unreachable!(),+ }+}++fn mutation_response() -> Json {+ json!({+ "saveEmailDraft": {+ "draftId": "draft-1",+ "draft": message("draft-1", true, "<p>offline</p>"),+ "thread": {+ "__typename": "GraphqlSoupEmailThread",+ "id": "thread-1",+ "updatedAt": "2026-08-27T01:00:00Z"+ }+ }+ })+}++fn messages_patch() -> OptimisticLinkPatch {+ messages_patch_with(LinkOperation::PrependUnique {+ entity_key: EntityKey("GraphqlSoupEmailMessage:draft-1".into()),+ })+}++fn messages_patch_with(operation: LinkOperation) -> OptimisticLinkPatch {+ OptimisticLinkPatch {+ query: PAGE_QUERY.into(),+ operation_name: Some("EmailThreadPage".into()),+ variables_json: serde_json::to_string(&page_variables()).unwrap(),+ path: vec![+ LinkPathSegment::Field {+ field: "user".into(),+ },+ LinkPathSegment::Field {+ field: "emailThread".into(),+ },+ LinkPathSegment::Field {+ field: "messages".into(),+ },+ ],+ operation,+ }+}++const DELETE_MUTATION: &str = r#"+mutation DeleteEmailDraft($input: DeleteEmailDraftInput!) {+ deleteEmailDraft(input: $input) {+ draftId+ deleted+ threadDeleted+ }+}+"#;++fn delete_variables() -> serde_json::Map<String, Json> {+ match json!({ "input": { "draftId": "draft-1" } }) {+ Json::Object(map) => map,+ _ => unreachable!(),+ }+}++fn delete_response() -> Json {+ json!({+ "deleteEmailDraft": {+ "draftId": "draft-1",+ "deleted": true,+ "threadDeleted": false+ }+ })+}++#[test]+fn queued_draft_save_is_visible_in_the_thread_page_read() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ engine+ .write_query(+ None,+ PAGE_QUERY,+ Some("EmailThreadPage"),+ &page_variables(),+ &thread_page(),+ None,+ )+ .await+ .unwrap();++ let patches = [messages_patch()];+ engine+ .begin_optimistic_write(+ None,+ BeginOptimisticWrite {+ uuid: "11111111-1111-4111-8111-111111111101",+ query: MUTATION,+ operation_name: Some("SaveEmailDraft"),+ variables: &mutation_variables(),+ data: &mutation_response(),+ link_patches: &patches,+ revalidations: &[],+ created_at_ms: 0,+ },+ )+ .await+ .expect("optimistic draft write must enqueue with its link patch");++ let data = match engine+ .read_query(None, PAGE_QUERY, Some("EmailThreadPage"), &page_variables())+ .await+ .unwrap()+ {+ ReadResult::Hit { data } => data,+ ReadResult::Miss => panic!("thread page must stay a cache hit"),+ };++ let messages = data["user"]["emailThread"]["messages"].as_array().unwrap();+ let ids: Vec<&str> = messages.iter().map(|m| m["id"].as_str().unwrap()).collect();+ assert!(+ ids.contains(&"draft-1"),+ "queued draft must appear in the thread page read, got {ids:?}"+ );+ assert_eq!(+ data["user"]["emailThread"]["messages"]+ .as_array()+ .unwrap()+ .iter()+ .find(|m| m["id"] == "draft-1")+ .unwrap()["bodyHtmlSanitized"],+ json!("<p>offline</p>")+ );+ });+}++// The discard flow layered on the save flow: a queued DeleteEmailDraft with+// a Remove link patch must compose with the still-queued save, so an+// offline save-then-discard reads back as a thread without the draft.+// The two writes deliberately use distinct uuids: production reuses the+// draft handle so the delete REPLACES the queued save, but this test pins+// layer composition, which needs both layers present.+#[test]+fn queued_draft_delete_removes_the_draft_from_the_thread_page_read() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ engine+ .write_query(+ None,+ PAGE_QUERY,+ Some("EmailThreadPage"),+ &page_variables(),+ &thread_page(),+ None,+ )+ .await+ .unwrap();++ let save_patches = [messages_patch()];+ engine+ .begin_optimistic_write(+ None,+ BeginOptimisticWrite {+ uuid: "11111111-1111-4111-8111-111111111102",+ query: MUTATION,+ operation_name: Some("SaveEmailDraft"),+ variables: &mutation_variables(),+ data: &mutation_response(),+ link_patches: &save_patches,+ revalidations: &[],+ created_at_ms: 0,+ },+ )+ .await+ .expect("optimistic draft write must enqueue with its link patch");++ let delete_patches = [messages_patch_with(LinkOperation::Remove {+ entity_key: EntityKey("GraphqlSoupEmailMessage:draft-1".into()),+ })];+ engine+ .begin_optimistic_write(+ None,+ BeginOptimisticWrite {+ uuid: "11111111-1111-4111-8111-111111111103",+ query: DELETE_MUTATION,+ operation_name: Some("DeleteEmailDraft"),+ variables: &delete_variables(),+ data: &delete_response(),+ link_patches: &delete_patches,+ revalidations: &[],+ created_at_ms: 1,+ },+ )+ .await+ .expect("optimistic draft delete must enqueue with its link patch");++ let data = match engine+ .read_query(None, PAGE_QUERY, Some("EmailThreadPage"), &page_variables())+ .await+ .unwrap()+ {+ ReadResult::Hit { data } => data,+ ReadResult::Miss => panic!("thread page must stay a cache hit"),+ };++ let messages = data["user"]["emailThread"]["messages"].as_array().unwrap();+ let ids: Vec<&str> = messages.iter().map(|m| m["id"].as_str().unwrap()).collect();+ assert_eq!(+ ids,+ vec!["msg-1"],+ "discarded draft must not appear in the thread page read"+ );+ });+}++fn save_response_with(draft_id: &str, body: &str) -> Json {+ json!({+ "saveEmailDraft": {+ "draftId": draft_id,+ "draft": message(draft_id, true, body),+ "thread": {+ "__typename": "GraphqlSoupEmailThread",+ "id": "thread-1",+ "updatedAt": "2026-08-27T01:00:00Z"+ }+ }+ })+}++async fn claim_head(engine: &mut Engine<InMemoryStorage>) -> MutationClaimToken {+ let claimed = engine+ .claim_next_mutation(MutationClaimRequest {+ owner: "runner".into(),+ now_ms: 10,+ lease_expires_at_ms: 1_010,+ })+ .await+ .unwrap()+ .expect("queue head");+ MutationClaimToken {+ owner: "runner".into(),+ generation: claimed.lease_generation,+ }+}++fn message_ids(data: &Json) -> Vec<&str> {+ data["user"]["emailThread"]["messages"]+ .as_array()+ .unwrap()+ .iter()+ .map(|m| m["id"].as_str().unwrap())+ .collect()+}++// Settlement path of the shipped client-real-id design: the server response+// carries the SAME id the enqueued link patch references, so the reapplied+// patch points at an entity the response just wrote. The page must stay a+// hit with the draft present, now carrying server truth.+#[test]+fn committed_draft_save_with_the_same_id_keeps_the_draft_visible() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ engine+ .write_query(+ None,+ PAGE_QUERY,+ Some("EmailThreadPage"),+ &page_variables(),+ &thread_page(),+ None,+ )+ .await+ .unwrap();++ let patches = [messages_patch()];+ let (transaction, _) = engine+ .begin_optimistic_write(+ None,+ BeginOptimisticWrite {+ uuid: "11111111-1111-4111-8111-111111111104",+ query: MUTATION,+ operation_name: Some("SaveEmailDraft"),+ variables: &mutation_variables(),+ data: &mutation_response(),+ link_patches: &patches,+ revalidations: &[],+ created_at_ms: 0,+ },+ )+ .await+ .unwrap();++ let claim = claim_head(&mut engine).await;+ engine+ .commit_optimistic_write(+ transaction,+ claim,+ MUTATION,+ Some("SaveEmailDraft"),+ &mutation_variables(),+ &save_response_with("draft-1", "<p>server copy</p>"),+ )+ .await+ .unwrap();++ let data = match engine+ .read_query(None, PAGE_QUERY, Some("EmailThreadPage"), &page_variables())+ .await+ .unwrap()+ {+ ReadResult::Hit { data } => data,+ ReadResult::Miss => panic!("thread page must stay a hit after commit"),+ };+ assert_eq!(message_ids(&data), vec!["draft-1", "msg-1"]);+ assert_eq!(+ data["user"]["emailThread"]["messages"][0]["bodyHtmlSanitized"],+ json!("<p>server copy</p>"),+ "the committed read must serve the server's copy, not the optimistic one"+ );+ });+}++// The alias-id flow (client handle as a lookup key, server-minted PK): the+// enqueued link patch references the CLIENT handle, but the settlement+// response carries the entity under the SERVER id, so at commit the patch+// points at an entity with no record. The engine must treat that inserted+// reference as not-applicable — dropped in skip mode rather than reapplied+// as a dangling ref that would turn every read of the page into a miss —+// leaving the page readable (briefly without the draft) until the+// mutation's revalidation delivers the server's list. This settlement skip+// is what makes client-handle identity safe; a regression here reads as+// the Miss branch below.+#[test]+fn committed_alias_id_response_skips_the_patch_and_stays_readable() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ engine+ .write_query(+ None,+ PAGE_QUERY,+ Some("EmailThreadPage"),+ &page_variables(),+ &thread_page(),+ None,+ )+ .await+ .unwrap();++ // The optimistic layer fabricates the draft under the client id, as+ // the alias design would: the client cannot know the server id yet.+ let patches = [messages_patch_with(LinkOperation::PrependUnique {+ entity_key: EntityKey("GraphqlSoupEmailMessage:client-1".into()),+ })];+ let (transaction, _) = engine+ .begin_optimistic_write(+ None,+ BeginOptimisticWrite {+ uuid: "11111111-1111-4111-8111-111111111105",+ query: MUTATION,+ operation_name: Some("SaveEmailDraft"),+ variables: &mutation_variables(),+ data: &save_response_with("client-1", "<p>offline</p>"),+ link_patches: &patches,+ revalidations: &[],+ created_at_ms: 0,+ },+ )+ .await+ .unwrap();++ // Queued, the page read hits: the alias entity exists optimistically.+ match engine+ .read_query(None, PAGE_QUERY, Some("EmailThreadPage"), &page_variables())+ .await+ .unwrap()+ {+ ReadResult::Hit { data } => {+ assert_eq!(message_ids(&data), vec!["client-1", "msg-1"]);+ }+ ReadResult::Miss => panic!("queued alias draft must be readable"),+ }++ // Settle with the server's response: the draft entity arrives under+ // the server-minted id; nothing ever writes a `client-1` record.+ let claim = claim_head(&mut engine).await;+ engine+ .commit_optimistic_write(+ transaction,+ claim,+ MUTATION,+ Some("SaveEmailDraft"),+ &mutation_variables(),+ &save_response_with("srv-1", "<p>server copy</p>"),+ )+ .await+ .unwrap();++ // Settlement must skip the alias patch (its entity has no record):+ // the page stays a hit, listing only the server's known messages.+ match engine+ .read_query(None, PAGE_QUERY, Some("EmailThreadPage"), &page_variables())+ .await+ .unwrap()+ {+ ReadResult::Hit { data } => {+ assert_eq!(+ message_ids(&data),+ vec!["msg-1"],+ "the skipped alias patch must leave the durable list untouched"+ );+ }+ ReadResult::Miss => panic!(+ "a record-less inserted reference must be skipped at settlement, \+ never planted as a dangling ref that misses the whole page"+ ),+ }++ // The draft's brief absence ends when the mutation's persisted+ // revalidation delivers the server's fresh list.+ let mut revalidated = thread_page();+ revalidated["user"]["emailThread"]["messages"] = json!([+ message("srv-1", true, "<p>server copy</p>"),+ message("msg-1", false, "<p>original</p>"),+ ]);+ engine+ .write_query(+ None,+ PAGE_QUERY,+ Some("EmailThreadPage"),+ &page_variables(),+ &revalidated,+ None,+ )+ .await+ .unwrap();+ match engine+ .read_query(None, PAGE_QUERY, Some("EmailThreadPage"), &page_variables())+ .await+ .unwrap()+ {+ ReadResult::Hit { data } => {+ assert_eq!(message_ids(&data), vec!["srv-1", "msg-1"]);+ }+ ReadResult::Miss => panic!("the revalidation write must repair the page"),+ }+ });+}diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rsindex 22724d0394..9995658b48 100644--- a/crates/complete_graph/src/lib.rs+++ b/crates/complete_graph/src/lib.rs@@ -30,14 +30,16 @@ pub use graphql_channel::{};pub use graphql_common::GraphqlRequestParts;pub use graphql_email::{- EmailContentKey, EmailContentLoad, EmailContentLoader, EmailMutationService,- EmailServiceEmailContentReader, EmailThreadMailProjectionLoad, EmailThreadMailProjectionLoader,- EmailThreadMetadataLoad, EmailThreadMetadataLoader, GraphqlEmailLabel, GraphqlEmailLink,- GraphqlEmailLinkSettings, GraphqlEmailMutation, GraphqlEmailProvider, GraphqlEmailQuery,- GraphqlEmailSyncStatus, MarkEmailThreadSeenInput, NoOpSoupEmailContentEdgeReader,- SoupEmailContentEdgeReader, SoupEmailEdgeReader, SoupEmailThreadMailProjectionEdgeReader,- SoupEmailThreadMetadataEdgeReader, UpdateEmailThreadLabelInput, email_content_loader,- email_thread_mail_projection_loader, email_thread_metadata_loader,+ DeleteEmailDraftInput, DeleteEmailDraftPayload, EmailContentKey, EmailContentLoad,+ EmailContentLoader, EmailMutationService, EmailServiceEmailContentReader,+ EmailThreadMailProjectionLoad, EmailThreadMailProjectionLoader, EmailThreadMetadataLoad,+ EmailThreadMetadataLoader, GraphqlEmailLabel, GraphqlEmailLink, GraphqlEmailLinkSettings,+ GraphqlEmailMutation, GraphqlEmailProvider, GraphqlEmailQuery, GraphqlEmailSyncStatus,+ MarkEmailThreadSeenInput, NoOpSoupEmailContentEdgeReader, SaveEmailDraftContactInput,+ SaveEmailDraftInput, SaveEmailDraftPayload, SoupEmailContentEdgeReader, SoupEmailEdgeReader,+ SoupEmailThreadMailProjectionEdgeReader, SoupEmailThreadMetadataEdgeReader,+ UpdateEmailThreadLabelInput, email_content_loader, email_thread_mail_projection_loader,+ email_thread_metadata_loader,};pub use graphql_entity_mutation::{ChannelSharePolicyInput, DuplicateEntityInput, EntityMutationPayload, EntityMutationRoot,diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex a67783a766..e4e77d53fc 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -420,6 +420,23 @@ impl EmailService for CountingEmailService {Err(test_email_err())}+ async fn save_draft_for_user(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ _link_id: Option<Uuid>,+ _input: CreateDraftInput,+ ) -> Result<email::domain::models::SavedUserDraft, EmailErr> {+ Err(test_email_err())+ }++ async fn delete_draft_for_user(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ _draft_id: Uuid,+ ) -> Result<email::domain::models::DeletedUserDraft, EmailErr> {+ Err(test_email_err())+ }+async fn send_message(&self,_link: &Link,diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rsindex fcc3fe54e8..f5801dcb57 100644--- a/crates/complete_graph/src/sdl_test.rs+++ b/crates/complete_graph/src/sdl_test.rs@@ -103,10 +103,22 @@ fn soup_response_schema_exposes_frontend_fields() {"entityId: ID!","markEmailThreadSeen(input: MarkEmailThreadSeenInput!): GraphqlSoupEmailThread!","updateEmailThreadLabel(input: UpdateEmailThreadLabelInput!): GraphqlSoupEmailThread!",+ "saveEmailDraft(input: SaveEmailDraftInput!): SaveEmailDraftPayload!",+ "deleteEmailDraft(input: DeleteEmailDraftInput!): DeleteEmailDraftPayload!","input MarkEmailThreadSeenInput {","input UpdateEmailThreadLabelInput {","labelId: ID!","value: Boolean!",+ "input SaveEmailDraftInput {",+ "draftId: ID!",+ "input SaveEmailDraftContactInput {",+ "type SaveEmailDraftPayload {",+ "draft: GraphqlSoupEmailMessage!",+ "thread: GraphqlSoupEmailThread!",+ "input DeleteEmailDraftInput {",+ "type DeleteEmailDraftPayload {",+ "deleted: Boolean!",+ "threadDeleted: Boolean!","enum ChannelActivityType {","enum NotificationUpdateOperation {","MARK_SEEN",diff --git a/crates/email/src/domain/models/draft.rs b/crates/email/src/domain/models/draft.rsindex 4d5475032d..a9a25e17e8 100644--- a/crates/email/src/domain/models/draft.rs+++ b/crates/email/src/domain/models/draft.rs@@ -3,7 +3,10 @@ use macro_user_id::user_id::MacroUserIdStr;use serde_json::Value as JsonValue;use uuid::Uuid;+use super::attachment::{AttachmentDraft, AttachmentForwarded, MessageAttachment};use super::contact::{ContactInfo, RecipientType};+use super::label::MessageLabel;+use super::link::Link;/// Input for creating a draft message. Mirrors the fields from `MessageToSend`.#[derive(Debug, Clone)]@@ -46,6 +49,14 @@ pub struct CreateDraftInput {/// delegated inboxes; attribution (events, activity) follows the actor./// Ignored for drafts.pub actor: Option<MacroUserIdStr<'static>>,+ /// Client draft handle to bind to the final message row. Set only by+ /// user-scoped (GraphQL) saves during handle resolution — never from a+ /// request body. The binding is upserted inside the insert transaction+ /// so replayed offline saves converge on one server-minted row.+ pub draft_client_binding: Option<Uuid>,+ /// Client thread handle to bind to the final thread row; same contract+ /// as `draft_client_binding`.+ pub thread_client_binding: Option<Uuid>,}/// A draft input with all IDs resolved, ready for database insertion.@@ -83,6 +94,25 @@ pub struct ResolvedDraftInput {/// The sending user's principal string, persisted with the scheduled/// send so the eventual `message_sent` event can attribute the actor.pub actor_id: Option<String>,+ /// Client draft handle to bind to `db_id` in the insert transaction.+ pub draft_client_id: Option<Uuid>,+ /// Client thread handle to bind to `thread_db_id` in the insert+ /// transaction.+ pub thread_client_id: Option<Uuid>,+}++/// The row IDs a save actually settled on, reported back by the insert.+///+/// Usually these are the IDs the caller resolved, but a save carrying a+/// client draft handle can adopt a row a concurrent first save minted for+/// the same handle, so the caller must echo these — not its own candidates —+/// back to the client.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct SettledDraftIds {+ /// The message row the save wrote.+ pub message_db_id: Uuid,+ /// The thread that message belongs to.+ pub thread_db_id: Uuid,}/// Simplified message info used for validation queries.@@ -104,6 +134,58 @@ pub struct SimpleMessageInfo {pub is_draft: bool,}+/// A draft saved on behalf of a user, paired with the sending inbox the save+/// resolved into — transports that build a message representation of the+/// draft (the GraphQL payload) need the inbox's address for the sender.+/// Metadata and attachment collections have been loaded successfully; a failed load+/// returns an error instead of an incomplete saved draft.+#[derive(Clone)]+pub struct SavedUserDraft {+ /// The created or updated draft.+ pub draft: CreatedDraft,+ /// The inbox the draft was saved into.+ pub link: Link,+ /// Persisted creation time; updating a draft does not reset it.+ pub created_at: DateTime<Utc>,+ /// Persisted modification time after the save.+ pub updated_at: DateTime<Utc>,+ /// Persisted labels, loaded after saving.+ pub labels: Vec<MessageLabel>,+ /// Persisted provider attachments, loaded after saving.+ pub attachments: Vec<MessageAttachment>,+ /// Persisted uploaded draft attachments, loaded after saving.+ pub attachments_draft: Vec<AttachmentDraft>,+ /// Persisted forwarded attachments, loaded after saving.+ pub attachments_forwarded: Vec<AttachmentForwarded>,+}++/// Persisted message timestamps used when returning an updated draft.+#[derive(Debug, Clone, Copy)]+pub struct MessageTimestamps {+ /// When the message was first stored.+ pub created_at: DateTime<Utc>,+ /// When the stored message was last updated.+ pub updated_at: DateTime<Utc>,+}++/// What an applied guarded draft delete removed beyond the draft row.+#[derive(Debug, Clone, Copy)]+pub struct DraftDeletion {+ /// Whether deleting the draft emptied its thread and removed it too.+ pub thread_deleted: bool,+}++/// Outcome of a user-scoped draft deletion. Deletes are idempotent: a replay+/// after the row is already gone reports `deleted: false` instead of failing,+/// so a queued offline delete lands cleanly no matter how late it arrives.+#[derive(Debug, Clone, Copy)]+pub struct DeletedUserDraft {+ /// Whether a draft row was actually deleted.+ pub deleted: bool,+ /// Whether the delete emptied the draft's thread and removed it too.+ pub thread_deleted: bool,+}+/// The result of creating a draft.#[derive(Debug, Clone)]pub struct CreatedDraft {diff --git a/crates/email/src/domain/models/error.rs b/crates/email/src/domain/models/error.rsindex 2c99dcc07f..a4f47de424 100644--- a/crates/email/src/domain/models/error.rs+++ b/crates/email/src/domain/models/error.rs@@ -17,6 +17,10 @@ pub enum EmailErr {/// The referenced message was not found.#[error("Message with id {0} not found")]MessageNotFound(Uuid),+ /// No sending inbox could be resolved: the requested link is not+ /// accessible to the caller, or the caller has no primary inbox.+ #[error("Email inbox not found")]+ InboxNotFound,/// The referenced message has already been sent and cannot be modified.#[error("Message with id {0} has already been sent")]MessageAlreadySent(Uuid),diff --git a/crates/email/src/domain/models/mod.rs b/crates/email/src/domain/models/mod.rsindex ba3fe09e51..90b0c15cbc 100644--- a/crates/email/src/domain/models/mod.rs+++ b/crates/email/src/domain/models/mod.rs@@ -18,7 +18,8 @@ mod tests;pub use attachment::{Attachment, AttachmentDraft, AttachmentForwarded, MessageAttachment};pub use contact::{Contact, ContactInfo, RecipientType};pub use draft::{- CreateDraftInput, CreatedDraft, ParsedAddresses, ResolvedDraftInput, SimpleMessageInfo,+ CreateDraftInput, CreatedDraft, DeletedUserDraft, DraftDeletion, MessageTimestamps,+ ParsedAddresses, ResolvedDraftInput, SavedUserDraft, SettledDraftIds, SimpleMessageInfo,UpsertedContacts, UpsertedRecipient,};pub use email_filter::{EmailFilter, UpsertEmailFilterInput};diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rsindex cbdf85c9b3..f50ac32895 100644--- a/crates/email/src/domain/ports.rs+++ b/crates/email/src/domain/ports.rs@@ -1,10 +1,11 @@use crate::domain::models::{Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,- CreatedDraft, EmailErr, EmailFilter, EmailInboxDetails, EmailThreadMailProjection,- EmailThreadMetadata, EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest, Label,- Link, LinkLabel, Message, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses,- ParsedMessage, ParsedThread, PreviewCursorQuery, RecipientType, ResolvedDraftInput,- SenderPolicy, SimpleMessage, SimpleMessageInfo, Thread, ThreadRow, UpdateThreadLabelsResult,+ CreatedDraft, DeletedUserDraft, DraftDeletion, EmailErr, EmailFilter, EmailInboxDetails,+ EmailThreadMailProjection, EmailThreadMetadata, EmailThreadPreview, EnrichedEmailThreadPreview,+ GetEmailsRequest, Label, Link, LinkLabel, Message, MessageAttachment, MessageLabel, MessageRow,+ MessageTimestamps, ParsedAddresses, ParsedMessage, ParsedThread, PreviewCursorQuery,+ RecipientType, ResolvedDraftInput, SavedUserDraft, SenderPolicy, SettledDraftIds,+ SimpleMessage, SimpleMessageInfo, Thread, ThreadRow, UpdateThreadLabelsResult,UpsertEmailFilterInput, UpsertedContacts, UserEmailLink, UserProvider,};use chrono::{DateTime, Utc};@@ -199,6 +200,13 @@ pub trait EmailRepo: Send + Sync + 'static {message_ids: &[Uuid],) -> impl Future<Output = Result<HashMap<Uuid, Vec<MessageLabel>>, Self::Err>> + Send;+ /// Fetch persisted message timestamps, scoped to the sending inbox.+ fn message_timestamps(+ &self,+ message_id: Uuid,+ link_id: Uuid,+ ) -> impl Future<Output = Result<Option<MessageTimestamps>, Self::Err>> + Send;+/// Fetch provider attachments for a set of message IDs, keyed by message ID.fn attachments_by_message_ids(&self,@@ -232,6 +240,23 @@ pub trait EmailRepo: Send + Sync + 'static {link_ids: &[Uuid],) -> impl Future<Output = Result<Option<SimpleMessageInfo>, Self::Err>> + Send;+ /// Resolve a client draft handle to its server-minted message ID through+ /// the mapping table, scoped to the caller's inboxes — identical handles+ /// from different users never interact.+ fn message_id_for_client_draft_id(+ &self,+ client_id: Uuid,+ link_ids: &[Uuid],+ ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;++ /// Resolve a client thread handle to its server-minted thread ID through+ /// the mapping table, scoped to the caller's inboxes.+ fn thread_id_for_client_thread_id(+ &self,+ client_id: Uuid,+ link_ids: &[Uuid],+ ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;+/// Find an existing draft that replies to the given message ID.fn get_draft_replying_to(&self,@@ -243,11 +268,18 @@ pub trait EmailRepo: Send + Sync + 'static {/// A surviving thread gets its denormalized metadata (inbox visibility,/// latest timestamps, is_signal) recomputed, since drafts count toward/// those fields.+ ///+ /// Ownership is enforced in the DELETE's WHERE clause — the row must be+ /// an unsent draft in `thread_db_id` belonging to one of `link_ids` —+ /// so a raced validation read can never delete someone else's row.+ /// Returns `None` when no row matched (already deleted, sent, or not+ /// owned): deletes are idempotent, classification is the caller's job.fn delete_draft_message(&self,message_id: Uuid,thread_db_id: Uuid,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ link_ids: &[Uuid],+ ) -> impl Future<Output = Result<Option<DraftDeletion>, Self::Err>> + Send;/// Upsert contacts from the parsed addresses. Must be called outside a transaction/// to avoid deadlocks (contacts are shared across messages).@@ -258,8 +290,21 @@ pub trait EmailRepo: Send + Sync + 'static {) -> impl Future<Output = Result<UpsertedContacts, Self::Err>> + Send;/// Insert a message within a transaction, including thread insert (if new),- /// recipients, scheduled message handling, thread metadata update, and user history.- /// If `new_thread` is Some, the thread is created inside the same transaction.+ /// recipients, scheduled message handling, thread metadata update, user+ /// history, and any client-handle bindings the input carries (upserted so+ /// replayed offline saves converge on the final row).+ ///+ /// A draft client handle is locked for the transaction and its binding+ /// re-read under that lock, so concurrent first saves of one handle settle+ /// on a single message and thread instead of each minting their own. The+ /// returned IDs are therefore the authoritative ones — a save that adopted+ /// a concurrent winner's row settled on IDs its own input never named.+ ///+ /// Returns `None` (rolling the transaction back) when the upsert's owner+ /// guard rejected the write: the message ID already exists but belongs to+ /// another inbox or is no longer an unsent draft. Defense-in-depth behind+ /// the handle resolution — validation reads can be raced, the guarded+ /// conflict clause cannot.fn insert_message(&self,input: &ResolvedDraftInput,@@ -267,7 +312,7 @@ pub trait EmailRepo: Send + Sync + 'static {link_id: Uuid,new_thread: Option<ThreadRow>,is_draft: bool,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<Option<SettledDraftIds>, Self::Err>> + Send;/// Fetch a label by its database ID and link ID.fn get_label_by_id(@@ -569,6 +614,33 @@ pub trait EmailService: Send + Sync + 'static {input: CreateDraftInput,) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;+ /// Create or update a draft for the authenticated user, resolving the+ /// sending inbox from `link_id` (or the caller's primary inbox when+ /// `None`). Lets transports without the `X-Email-Link-Id` header (the+ /// GraphQL mutation, whose offline replay persists only variables) target+ /// an inbox by value. The input's `db_id`/`thread_db_id` are client+ /// handles here — resolved through the caller-scoped mapping tables and+ /// bound to server-minted rows, never used as primary keys.+ fn save_draft_for_user(+ &self,+ macro_id: MacroUserIdStr<'_>,+ link_id: Option<Uuid>,+ input: CreateDraftInput,+ ) -> impl Future<Output = Result<SavedUserDraft, EmailErr>> + Send;++ /// Delete a draft for the authenticated user, searching every inbox they+ /// can reach. `draft_id` is a handle resolved like a save's: through the+ /// caller-scoped mapping, else as a server ID. Idempotent: a handle that+ /// resolves to nothing (or to a row that is not theirs — reported+ /// identically to avoid an existence oracle) is a successful no-op, so a+ /// delete queued offline lands cleanly however late it replays. Deleting+ /// a draft that has since been sent fails with `MessageAlreadySent`.+ fn delete_draft_for_user(+ &self,+ macro_id: MacroUserIdStr<'_>,+ draft_id: Uuid,+ ) -> impl Future<Output = Result<DeletedUserDraft, EmailErr>> + Send;+/// Send a message: persist it and enqueue for scheduled delivery./// `accessible_inboxes` is every inbox the caller can reach (own +/// delegated); a reply target may live in any of them, not just `link`.@@ -838,6 +910,23 @@ impl EmailService for NoOpEmailService {Err(no_op_email_err())}+ async fn save_draft_for_user(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ _link_id: Option<Uuid>,+ _input: CreateDraftInput,+ ) -> Result<SavedUserDraft, EmailErr> {+ Err(no_op_email_err())+ }++ async fn delete_draft_for_user(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ _draft_id: Uuid,+ ) -> Result<DeletedUserDraft, EmailErr> {+ Err(no_op_email_err())+ }+async fn send_message(&self,_link: &Link,diff --git a/crates/email/src/domain/service.rs b/crates/email/src/domain/service.rsindex 401e9386e0..6cc0381979 100644--- a/crates/email/src/domain/service.rs+++ b/crates/email/src/domain/service.rs@@ -278,6 +278,24 @@ where.await}+ async fn save_draft_for_user(+ &self,+ macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ link_id: Option<uuid::Uuid>,+ input: CreateDraftInput,+ ) -> Result<crate::domain::models::SavedUserDraft, EmailErr> {+ self.save_draft_for_user_impl(macro_id, link_id, input)+ .await+ }++ async fn delete_draft_for_user(+ &self,+ macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ draft_id: uuid::Uuid,+ ) -> Result<crate::domain::models::DeletedUserDraft, EmailErr> {+ self.delete_draft_for_user_impl(macro_id, draft_id).await+ }+async fn send_message(&self,link: &Link,diff --git a/crates/email/src/domain/service/draft.rs b/crates/email/src/domain/service/draft.rsindex 90f3cede3c..48b1a8ba16 100644--- a/crates/email/src/domain/service/draft.rs+++ b/crates/email/src/domain/service/draft.rs@@ -1,7 +1,7 @@use crate::domain::{models::{- CreateDraftInput, CreatedDraft, EmailErr, Link, ParsedAddresses, ResolvedDraftInput,- SimpleMessageInfo, ThreadRow,+ CreateDraftInput, CreatedDraft, DeletedUserDraft, EmailErr, Link, ParsedAddresses,+ ResolvedDraftInput, SavedUserDraft, SimpleMessageInfo, ThreadRow,},ports::EmailRepo,};@@ -34,6 +34,227 @@ where.await}+ #[tracing::instrument(err, skip(self, input))]+ pub(crate) async fn save_draft_for_user_impl(+ &self,+ macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ link_id: Option<Uuid>,+ mut input: CreateDraftInput,+ ) -> Result<SavedUserDraft, EmailErr> {+ let accessible_inboxes = self+ .email_repo+ .inboxes_for_macro_id(macro_id.clone())+ .await+ .map_err(anyhow::Error::from)?;+ let link = resolve_target_link(&accessible_inboxes, link_id, ¯o_id)?.clone();+ let accessible_link_ids: Vec<Uuid> = accessible_inboxes.iter().map(|l| l.id).collect();+ self.resolve_client_handles(&mut input, &accessible_link_ids)+ .await?;+ let mut draft = self+ .create_draft_impl(&link, &accessible_inboxes, input)+ .await?;+ let message_ids = [draft.db_id];+ let (+ mut attachments,+ mut attachments_draft,+ mut attachments_forwarded,+ mut send_times,+ timestamps,+ mut labels,+ ) = tokio::try_join!(+ self.email_repo.attachments_by_message_ids(&message_ids),+ self.email_repo+ .draft_attachments_by_message_ids(&message_ids),+ self.email_repo+ .forwarded_attachments_by_message_ids(&message_ids),+ self.email_repo+ .scheduled_send_times_by_message_ids(&message_ids),+ self.email_repo+ .message_timestamps(draft.db_id, draft.link_id),+ self.email_repo.labels_by_message_ids(&message_ids),+ )+ .map_err(anyhow::Error::from)?;+ let timestamps =+ timestamps.ok_or_else(|| anyhow::anyhow!("saved draft metadata is unavailable"))?;++ // Autosaves leave scheduling untouched. Return the stored schedule,+ // not the usually absent input, so normalized cache writes preserve it.+ draft.send_time = send_times.remove(&draft.db_id);++ Ok(SavedUserDraft {+ created_at: timestamps.created_at,+ updated_at: timestamps.updated_at,+ labels: labels.remove(&draft.db_id).unwrap_or_default(),+ attachments: attachments.remove(&draft.db_id).unwrap_or_default(),+ attachments_draft: attachments_draft.remove(&draft.db_id).unwrap_or_default(),+ attachments_forwarded: attachments_forwarded+ .remove(&draft.db_id)+ .unwrap_or_default(),+ draft,+ link,+ })+ }++ /// Resolve the user-scoped save's client handles into server IDs.+ ///+ /// GraphQL saves carry client-generated identity so offline replays stay+ /// idempotent — but a client-supplied ID must never become a primary key+ /// in the shared email tables. Each handle resolves through its mapping+ /// table (scoped to the caller's inboxes, so identical handles from+ /// different users never interact); an unmapped handle that happens to+ /// name an accessible row is treated as a server ID from a fetched draft+ /// and bound to itself; anything else stays unresolved and gets a+ /// server-minted row, with the binding recorded in the same transaction+ /// as the insert. Resolution reads are advisory — they run outside that+ /// transaction and cannot see a concurrent first save's pending binding.+ /// The race-proof enforcement is inside it: the per-handle lock and the+ /// re-read it guards converge concurrent first saves on one row, and the+ /// upsert's owner guard rejects a write the resolution shouldn't have+ /// reached.+ async fn resolve_client_handles(+ &self,+ input: &mut CreateDraftInput,+ accessible_link_ids: &[Uuid],+ ) -> Result<(), EmailErr> {+ if let Some(handle) = input.db_id {+ // Bind on every save, hit or miss: a sender switch deletes and+ // recreates the row, cascading the old binding away — the+ // insert's binding upsert re-points the handle at whatever row+ // the save converges on.+ input.draft_client_binding = Some(handle);+ match self+ .email_repo+ .message_id_for_client_draft_id(handle, accessible_link_ids)+ .await+ .map_err(anyhow::Error::from)?+ {+ Some(message_id) => input.db_id = Some(message_id),+ None => {+ let is_server_id = self+ .email_repo+ .get_simple_message(handle, accessible_link_ids)+ .await+ .map_err(anyhow::Error::from)?+ .is_some();+ if !is_server_id {+ input.db_id = None;+ }+ }+ }+ }+ // Thread handles are a compose concern: replies derive their thread+ // from the reply target, and binding the reply's server-thread hint+ // here would write junk mapping rows — or, for a cross-inbox reply,+ // map the original thread's ID onto the newly created thread.+ if input.replying_to_id.is_none()+ && let Some(handle) = input.thread_db_id+ {+ input.thread_client_binding = Some(handle);+ if let Some(thread_id) = self+ .email_repo+ .thread_id_for_client_thread_id(handle, accessible_link_ids)+ .await+ .map_err(anyhow::Error::from)?+ {+ input.thread_db_id = Some(thread_id);+ }+ // Unmapped handles stay in place: validate_thread_hint+ // attaches an accessible server thread, and anything else+ // gets a server-minted thread the binding then points at.+ }+ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ pub(crate) async fn delete_draft_for_user_impl(+ &self,+ macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ draft_id: Uuid,+ ) -> Result<DeletedUserDraft, EmailErr> {+ let accessible_link_ids: Vec<Uuid> = self+ .email_repo+ .inboxes_for_macro_id(macro_id)+ .await+ .map_err(anyhow::Error::from)?+ .iter()+ .map(|link| link.id)+ .collect();++ // The handle resolves like a save's: through the caller-scoped+ // mapping first, else as a server ID from a fetched draft.+ //+ // Known window: this read does not take the save's per-handle+ // advisory lock, so a delete that lands while a first save of the+ // same handle is still uncommitted sees no binding and returns the+ // no-op below; the save then commits a draft the client believes is+ // gone. The client queue serializes a handle's save and delete, so+ // reaching it takes a connection drop after the server received the+ // save. Closing it means a per-handle lock (no inbox in the key) and+ // resolve-plus-delete in one repo transaction.+ let resolved_id = self+ .email_repo+ .message_id_for_client_draft_id(draft_id, &accessible_link_ids)+ .await+ .map_err(anyhow::Error::from)?+ .unwrap_or(draft_id);++ // Advisory read: classifies the ID for error reporting. Enforcement+ // is the guarded DELETE below, whose WHERE clause re-checks ownership+ // and draft state, so a raced read can at most turn the delete into+ // a no-op — never remove a row the caller doesn't own.+ let Some(msg) = self+ .email_repo+ .get_simple_message(resolved_id, &accessible_link_ids)+ .await+ .map_err(anyhow::Error::from)?+ else {+ // Absent or someone else's (reported identically so the delete is+ // no existence oracle): an idempotent no-op, so a delete queued+ // offline lands cleanly even when it replays after the draft is+ // already gone.+ return Ok(DeletedUserDraft {+ deleted: false,+ thread_deleted: false,+ });+ };++ if msg.is_sent || !msg.is_draft {+ return Err(EmailErr::MessageAlreadySent(draft_id));+ }++ let deletion = self+ .email_repo+ .delete_draft_message(msg.db_id, msg.thread_db_id, &accessible_link_ids)+ .await+ .map_err(anyhow::Error::from)?;++ let Some(deletion) = deletion else {+ // The guarded delete matched nothing: between the read above and+ // the DELETE, the draft was removed or sent. Re-read to tell those+ // apart — a discard that raced a send reports the same+ // `MessageAlreadySent` the unraced path does, while a row that is+ // gone stays the idempotent no-op an offline-queued discard+ // relies on when it replays after the draft is already deleted.+ let raced = self+ .email_repo+ .get_simple_message(msg.db_id, &accessible_link_ids)+ .await+ .map_err(anyhow::Error::from)?;+ if raced.is_some_and(|m| m.is_sent || !m.is_draft) {+ return Err(EmailErr::MessageAlreadySent(draft_id));+ }+ return Ok(DeletedUserDraft {+ deleted: false,+ thread_deleted: false,+ });+ };++ Ok(DeletedUserDraft {+ deleted: true,+ thread_deleted: deletion.thread_deleted,+ })+ }+/// Shared pipeline for creating a draft or a sent message.////// Validates existing message / reply-to, decodes and sanitizes the HTML@@ -57,6 +278,8 @@ whereself.validate_replying_to(link_id, &accessible_link_ids, &mut input).await?;+ self.validate_thread_hint(link_id, &mut input).await?;+decode_and_sanitize_html_body(&mut input)?;// On send (not drafts), inject the inbox's signature into the body per@@ -105,19 +328,54 @@ whereheaders_json: input.headers_json,send_time: input.send_time,actor_id: input.actor.as_ref().map(|actor| actor.as_ref().to_owned()),+ draft_client_id: input.draft_client_binding,+ thread_client_id: input.thread_client_binding,};- self.email_repo+ // The insert reports the IDs it settled on rather than echoing the+ // candidates above: a save whose client handle raced a concurrent+ // first save adopts that save's row, and the client must hear about+ // the row that actually exists.+ let Some(settled) = self+ .email_repo.insert_message(&resolved, &contacts, link_id, new_thread, is_draft).await- .map_err(anyhow::Error::from)?;+ .map_err(anyhow::Error::from)?+ else {+ // The upsert's owner guard rejected the write: the row it landed+ // on is under another inbox or is no longer an unsent draft. Tell+ // the sent case apart, as the delete path does — the client+ // resets its composer on `MessageAlreadySent` but latches+ // autosave off on a not-found. Re-read through the handle when the+ // save carried one, since a concurrent first save may have+ // settled it on a row this save's input never named. Anything+ // else stays the opaque not-found the validation read reports.+ let rejected_id = match resolved.draft_client_id {+ Some(handle) => self+ .email_repo+ .message_id_for_client_draft_id(handle, &accessible_link_ids)+ .await+ .map_err(anyhow::Error::from)?+ .unwrap_or(resolved.db_id),+ None => resolved.db_id,+ };+ let rejected = self+ .email_repo+ .get_simple_message(rejected_id, &accessible_link_ids)+ .await+ .map_err(anyhow::Error::from)?;+ if rejected.is_some_and(|m| m.is_sent || !m.is_draft) {+ return Err(EmailErr::MessageAlreadySent(resolved.db_id));+ }+ return Err(EmailErr::MessageNotFound(resolved.db_id));+ };Ok(CreatedDraft {- db_id: resolved.db_id,+ db_id: settled.message_db_id,provider_id: resolved.provider_id,replying_to_id: resolved.replying_to_id,provider_thread_id: resolved.provider_thread_id,- thread_db_id: resolved.thread_db_id,+ thread_db_id: settled.thread_db_id,link_id,subject: resolved.subject,to: resolved.to,@@ -206,12 +464,19 @@ wherereturn Ok(());};- let msg = self+ let Some(msg) = self.email_repo.get_simple_message(db_id, accessible_link_ids).await.map_err(anyhow::Error::from)?- .ok_or(EmailErr::MessageNotFound(db_id))?;+ else {+ // A message ID must name an accessible row: REST clients only+ // send IDs learned from responses, and user-scoped (GraphQL)+ // saves arrive here with the client handle already resolved —+ // an unresolvable handle was cleared so the row is server-minted.+ // A miss is therefore a stale/foreign ID, reported opaquely.+ return Err(EmailErr::MessageNotFound(db_id));+ };if msg.is_sent || !msg.is_draft {return Err(EmailErr::MessageAlreadySent(db_id));@@ -221,12 +486,17 @@ where// The sender was switched to a different inbox. A draft belongs to a// single inbox, so discard it (and its now-empty thread) and create a// fresh draft in the sending inbox; validate_replying_to re-derives- // the thread from the reply target.+ // the thread from the reply target. The draft keeps its server ID+ // across the move, and the delete's cascade drops any client-handle+ // binding — the save's binding upsert re-points the handle at the+ // recreated row in the same transaction, so queued offline saves+ // keep converging. A raced delete (`None`) is fine — the row is+ // gone either way, and a raced send is caught by the insert's+ // owner guard.self.email_repo- .delete_draft_message(msg.db_id, msg.thread_db_id)+ .delete_draft_message(msg.db_id, msg.thread_db_id, accessible_link_ids).await.map_err(anyhow::Error::from)?;- input.db_id = None;input.provider_id = None;input.thread_db_id = None;input.provider_thread_id = None;@@ -315,8 +585,45 @@ whereOk(())}- /// If the input already has a thread_db_id, return it with no new thread.- /// Otherwise, build a ThreadRow for creation inside the transaction.+ /// Validate a client-supplied thread hint on the no-reply-target path.+ /// Reply drafts never reach the decision: their linkage was already+ /// re-derived from the reply target. A hint naming an accessible thread+ /// in the sending inbox attaches to it; any other hint — unknown, or a+ /// thread owned elsewhere, handled identically — gets a fresh+ /// server-minted thread. Compose saves replayed offline still converge+ /// on one thread through the client-handle binding, never by letting+ /// the hint become the thread's primary key.+ async fn validate_thread_hint(+ &self,+ link_id: Uuid,+ input: &mut CreateDraftInput,+ ) -> Result<(), EmailErr> {+ if input.replying_to_id.is_some() {+ return Ok(());+ }+ let Some(thread_db_id) = input.thread_db_id else {+ return Ok(());+ };+ let existing = self+ .email_repo+ .thread_by_id(thread_db_id)+ .await+ .map_err(anyhow::Error::from)?;+ match resolve_thread_hint(existing.as_ref(), link_id) {+ ThreadHintOutcome::Attach { provider_thread_id } => {+ input.provider_thread_id = provider_thread_id;+ }+ ThreadHintOutcome::CreateNew => {+ input.thread_db_id = None;+ input.provider_thread_id = None;+ }+ }+ Ok(())+ }++ /// If the input already has a (validated) thread_db_id, return it with no+ /// new thread. Otherwise, build a server-minted ThreadRow for creation+ /// inside the transaction.fn build_new_thread_if_needed(&self,link_id: Uuid,@@ -346,6 +653,49 @@ where}}+/// The decision for a compose draft's client-supplied thread hint.+enum ThreadHintOutcome {+ /// The thread exists in the sending inbox — attach, adopting its+ /// provider thread ID.+ Attach { provider_thread_id: Option<String> },+ /// The hint names no thread in the sending inbox — unknown, or owned+ /// elsewhere. Create a fresh server-minted thread; behaving identically+ /// for both keeps the hint from acting as a thread-existence oracle.+ CreateNew,+}++/// Pure decision for a client-supplied thread hint: attach when the thread+/// exists in the sending inbox, create a fresh server-minted thread+/// otherwise. Hints are untrusted input and never become primary keys.+fn resolve_thread_hint(existing: Option<&ThreadRow>, link_id: Uuid) -> ThreadHintOutcome {+ match existing {+ Some(thread) if thread.link_id == link_id => ThreadHintOutcome::Attach {+ provider_thread_id: thread.provider_id.clone(),+ },+ Some(_) | None => ThreadHintOutcome::CreateNew,+ }+}++/// Resolve the single inbox a draft save targets from the caller's accessible+/// `links`. With an explicit `link_id`, the matching accessible link is used;+/// without one, the caller's own `is_primary` link. The `macro_id` guard+/// matters: the links list includes delegated inboxes, which are primary for+/// *their* account. Mirrors the `X-Email-Link-Id` axum extractor's semantics+/// for transports that carry the inbox by value instead of a header.+fn resolve_target_link<'a>(+ links: &'a [Link],+ link_id: Option<Uuid>,+ caller: ¯o_user_id::user_id::MacroUserIdStr<'_>,+) -> Result<&'a Link, EmailErr> {+ match link_id {+ Some(id) => links.iter().find(|link| link.id == id),+ None => links+ .iter()+ .find(|link| link.is_primary && &link.macro_id == caller),+ }+ .ok_or(EmailErr::InboxNotFound)+}+/// Decodes the base64 `body_html` and sanitizes it against the shared email/// allowlist.///diff --git a/crates/email/src/domain/service/draft/test.rs b/crates/email/src/domain/service/draft/test.rsindex c92e0ceeb0..3af67a0a2d 100644--- a/crates/email/src/domain/service/draft/test.rs+++ b/crates/email/src/domain/service/draft/test.rs@@ -19,6 +19,8 @@ fn input_with_body_html(html: &str) -> CreateDraftInput {send_time: None,include_signature: None,actor: None,+ draft_client_binding: None,+ thread_client_binding: None,}}@@ -64,3 +66,131 @@ fn missing_body_html_is_left_alone() {assert!(input.body_html.is_none());}++fn test_link(id: Uuid, owner: &str, email: &str, is_primary: bool) -> Link {+ use crate::domain::models::UserProvider;+ Link {+ id,+ macro_id: macro_user_id::user_id::MacroUserIdStr::try_from_email(owner).unwrap(),+ fusionauth_user_id: "fa-user".to_string(),+ email_address: macro_user_id::email::EmailStr::try_from(email.to_string()).unwrap(),+ provider: UserProvider::Gmail,+ is_sync_active: true,+ is_primary,+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ }+}++fn caller() -> macro_user_id::user_id::MacroUserIdStr<'static> {+ macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").unwrap()+}++#[test]+fn explicit_link_id_selects_accessible_link() {+ let id1 = Uuid::from_u128(1);+ let id2 = Uuid::from_u128(2);+ let links = vec![+ test_link(id1, "[email protected]", "[email protected]", true),+ test_link(id2, "[email protected]", "[email protected]", false),+ ];+ let resolved = resolve_target_link(&links, Some(id2), &caller()).unwrap();+ assert_eq!(resolved.id, id2);+}++#[test]+fn explicit_link_id_outside_accessible_set_is_rejected() {+ let links = vec![test_link(+ Uuid::from_u128(1),+ "[email protected]",+ "[email protected]",+ true,+ )];+ let result = resolve_target_link(&links, Some(Uuid::from_u128(99)), &caller());+ assert!(matches!(result, Err(EmailErr::InboxNotFound)));+}++#[test]+fn no_link_id_falls_back_to_callers_primary() {+ let primary = Uuid::from_u128(1);+ let links = vec![+ test_link(+ Uuid::from_u128(2),+ "[email protected]",+ "[email protected]",+ false,+ ),+ test_link(primary, "[email protected]", "[email protected]", true),+ ];+ let resolved = resolve_target_link(&links, None, &caller()).unwrap();+ assert_eq!(resolved.id, primary);+}++#[test]+fn delegated_primary_is_never_the_callers_default() {+ // A delegated inbox is primary for its own account; without the macro_id+ // guard it would be picked as the caller's default target.+ let own_primary = Uuid::from_u128(1);+ let links = vec![+ test_link(+ Uuid::from_u128(2),+ "[email protected]",+ "[email protected]",+ true,+ ),+ test_link(own_primary, "[email protected]", "[email protected]", true),+ ];+ let resolved = resolve_target_link(&links, None, &caller()).unwrap();+ assert_eq!(resolved.id, own_primary);+}++#[test]+fn no_link_id_and_no_primary_is_rejected() {+ let result = resolve_target_link(&[], None, &caller());+ assert!(matches!(result, Err(EmailErr::InboxNotFound)));+}++fn thread_row(link_id: Uuid, provider_id: Option<&str>) -> ThreadRow {+ let now = chrono::Utc::now();+ ThreadRow {+ db_id: Uuid::from_u128(0xbeef),+ provider_id: provider_id.map(str::to_owned),+ link_id,+ inbox_visible: true,+ is_read: true,+ latest_inbound_message_ts: None,+ latest_outbound_message_ts: None,+ latest_non_spam_message_ts: None,+ created_at: now,+ updated_at: now,+ project_id: None,+ }+}++#[test]+fn thread_hint_attaches_to_an_owned_thread_and_adopts_its_provider_id() {+ let link_id = Uuid::from_u128(1);+ let thread = thread_row(link_id, Some("provider-7"));+ match resolve_thread_hint(Some(&thread), link_id) {+ ThreadHintOutcome::Attach { provider_thread_id } => {+ assert_eq!(provider_thread_id.as_deref(), Some("provider-7"));+ }+ ThreadHintOutcome::CreateNew => panic!("expected attach"),+ }+}++// A hint naming another inbox's thread and one naming no thread at all must+// behave identically — the hint is untrusted input and must not act as a+// thread-existence oracle. Neither becomes the new thread's primary key.+#[test]+fn foreign_and_unknown_thread_hints_both_create_a_fresh_thread() {+ let foreign = thread_row(Uuid::from_u128(2), None);+ assert!(matches!(+ resolve_thread_hint(Some(&foreign), Uuid::from_u128(1)),+ ThreadHintOutcome::CreateNew+ ));+ assert!(matches!(+ resolve_thread_hint(None, Uuid::from_u128(1)),+ ThreadHintOutcome::CreateNew+ ));+}diff --git a/crates/email/src/inbound/axum/api_types/draft.rs b/crates/email/src/inbound/axum/api_types/draft.rsindex 2cf1ce65ac..ef3939ae18 100644--- a/crates/email/src/inbound/axum/api_types/draft.rs+++ b/crates/email/src/inbound/axum/api_types/draft.rs@@ -163,6 +163,8 @@ impl CreateDraftRequest {// Drafts carry no actor; attribution happens when the draft is// actually sent.actor: None,+ draft_client_binding: None,+ thread_client_binding: None,}}}diff --git a/crates/email/src/inbound/axum/api_types/send.rs b/crates/email/src/inbound/axum/api_types/send.rsindex 8ea4872cfa..02c6bcb7a0 100644--- a/crates/email/src/inbound/axum/api_types/send.rs+++ b/crates/email/src/inbound/axum/api_types/send.rs@@ -60,6 +60,8 @@ impl SendMessageRequest {// The actor comes from the transport's auth context, never the// request body; the handler fills it in.actor: None,+ draft_client_binding: None,+ thread_client_binding: None,}}}diff --git a/crates/email/src/inbound/axum/draft_router.rs b/crates/email/src/inbound/axum/draft_router.rsindex cf640c97ce..99ff0c1008 100644--- a/crates/email/src/inbound/axum/draft_router.rs+++ b/crates/email/src/inbound/axum/draft_router.rs@@ -64,7 +64,9 @@ impl IntoResponse for CreateDraftError {impl From<EmailErr> for CreateDraftError {fn from(err: EmailErr) -> Self {match &err {- EmailErr::MessageNotFound(_) => CreateDraftError::NotFound(err.to_string()),+ EmailErr::MessageNotFound(_) | EmailErr::ThreadNotFound => {+ CreateDraftError::NotFound(err.to_string())+ }EmailErr::MessageAlreadySent(_)| EmailErr::CannotReplyToDraft| EmailErr::Base64DecodeError(_)diff --git a/crates/email/src/inbound/toolset/send_email.rs b/crates/email/src/inbound/toolset/send_email.rsindex cc0c4d6d81..b2968e967c 100644--- a/crates/email/src/inbound/toolset/send_email.rs+++ b/crates/email/src/inbound/toolset/send_email.rs@@ -137,6 +137,8 @@ where// apply the default signature policy.include_signature: self.include_signature,actor: Some(acting_user),+ draft_client_binding: None,+ thread_client_binding: None,};let sent = service_contextdiff --git a/crates/email/src/outbound/email_pg_repo.rs b/crates/email/src/outbound/email_pg_repo.rsindex 9e94094da8..f2334a5a8a 100644--- a/crates/email/src/outbound/email_pg_repo.rs+++ b/crates/email/src/outbound/email_pg_repo.rs@@ -1,10 +1,11 @@use crate::domain::{models::{- Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailErr,- EmailFilter, EmailInboxDetails, EmailThreadMailProjection, EmailThreadMetadata,+ Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, DraftDeletion,+ EmailErr, EmailFilter, EmailInboxDetails, EmailThreadMailProjection, EmailThreadMetadata,EmailThreadPreview, Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow,- ParsedAddresses, PreviewCursorQuery, ResolvedDraftInput, SimpleMessage, SimpleMessageInfo,- ThreadRow, UpsertEmailFilterInput, UpsertedContacts, UserProvider,+ MessageTimestamps, ParsedAddresses, PreviewCursorQuery, ResolvedDraftInput,+ SettledDraftIds, SimpleMessage, SimpleMessageInfo, ThreadRow, UpsertEmailFilterInput,+ UpsertedContacts, UserProvider,},ports::{EmailRepo, EmailUserRepo, LinkEmailSettings, RecipientsByMessageId},};@@ -14,6 +15,7 @@ use sqlx::PgPool;use std::collections::HashMap;use uuid::Uuid;+mod client_id_mapping;mod contact;mod db_types;mod draft;@@ -220,6 +222,14 @@ impl EmailRepo for EmailPgRepo {message::attachments_by_message_ids(&self.pool, message_ids).await}+ async fn message_timestamps(+ &self,+ message_id: Uuid,+ link_id: Uuid,+ ) -> Result<Option<MessageTimestamps>, Self::Err> {+ message::message_timestamps(&self.pool, message_id, link_id).await+ }+async fn draft_attachments_by_message_ids(&self,message_ids: &[Uuid],@@ -249,6 +259,22 @@ impl EmailRepo for EmailPgRepo {message::get_simple_message(&self.pool, message_id, link_ids).await}+ async fn message_id_for_client_draft_id(+ &self,+ client_id: Uuid,+ link_ids: &[Uuid],+ ) -> Result<Option<Uuid>, Self::Err> {+ client_id_mapping::message_id_for_client_draft_id(&self.pool, client_id, link_ids).await+ }++ async fn thread_id_for_client_thread_id(+ &self,+ client_id: Uuid,+ link_ids: &[Uuid],+ ) -> Result<Option<Uuid>, Self::Err> {+ client_id_mapping::thread_id_for_client_thread_id(&self.pool, client_id, link_ids).await+ }+async fn get_draft_replying_to(&self,link_id: Uuid,@@ -261,8 +287,9 @@ impl EmailRepo for EmailPgRepo {&self,message_id: Uuid,thread_db_id: Uuid,- ) -> Result<(), Self::Err> {- message::delete_draft_message(&self.pool, message_id, thread_db_id).await+ link_ids: &[Uuid],+ ) -> Result<Option<DraftDeletion>, Self::Err> {+ message::delete_draft_message(&self.pool, message_id, thread_db_id, link_ids).await}async fn upsert_contacts(@@ -280,7 +307,7 @@ impl EmailRepo for EmailPgRepo {link_id: Uuid,new_thread: Option<ThreadRow>,is_draft: bool,- ) -> Result<(), Self::Err> {+ ) -> Result<Option<SettledDraftIds>, Self::Err> {draft::insert_message(&self.pool, input, contacts, link_id, new_thread, is_draft).await}diff --git a/crates/email/src/outbound/email_pg_repo/client_id_mapping.rs b/crates/email/src/outbound/email_pg_repo/client_id_mapping.rsnew file mode 100644index 0000000000..a46bb07eb7--- /dev/null+++ b/crates/email/src/outbound/email_pg_repo/client_id_mapping.rs@@ -0,0 +1,159 @@+//! Client-handle mapping tables: client-generated draft/thread identity as+//! lookup aliases over server-minted primary keys. Lookups scope to the+//! caller's accessible inboxes, so identical client handles from different+//! users never interact; the handle lock, the in-transaction re-read and the+//! binding upserts all run inside the message-insert transaction (see+//! `draft::insert_message`).++use crate::domain::models::SettledDraftIds;+use sqlx::PgPool;+use uuid::Uuid;++/// Resolve a client draft handle to its message ID within the given inboxes.+/// Newest binding wins if a handle ever appears under more than one link+/// (a moved draft re-binds under its new inbox).+#[tracing::instrument(skip(pool, link_ids), err)]+pub(crate) async fn message_id_for_client_draft_id(+ pool: &PgPool,+ client_id: Uuid,+ link_ids: &[Uuid],+) -> Result<Option<Uuid>, sqlx::Error> {+ sqlx::query_scalar!(+ r#"+ SELECT message_id+ FROM email_draft_client_ids+ WHERE client_id = $1 AND link_id = ANY($2)+ ORDER BY created_at DESC+ LIMIT 1+ "#,+ client_id,+ link_ids,+ )+ .fetch_optional(pool)+ .await+}++/// Resolve a client thread handle to its thread ID within the given inboxes.+#[tracing::instrument(skip(pool, link_ids), err)]+pub(crate) async fn thread_id_for_client_thread_id(+ pool: &PgPool,+ client_id: Uuid,+ link_ids: &[Uuid],+) -> Result<Option<Uuid>, sqlx::Error> {+ sqlx::query_scalar!(+ r#"+ SELECT thread_id+ FROM email_thread_client_ids+ WHERE client_id = $1 AND link_id = ANY($2)+ ORDER BY created_at DESC+ LIMIT 1+ "#,+ client_id,+ link_ids,+ )+ .fetch_optional(pool)+ .await+}++/// Serialize saves that share one client draft handle in one inbox.+///+/// Held until the transaction commits, so a concurrent first save for the+/// same handle waits for the winner to bind before re-reading the mapping.+/// Without it both saves miss the (uncommitted) binding on their own+/// connections and each mints a full message + thread row set, leaving the+/// loser's rows orphaned when the binding upsert re-points the handle.+pub(super) async fn lock_draft_client_id(+ tx: &mut sqlx::PgConnection,+ client_id: Uuid,+ link_id: Uuid,+) -> Result<(), sqlx::Error> {+ sqlx::query!(+ r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,+ format!("email_draft_client:{link_id}:{client_id}"),+ )+ .execute(tx)+ .await?;+ Ok(())+}++/// Re-read a client draft handle's binding inside the insert transaction,+/// returning the bound row and the thread it lives in. Scoped to the single+/// inbox the binding would be written under — the lock is per inbox too, so+/// a binding under another accessible inbox is not ours to converge on.+///+/// The join means a binding whose message has since been deleted reads as+/// unbound, and the save mints its own row as it would have anyway. Sent and+/// non-draft rows are returned: the upsert's owner guard, not this read,+/// decides whether the save may write them.+pub(super) async fn bound_draft_row(+ tx: &mut sqlx::PgConnection,+ client_id: Uuid,+ link_id: Uuid,+) -> Result<Option<SettledDraftIds>, sqlx::Error> {+ sqlx::query_as!(+ SettledDraftIds,+ r#"+ SELECT m.id AS "message_db_id!", m.thread_id AS "thread_db_id!"+ FROM email_draft_client_ids c+ JOIN email_messages m ON m.id = c.message_id+ WHERE c.link_id = $1 AND c.client_id = $2 AND m.link_id = $1+ "#,+ link_id,+ client_id,+ )+ .fetch_optional(tx)+ .await+}++/// Bind a client draft handle to its server-minted message row, re-pointing+/// an existing binding in the same inbox — replays and moved drafts converge+/// on whatever row the save settled on.+///+/// `created_at` is refreshed on the re-point because the cross-inbox lookup+/// orders by it: a rebind is a new binding, and leaving the original insert's+/// timestamp would strand it behind a stale binding under another inbox.+pub(super) async fn bind_draft_client_id(+ tx: &mut sqlx::PgConnection,+ client_id: Uuid,+ link_id: Uuid,+ message_id: Uuid,+) -> Result<(), sqlx::Error> {+ sqlx::query!(+ r#"+ INSERT INTO email_draft_client_ids (client_id, link_id, message_id)+ VALUES ($1, $2, $3)+ ON CONFLICT (link_id, client_id)+ DO UPDATE SET message_id = EXCLUDED.message_id, created_at = now()+ "#,+ client_id,+ link_id,+ message_id,+ )+ .execute(tx)+ .await?;+ Ok(())+}++/// Bind a client thread handle to its server-minted thread row. `created_at`+/// is refreshed on the re-point for the same reason as the draft binding.+pub(super) async fn bind_thread_client_id(+ tx: &mut sqlx::PgConnection,+ client_id: Uuid,+ link_id: Uuid,+ thread_id: Uuid,+) -> Result<(), sqlx::Error> {+ sqlx::query!(+ r#"+ INSERT INTO email_thread_client_ids (client_id, link_id, thread_id)+ VALUES ($1, $2, $3)+ ON CONFLICT (link_id, client_id)+ DO UPDATE SET thread_id = EXCLUDED.thread_id, created_at = now()+ "#,+ client_id,+ link_id,+ thread_id,+ )+ .execute(tx)+ .await?;+ Ok(())+}diff --git a/crates/email/src/outbound/email_pg_repo/draft.rs b/crates/email/src/outbound/email_pg_repo/draft.rsindex b68c2c84f0..b153c95454 100644--- a/crates/email/src/outbound/email_pg_repo/draft.rs+++ b/crates/email/src/outbound/email_pg_repo/draft.rs@@ -1,5 +1,5 @@-use super::{message, thread};-use crate::domain::models::{ResolvedDraftInput, ThreadRow, UpsertedContacts};+use super::{client_id_mapping, message, thread};+use crate::domain::models::{ResolvedDraftInput, SettledDraftIds, ThreadRow, UpsertedContacts};use chrono::Utc;use sqlx::PgPool;use uuid::Uuid;@@ -7,7 +7,9 @@ use uuid::Uuid;/// Insert a draft message within a transaction./// Includes: thread insert (if new), message upsert, scheduled message, recipients,/// thread metadata update, and user history.-/// Returns the thread DB ID.+/// Returns the IDs the save settled on, or `None` (rolling everything back)+/// when the upsert's owner guard rejected the write — the message ID exists+/// under another inbox or is no longer an unsent draft.#[tracing::instrument(skip(pool, input, contacts, new_thread), err)]pub(crate) async fn insert_message(pool: &PgPool,@@ -16,17 +18,42 @@ pub(crate) async fn insert_message(link_id: Uuid,new_thread: Option<ThreadRow>,is_draft: bool,-) -> Result<(), sqlx::Error> {+) -> Result<Option<SettledDraftIds>, sqlx::Error> {let mut tx = pool.begin().await?;- let message_db_id = input.db_id;- let thread_db_id = input.thread_db_id;+ let mut settled = SettledDraftIds {+ message_db_id: input.db_id,+ thread_db_id: input.thread_db_id,+ };+ let mut new_thread = new_thread;++ // The caller resolved this handle on its own connection, where a+ // concurrent first save's binding is invisible until it commits — so two+ // first saves of one draft would each mint a message and a thread, and the+ // losing binding upsert would orphan a full row set. Serialize on the+ // handle and re-read the binding under the lock: the loser adopts the row+ // the winner settled on and updates it instead.+ if let Some(client_id) = input.draft_client_id {+ client_id_mapping::lock_draft_client_id(&mut tx, client_id, link_id).await?;+ if let Some(bound) = client_id_mapping::bound_draft_row(&mut tx, client_id, link_id).await?+ && bound.message_db_id != settled.message_db_id+ {+ settled = bound;+ // Our thread would have no messages left to hold.+ new_thread = None;+ }+ }++ let SettledDraftIds {+ message_db_id,+ thread_db_id,+ } = settled;if let Some(thread) = new_thread {thread::insert_thread(&mut tx, &thread, link_id).await?;}- upsert_draft(+ let applied = upsert_draft(&mut tx,input,message_db_id,@@ -36,6 +63,10 @@ pub(crate) async fn insert_message(is_draft,).await?;+ if !applied {+ tx.rollback().await?;+ return Ok(None);+ }// Only touch scheduling if send_time is explicitly provided.// Scheduling is managed via the dedicated /drafts/scheduled endpoints.@@ -56,11 +87,26 @@ pub(crate) async fn insert_message(thread::upsert_user_history(&mut tx, link_id, thread_db_id).await?;+ // Bind client handles to the settled rows in the same transaction, so a+ // replayed offline save resolves to this row instead of creating another.+ if let Some(client_id) = input.draft_client_id {+ client_id_mapping::bind_draft_client_id(&mut tx, client_id, link_id, message_db_id).await?;+ }+ if let Some(client_id) = input.thread_client_id {+ client_id_mapping::bind_thread_client_id(&mut tx, client_id, link_id, thread_db_id).await?;+ }+tx.commit().await?;- Ok(())+ Ok(Some(settled))}/// Upsert a draft message row.+///+/// The conflict clause is owner-guarded: an existing row is only updated when+/// it is an unsent draft in the sending inbox. The IDs reaching this upsert+/// come from validated reads, but reads race — the guard, not the read, is+/// what keeps a raced save from rewriting another inbox's row or a sent+/// message. Returns `false` when the guard rejected the write.pub(crate) async fn upsert_draft(tx: &mut sqlx::PgConnection,input: &ResolvedDraftInput,@@ -69,10 +115,10 @@ pub(crate) async fn upsert_draft(from_contact_id: Option<Uuid>,link_id: Uuid,is_draft: bool,-) -> Result<(), sqlx::Error> {+) -> Result<bool, sqlx::Error> {let now = Utc::now();- sqlx::query!(+ let result = sqlx::query!(r#"INSERT INTO email_messages (id, provider_id, link_id, thread_id, provider_thread_id,@@ -90,7 +136,6 @@ pub(crate) async fn upsert_draft(subject = EXCLUDED.subject,from_contact_id = EXCLUDED.from_contact_id,sent_at = EXCLUDED.sent_at,- has_attachments = EXCLUDED.has_attachments,is_read = EXCLUDED.is_read,is_starred = EXCLUDED.is_starred,is_sent = EXCLUDED.is_sent,@@ -100,6 +145,9 @@ pub(crate) async fn upsert_draft(body_macro = EXCLUDED.body_macro,headers_jsonb = EXCLUDED.headers_jsonb,updated_at = NOW()+ WHERE email_messages.link_id = EXCLUDED.link_id+ AND email_messages.is_draft+ AND NOT email_messages.is_sent"#,message_db_id,input.provider_id,@@ -125,5 +173,5 @@ pub(crate) async fn upsert_draft(.execute(&mut *tx).await?;- Ok(())+ Ok(result.rows_affected() > 0)}diff --git a/crates/email/src/outbound/email_pg_repo/message.rs b/crates/email/src/outbound/email_pg_repo/message.rsindex df38a27816..239a42dedc 100644--- a/crates/email/src/outbound/email_pg_repo/message.rs+++ b/crates/email/src/outbound/email_pg_repo/message.rs@@ -1,7 +1,7 @@use crate::domain::{models::{- AttachmentDraft, AttachmentForwarded, ContactInfo, MessageAttachment, MessageLabel,- RecipientType, SimpleMessageInfo, UpsertedContacts,+ AttachmentDraft, AttachmentForwarded, ContactInfo, DraftDeletion, MessageAttachment,+ MessageLabel, MessageTimestamps, RecipientType, SimpleMessageInfo, UpsertedContacts,},ports::RecipientsByMessageId,};@@ -15,6 +15,22 @@ use super::db_types::{DbRecipientRow, DbRecipientType, DbSenderRow, DbSimpleMessageRow,};+#[tracing::instrument(err, skip(pool))]+pub(super) async fn message_timestamps(+ pool: &PgPool,+ message_id: Uuid,+ link_id: Uuid,+) -> Result<Option<MessageTimestamps>, sqlx::Error> {+ sqlx::query_as!(+ MessageTimestamps,+ "SELECT created_at, updated_at FROM email_messages WHERE id = $1 AND link_id = $2",+ message_id,+ link_id,+ )+ .fetch_optional(pool)+ .await+}+#[tracing::instrument(err, skip(pool, message_ids))]pub(super) async fn senders_by_message_ids(pool: &PgPool,@@ -343,31 +359,39 @@ pub(crate) async fn get_draft_replying_to(}/// Delete an unsent draft in the given thread (dependent rows cascade) and, if-/// the thread is left empty, delete the thread too. Errors if no matching unsent-/// draft exists in that thread, so sent mail or a mismatched thread is never-/// touched.-#[tracing::instrument(skip(pool), err)]+/// the thread is left empty, delete the thread too. The WHERE clause is the+/// ownership enforcement: the row must belong to one of `link_ids`, so sent+/// mail, a mismatched thread, or someone else's row is never touched even+/// when the caller's validation read was raced. No matching row is `None`,+/// not an error — deletes are idempotent.+#[tracing::instrument(skip(pool, link_ids), err)]pub(crate) async fn delete_draft_message(pool: &PgPool,message_id: Uuid,thread_db_id: Uuid,-) -> Result<(), sqlx::Error> {+ link_ids: &[Uuid],+) -> Result<Option<DraftDeletion>, sqlx::Error> {let mut tx = pool.begin().await?;let deleted_link_id = sqlx::query_scalar!(r#"DELETE FROM email_messages- WHERE id = $1 AND thread_id = $2 AND is_draft = true AND is_sent = false+ WHERE id = $1+ AND thread_id = $2+ AND link_id = ANY($3)+ AND is_draft = true+ AND is_sent = falseRETURNING link_id"#,message_id,thread_db_id,+ link_ids,).fetch_optional(&mut *tx).await?;let Some(link_id) = deleted_link_id else {- return Err(sqlx::Error::RowNotFound);+ return Ok(None);};let messages_remain = sqlx::query_scalar!(@@ -390,7 +414,9 @@ pub(crate) async fn delete_draft_message(}tx.commit().await?;- Ok(())+ Ok(Some(DraftDeletion {+ thread_deleted: !messages_remain,+ }))}/// Upsert or delete a scheduled message based on send_time.diff --git a/crates/email/src/outbound/email_pg_repo/test/draft.rs b/crates/email/src/outbound/email_pg_repo/test/draft.rsindex 26b250fada..c8df6b68aa 100644--- a/crates/email/src/outbound/email_pg_repo/test/draft.rs+++ b/crates/email/src/outbound/email_pg_repo/test/draft.rs@@ -181,7 +181,14 @@ async fn test_delete_draft_message_keeps_nonempty_thread(let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;- repo.delete_draft_message(draft_id, thread_id).await?;+ let deletion = repo+ .delete_draft_message(draft_id, thread_id, &[link_id])+ .await?+ .expect("the draft should be deleted");+ assert!(+ !deletion.thread_deleted,+ "a thread that still has messages should not be reported deleted"+ );assert!(repo.get_simple_message(draft_id, &[link_id])@@ -208,8 +215,16 @@ async fn test_delete_draft_message_removes_empty_thread(let draft_id = Uuid::parse_str("ee000004-0000-0000-0000-000000000004")?;let thread_id = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;- repo.delete_draft_message(draft_id, thread_id).await?;+ let deletion = repo+ .delete_draft_message(draft_id, thread_id, &[link_id])+ .await?+ .expect("the draft should be deleted");+ assert!(+ deletion.thread_deleted,+ "emptying the thread should be reported"+ );assert!(repo.thread_by_id(thread_id).await?.is_none(),@@ -231,10 +246,19 @@ async fn test_delete_draft_message_rejects_sent_message(// ee000003 is a sent message, not a draft; deleting it must not succeed.let sent_id = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;let thread_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;assert!(- repo.delete_draft_message(sent_id, thread_id).await.is_err(),- "deleting a non-draft should error and leave it intact"+ repo.delete_draft_message(sent_id, thread_id, &[link_id])+ .await?+ .is_none(),+ "deleting a non-draft should match nothing and leave it intact"+ );+ assert!(+ repo.get_simple_message(sent_id, &[link_id])+ .await?+ .is_some(),+ "the sent message must survive");assert!(repo.thread_by_id(thread_id).await?.is_some(),@@ -244,6 +268,39 @@ async fn test_delete_draft_message_rejects_sent_message(Ok(())}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_delete_draft_message_rejects_foreign_link_scope(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ // The draft exists, but the caller's link scope doesn't include its+ // inbox: the WHERE-clause guard must match nothing and leave the row —+ // this is the enforcement a raced validation read falls back on.+ let draft_id = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;+ let owner_link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let foreign_link = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;++ assert!(+ repo.delete_draft_message(draft_id, thread_id, &[foreign_link])+ .await?+ .is_none(),+ "a delete outside the caller's inboxes must match nothing"+ );+ assert!(+ repo.get_simple_message(draft_id, &[owner_link])+ .await?+ .is_some(),+ "the draft must survive a foreign-scoped delete"+ );++ Ok(())+}+// ── cross_inbox_reply_drafts ──────────────────────────────────────#[sqlx::test(@@ -504,6 +561,8 @@ async fn test_insert_draft_message_into_existing_thread(headers_json: None,send_time: None,actor_id: None,+ draft_client_id: None,+ thread_client_id: None,};let contacts = UpsertedContacts {@@ -589,6 +648,8 @@ async fn test_insert_draft_message_with_new_thread(pool: Pool<Postgres>) -> anyhheaders_json: None,send_time: None,actor_id: None,+ draft_client_id: None,+ thread_client_id: None,};let contacts = UpsertedContacts {@@ -662,6 +723,8 @@ async fn test_insert_draft_message_with_scheduled_send(pool: Pool<Postgres>) ->headers_json: None,send_time: Some(send_time),actor_id: None,+ draft_client_id: None,+ thread_client_id: None,};let contacts = UpsertedContacts {@@ -689,7 +752,6 @@ async fn test_insert_draft_message_with_scheduled_send(pool: Pool<Postgres>) ->migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../../fixtures", scripts("email_draft")))]-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]async fn test_insert_draft_message_upsert_existing(pool: Pool<Postgres>) -> anyhow::Result<()> {let repo = EmailPgRepo::new(pool.clone());@@ -697,6 +759,23 @@ async fn test_insert_draft_message_upsert_existing(pool: Pool<Postgres>) -> anyhlet thread_db_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;// Re-use the existing draft message ID (msg2)let message_db_id = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;+ let timestamps_before = repo+ .message_timestamps(message_db_id, link_id)+ .await?+ .unwrap();+ assert!(+ repo.message_timestamps(message_db_id, Uuid::nil())+ .await?+ .is_none()+ );+ repo.insert_message_labels_batch(&[message_db_id], "INBOX", link_id)+ .await?;+ sqlx::query!(+ "UPDATE email_messages SET has_attachments = true WHERE id = $1",+ message_db_id+ )+ .execute(&pool)+ .await?;let thread_before = repo.thread_by_id(thread_db_id).await?@@ -720,6 +799,8 @@ async fn test_insert_draft_message_upsert_existing(pool: Pool<Postgres>) -> anyhheaders_json: None,send_time: None,actor_id: None,+ draft_client_id: None,+ thread_client_id: None,};let contacts = UpsertedContacts {@@ -731,19 +812,27 @@ async fn test_insert_draft_message_upsert_existing(pool: Pool<Postgres>) -> anyh.await?;// Verify the message was updated (not duplicated)- let row = sqlx::query("SELECT subject, body_text FROM email_messages WHERE id = $1")- .bind(message_db_id)- .fetch_one(&pool)- .await?;+ let row = sqlx::query!(+ "SELECT subject, body_text, has_attachments FROM email_messages WHERE id = $1",+ message_db_id+ )+ .fetch_one(&pool)+ .await?;- assert_eq!(- row.get::<Option<String>, _>("subject").as_deref(),- Some("Updated draft subject")- );- assert_eq!(- row.get::<Option<String>, _>("body_text").as_deref(),- Some("Updated body")+ assert_eq!(row.subject.as_deref(), Some("Updated draft subject"));+ assert_eq!(row.body_text.as_deref(), Some("Updated body"));+ assert!(+ row.has_attachments,+ "editing a draft must preserve its attachment flag");+ let timestamps_after = repo+ .message_timestamps(message_db_id, link_id)+ .await?+ .unwrap();+ assert_eq!(timestamps_after.created_at, timestamps_before.created_at);+ assert!(timestamps_after.updated_at > timestamps_before.updated_at);+ let labels = repo.labels_by_message_ids(&[message_db_id]).await?;+ assert_eq!(labels[&message_db_id][0].provider_label_id, "INBOX");let thread_after = repo.thread_by_id(thread_db_id)@@ -788,6 +877,8 @@ async fn test_insert_draft_message_updates_thread_metadata(headers_json: None,send_time: None,actor_id: None,+ draft_client_id: None,+ thread_client_id: None,};let contacts = UpsertedContacts {@@ -841,6 +932,8 @@ async fn test_insert_message_with_is_draft_false(pool: Pool<Postgres>) -> anyhowheaders_json: None,send_time: None,actor_id: None,+ draft_client_id: None,+ thread_client_id: None,};let contacts = UpsertedContacts {@@ -864,3 +957,448 @@ async fn test_insert_message_with_is_draft_false(pool: Pool<Postgres>) -> anyhowOk(())}++// ── client-handle mappings / owner-guarded upsert ───────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_client_handle_bindings_resolve_scoped_and_cascade(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let other_link = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;+ let draft_id = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;+ let draft_handle = Uuid::parse_str("c11e0001-0000-0000-0000-000000000001")?;+ let thread_handle = Uuid::parse_str("c11e0002-0000-0000-0000-000000000002")?;++ // A save carrying unbound client handles binds them to the settled rows+ // inside the insert transaction.+ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };+ let mut input = resolved_input(draft_id, thread_id);+ input.subject = "Bound".to_string();+ input.draft_client_id = Some(draft_handle);+ input.thread_client_id = Some(thread_handle);+ assert!(+ repo.insert_message(&input, &contacts, link, None, true)+ .await?+ .is_some()+ );++ // Lookups are scoped to the caller's inboxes: the owner resolves, and an+ // unrelated inbox sees nothing — identical handles never interact.+ assert_eq!(+ repo.message_id_for_client_draft_id(draft_handle, &[link])+ .await?,+ Some(draft_id)+ );+ assert_eq!(+ repo.thread_id_for_client_thread_id(thread_handle, &[link])+ .await?,+ Some(thread_id)+ );+ assert_eq!(+ repo.message_id_for_client_draft_id(draft_handle, &[other_link])+ .await?,+ None+ );+ assert_eq!(+ repo.thread_id_for_client_thread_id(thread_handle, &[other_link])+ .await?,+ None+ );++ // Deleting the draft cascades its binding away.+ repo.delete_draft_message(draft_id, thread_id, &[link])+ .await?+ .expect("the draft should be deleted");+ assert_eq!(+ repo.message_id_for_client_draft_id(draft_handle, &[link])+ .await?,+ None+ );++ Ok(())+}++/// Build the input + new thread a first save of `handle` hands the repo: its+/// own freshly minted message and thread, because its resolution read saw no+/// binding for the handle.+fn first_save_of(+ handle: Uuid,+ link_id: Uuid,+ subject: &str,+) -> (ResolvedDraftInput, ThreadRow, Uuid) {+ let message_db_id = macro_uuid::generate_uuid_v7();+ let thread_db_id = macro_uuid::generate_uuid_v7();+ let mut input = resolved_input(message_db_id, thread_db_id);+ input.subject = subject.to_string();+ input.draft_client_id = Some(handle);+ let thread = ThreadRow {+ db_id: thread_db_id,+ provider_id: None,+ link_id,+ inbox_visible: true,+ is_read: true,+ latest_inbound_message_ts: None,+ latest_outbound_message_ts: None,+ latest_non_spam_message_ts: None,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ project_id: None,+ };+ (input, thread, message_db_id)+}++async fn message_exists(pool: &Pool<Postgres>, id: Uuid) -> anyhow::Result<bool> {+ Ok(sqlx::query_scalar!(+ r#"SELECT EXISTS (SELECT 1 FROM email_messages WHERE id = $1) AS "exists!""#,+ id+ )+ .fetch_one(pool)+ .await?)+}++async fn thread_exists(pool: &Pool<Postgres>, id: Uuid) -> anyhow::Result<bool> {+ Ok(sqlx::query_scalar!(+ r#"SELECT EXISTS (SELECT 1 FROM email_threads WHERE id = $1) AS "exists!""#,+ id+ )+ .fetch_one(pool)+ .await?)+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_concurrent_first_saves_of_one_handle_settle_on_one_row(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let handle = Uuid::parse_str("c11e0003-0000-0000-0000-000000000003")?;+ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };++ // Two saves of one client handle in flight at once, each having missed the+ // other's uncommitted binding and minted a full message + thread of its+ // own. The handle lock decides one winner; the loser adopts its row.+ let (input_a, thread_a, message_a) = first_save_of(handle, link, "save a");+ let (input_b, thread_b, message_b) = first_save_of(handle, link, "save b");+ let (a, b) = futures::future::join(+ repo.insert_message(&input_a, &contacts, link, Some(thread_a.clone()), true),+ repo.insert_message(&input_b, &contacts, link, Some(thread_b.clone()), true),+ )+ .await;++ let a = a?.expect("the first save should apply");+ let b = b?.expect("the second save should apply");+ assert_eq!(+ a, b,+ "concurrent saves of one handle must settle on one message and thread"+ );++ // Only the settled row set exists: the loser never created a duplicate.+ let (winner_message, loser_message) = if a.message_db_id == message_a {+ (message_a, message_b)+ } else {+ (message_b, message_a)+ };+ let (winner_thread, loser_thread) = if a.thread_db_id == thread_a.db_id {+ (thread_a.db_id, thread_b.db_id)+ } else {+ (thread_b.db_id, thread_a.db_id)+ };+ assert_eq!(a.message_db_id, winner_message);+ assert_eq!(a.thread_db_id, winner_thread);+ assert!(+ !message_exists(&pool, loser_message).await?,+ "the losing save must not leave an orphaned message"+ );+ assert!(+ !thread_exists(&pool, loser_thread).await?,+ "the losing save must not leave an orphaned thread"+ );++ // The handle names the settled row, so later saves keep converging on it.+ assert_eq!(+ repo.message_id_for_client_draft_id(handle, &[link]).await?,+ Some(winner_message)+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_save_racing_a_committed_binding_adopts_it(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let handle = Uuid::parse_str("c11e0004-0000-0000-0000-000000000004")?;+ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };++ let (input_a, thread_a, message_a) = first_save_of(handle, link, "winner");+ let a = repo+ .insert_message(&input_a, &contacts, link, Some(thread_a.clone()), true)+ .await?+ .expect("the winning save should apply");++ // A save whose resolution read predates that commit still carries its own+ // minted ids. The in-transaction re-read redirects it onto the bound row.+ let (input_b, thread_b, _) = first_save_of(handle, link, "adopter");+ let b = repo+ .insert_message(&input_b, &contacts, link, Some(thread_b.clone()), true)+ .await?+ .expect("the adopting save should apply");++ assert_eq!(a, b, "the later save must adopt the bound row");+ assert!(+ !thread_exists(&pool, thread_b.db_id).await?,+ "the adopted save's own thread must never be created"+ );++ // It updated the bound row rather than inserting alongside it.+ let subject = sqlx::query_scalar!(+ "SELECT subject FROM email_messages WHERE id = $1",+ message_a+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(subject.as_deref(), Some("adopter"));++ Ok(())+}++// A handle can name a binding under more than one accessible inbox when a+// move's cascade did not land, and the lookup breaks that tie by recency. A+// rebind has to count as the newest binding, or the handle keeps resolving to+// the inbox the draft was moved away from.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_rebinding_a_handle_wins_the_cross_inbox_recency_tie(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link_a = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let link_b = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc")?;+ let both = [link_a, link_b];+ let draft_handle = Uuid::parse_str("c11e0005-0000-0000-0000-000000000005")?;+ let thread_handle = Uuid::parse_str("c11e0006-0000-0000-0000-000000000006")?;+ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };++ let save = async |link_id: Uuid, subject: &str| {+ let (mut input, thread, _) = first_save_of(draft_handle, link_id, subject);+ input.thread_client_id = Some(thread_handle);+ repo.insert_message(&input, &contacts, link_id, Some(thread), true)+ .await+ };++ // Bound under B, then under A: A is the newer binding, so it wins.+ let b = save(link_b, "in b")+ .await?+ .expect("the B save should apply");+ let a = save(link_a, "in a")+ .await?+ .expect("the A save should apply");+ assert_eq!(+ repo.message_id_for_client_draft_id(draft_handle, &both)+ .await?,+ Some(a.message_db_id)+ );++ // Bound back under B. This re-points the existing B row rather than+ // inserting one, so its recency has to be refreshed for B to win again.+ let b_again = save(link_b, "back in b")+ .await?+ .expect("the rebind applies");+ assert_eq!(+ b_again, b,+ "the rebind should settle on B's existing row, not a third one"+ );+ assert_eq!(+ repo.message_id_for_client_draft_id(draft_handle, &both)+ .await?,+ Some(b.message_db_id),+ "the rebind must outrank the older binding under A"+ );+ assert_eq!(+ repo.thread_id_for_client_thread_id(thread_handle, &both)+ .await?,+ Some(b.thread_db_id),+ "the thread mapping breaks the tie the same way"+ );++ Ok(())+}++fn resolved_input(db_id: Uuid, thread_db_id: Uuid) -> ResolvedDraftInput {+ ResolvedDraftInput {+ db_id,+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: None,+ thread_db_id,+ subject: "Overwritten".to_string(),+ to: vec![],+ cc: vec![],+ bcc: vec![],+ body_text: Some("attacker content".to_string()),+ body_html: Some("<p>attacker content</p>".to_string()),+ body_macro: None,+ headers_json: None,+ send_time: None,+ actor_id: None,+ draft_client_id: None,+ thread_client_id: None,+ }+}++async fn message_snapshot(+ pool: &Pool<Postgres>,+ id: Uuid,+) -> anyhow::Result<(Uuid, Option<String>, Option<String>, bool, bool)> {+ let row = sqlx::query(+ "SELECT link_id, subject, body_text, is_sent, is_draft FROM email_messages WHERE id = $1",+ )+ .bind(id)+ .fetch_one(pool)+ .await?;+ Ok((+ row.get::<Uuid, _>("link_id"),+ row.get::<Option<String>, _>("subject"),+ row.get::<Option<String>, _>("body_text"),+ row.get::<bool, _>("is_sent"),+ row.get::<bool, _>("is_draft"),+ ))+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_guard_rejects_cross_inbox_overwrite(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ // A draft owned by the cccc inbox; the write is issued from aaaa. The+ // IDs reaching the upsert come from validated reads, but reads race —+ // the conflict clause, not the read, is what must hold the line.+ let victim = Uuid::parse_str("ee000005-0000-0000-0000-000000000005")?;+ let attacker_link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let attacker_thread = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ let before = message_snapshot(&pool, victim).await?;++ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };+ let applied = repo+ .insert_message(+ &resolved_input(victim, attacker_thread),+ &contacts,+ attacker_link,+ None,+ true,+ )+ .await?;++ assert!(+ applied.is_none(),+ "owner guard must reject a cross-inbox overwrite"+ );+ let after = message_snapshot(&pool, victim).await?;+ assert_eq!(before, after, "victim row must be untouched");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_guard_rejects_sent_message_overwrite(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ // Same inbox, but the row is a sent message — no draft save may rewrite it.+ let victim = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ let before = message_snapshot(&pool, victim).await?;++ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };+ let applied = repo+ .insert_message(&resolved_input(victim, thread), &contacts, link, None, true)+ .await?;++ assert!(+ applied.is_none(),+ "owner guard must reject rewriting a sent message"+ );+ let after = message_snapshot(&pool, victim).await?;+ assert_eq!(before, after, "sent message must be untouched");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_insert_message_reports_applied_on_create(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;+ let fresh_id = Uuid::parse_str("dd000002-0000-0000-0000-000000000002")?;++ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };+ let applied = repo+ .insert_message(+ &resolved_input(fresh_id, thread),+ &contacts,+ link,+ None,+ true,+ )+ .await?;++ assert!(applied.is_some(), "a fresh unclaimed id inserts normally");++ Ok(())+}diff --git a/crates/email/src/outbound/email_pg_repo/test/signal_flag.rs b/crates/email/src/outbound/email_pg_repo/test/signal_flag.rsindex 62ce1a58b1..8aec7ec89e 100644--- a/crates/email/src/outbound/email_pg_repo/test/signal_flag.rs+++ b/crates/email/src/outbound/email_pg_repo/test/signal_flag.rs@@ -135,6 +135,7 @@ async fn delete_draft_message_recomputes_thread_metadata(repo.delete_draft_message(Uuid::parse_str(DRAFT_MSG)?,Uuid::parse_str(THREAD_DRAFT_SIGNAL)?,+ &[Uuid::parse_str(LINK_ID)?],).await?;@@ -167,6 +168,7 @@ async fn delete_draft_message_returns_sent_thread_out_of_inbox(repo.delete_draft_message(Uuid::parse_str(SENT_THREAD_DRAFT_MSG)?,Uuid::parse_str(THREAD_SENT_DONE)?,+ &[Uuid::parse_str(LINK_ID)?],).await?;diff --git a/crates/graphql_email/Cargo.toml b/crates/graphql_email/Cargo.tomlindex b410718519..2e8c9a76ee 100644--- a/crates/graphql_email/Cargo.toml+++ b/crates/graphql_email/Cargo.toml@@ -8,6 +8,7 @@ publish = falseasync-graphql = { workspace = true, features = ["dataloader"] }chrono = { workspace = true }email = { path = "../email", default-features = false, features = ["ports"] }+email_utils = { path = "../email_utils" }entity_access = { path = "../entity_access", default-features = false }futures = { workspace = true }graphql_common = { path = "../graphql_common" }diff --git a/crates/graphql_email/src/lib.rs b/crates/graphql_email/src/lib.rsindex 9dd881459d..c5c279609d 100644--- a/crates/graphql_email/src/lib.rs+++ b/crates/graphql_email/src/lib.rs@@ -17,9 +17,10 @@ pub use loaders::{email_thread_metadata_loader,};pub use mutation::{- EmailMutationService, EmailThreadMutationLoadFuture, EmailThreadMutationOutput,- GraphqlEmailMutation, MarkEmailThreadSeenInput, MarkEmailThreadUnreadInput,- UpdateEmailThreadLabelInput,+ DeleteEmailDraftInput, DeleteEmailDraftPayload, EmailMutationService,+ EmailThreadMutationLoadFuture, EmailThreadMutationOutput, GraphqlEmailMutation,+ MarkEmailThreadSeenInput, MarkEmailThreadUnreadInput, SaveEmailDraftContactInput,+ SaveEmailDraftInput, SaveEmailDraftPayload, UpdateEmailThreadLabelInput,};pub use objects::{GraphqlMailPreviewMessage, GraphqlSoupEmailMessage,diff --git a/crates/graphql_email/src/mutation.rs b/crates/graphql_email/src/mutation.rsindex cbd6451588..c6661cf074 100644--- a/crates/graphql_email/src/mutation.rs+++ b/crates/graphql_email/src/mutation.rs@@ -1,10 +1,17 @@use std::{future::Future, marker::PhantomData, pin::Pin, sync::Arc};-use async_graphql::{Context, ID, InputObject, Object, OutputType};+use async_graphql::{Context, ErrorExtensions, ID, InputObject, Object, OutputType, SimpleObject};+use chrono::Utc;use email::domain::{- models::{EmailErr, UpdateThreadLabelsResult},+ models::{+ ContactInfo, CreateDraftInput, DeletedUserDraft, EmailErr, Message, SavedUserDraft,+ UpdateThreadLabelsResult,+ },ports::EmailService,};++use crate::loaders::EmailContentMessage;+use crate::objects::GraphqlSoupEmailMessage;use graphql_common::{parse_id, require_authenticated_user};use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;@@ -36,6 +43,23 @@ pub trait EmailMutationService: Send + Sync + 'static {label_id: Uuid,value: bool,) -> impl Future<Output = Result<UpdateThreadLabelsResult, EmailErr>> + Send;++ /// Create or update a draft for the authenticated user, resolving the+ /// sending inbox from `link_id` (or the caller's primary inbox).+ fn save_email_draft(+ &self,+ user_id: MacroUserIdStr<'static>,+ link_id: Option<Uuid>,+ input: CreateDraftInput,+ ) -> impl Future<Output = Result<SavedUserDraft, EmailErr>> + Send;++ /// Delete a draft for the authenticated user, idempotently: an ID that+ /// is already gone is a successful no-op.+ fn delete_email_draft(+ &self,+ user_id: MacroUserIdStr<'static>,+ draft_id: Uuid,+ ) -> impl Future<Output = Result<DeletedUserDraft, EmailErr>> + Send;}impl<S> EmailMutationService for S@@ -68,6 +92,23 @@ whereself.update_thread_labels_for_user(user_id, thread_id, label_id, value).await}++ async fn save_email_draft(+ &self,+ user_id: MacroUserIdStr<'static>,+ link_id: Option<Uuid>,+ input: CreateDraftInput,+ ) -> Result<SavedUserDraft, EmailErr> {+ self.save_draft_for_user(user_id, link_id, input).await+ }++ async fn delete_email_draft(+ &self,+ user_id: MacroUserIdStr<'static>,+ draft_id: Uuid,+ ) -> Result<DeletedUserDraft, EmailErr> {+ self.delete_draft_for_user(user_id, draft_id).await+ }}/// Boxed future that reloads an email thread after a mutation.@@ -131,6 +172,232 @@ pub struct UpdateEmailThreadLabelInput {pub value: bool,}+/// One recipient of an email draft.+#[derive(InputObject)]+pub struct SaveEmailDraftContactInput {+ /// Recipient email address.+ pub email: String,+ /// Recipient display name, when known.+ pub name: Option<String>,+ /// Recipient photo URL, when known.+ pub photo_url: Option<String>,+}++impl From<SaveEmailDraftContactInput> for ContactInfo {+ fn from(input: SaveEmailDraftContactInput) -> Self {+ Self {+ email: input.email,+ name: input.name,+ photo_url: input.photo_url,+ }+ }+}++/// Input for creating or updating an email draft.+///+/// The draft ID is a client-generated handle so a save queued offline stays+/// an idempotent upsert when it replays later — possibly after an app+/// restart, possibly more than once. Handles are untrusted input and never+/// become primary keys: the server resolves them through a caller-scoped+/// mapping to server-minted rows. Thread identifiers are hints: the server+/// derives authoritative thread linkage from the reply target or the+/// existing draft.+#[derive(InputObject)]+pub struct SaveEmailDraftInput {+ /// Draft handle: a client-generated ID, or a server ID from a fetched+ /// draft. Resolved scoped to the caller's inboxes, and bound to the+ /// server row the save settles on, so replays converge on one draft.+ pub draft_id: ID,+ /// Sending inbox. Absent means the caller's primary inbox. Carried as a+ /// variable (not a header) so queued offline saves replay with it.+ pub link_id: Option<ID>,+ /// Message this draft replies to, when it is a reply.+ pub replying_to_id: Option<ID>,+ /// Provider-assigned draft ID, when the draft already exists upstream.+ pub provider_id: Option<String>,+ /// Provider-assigned thread ID hint.+ pub provider_thread_id: Option<String>,+ /// Thread handle. For replies this is a hint the server may override.+ /// For compose drafts (no reply target) it is client-generated: an+ /// unresolvable handle gets a fresh server-minted thread and is bound+ /// to it, so saves queued offline replay against one thread.+ pub thread_db_id: Option<ID>,+ /// Draft subject line.+ pub subject: String,+ /// To recipients.+ pub to: Option<Vec<SaveEmailDraftContactInput>>,+ /// Cc recipients.+ pub cc: Option<Vec<SaveEmailDraftContactInput>>,+ /// Bcc recipients.+ pub bcc: Option<Vec<SaveEmailDraftContactInput>>,+ /// Plain text body.+ pub body_text: Option<String>,+ /// HTML body, base64 URL-safe (no padding) encoded; the server decodes+ /// and sanitizes it before storing.+ pub body_html: Option<String>,+ /// Macro body.+ pub body_macro: Option<String>,+ /// Scheduled send time (RFC 3339), when the draft is scheduled.+ pub send_time: Option<String>,+}++/// Input for deleting an email draft.+#[derive(InputObject)]+pub struct DeleteEmailDraftInput {+ /// Draft handle to delete: a client-generated ID or a server ID, resolved+ /// like a save's. A handle that is already gone (or was never bound — a+ /// discard can replay before its draft's first save ever committed)+ /// deletes nothing and still succeeds, so a delete queued offline lands+ /// cleanly however late it replays.+ pub draft_id: ID,+}++/// Result of deleting an email draft.+#[derive(SimpleObject)]+pub struct DeleteEmailDraftPayload {+ /// The requested draft ID, echoed for client cache bookkeeping.+ pub draft_id: ID,+ /// Whether a draft row was actually deleted. `false` means the ID was+ /// already gone and the delete was an idempotent no-op.+ pub deleted: bool,+ /// Whether deleting the draft emptied its thread and removed the thread+ /// too (a discarded compose draft that never gained other messages).+ pub thread_deleted: bool,+}++/// Result of creating or updating an email draft.+pub struct SaveEmailDraftPayload<O: EmailThreadMutationOutput> {+ draft_id: Uuid,+ draft: GraphqlSoupEmailMessage,+ thread: O::Thread,+}++/// Result of creating or updating an email draft.+// Repeated on purpose: the schema description comes from the impl's doc,+// while `missing_docs` wants one on the struct.+#[Object(name = "SaveEmailDraftPayload")]+impl<O> SaveEmailDraftPayload<O>+where+ O: EmailThreadMutationOutput,+{+ /// Server-confirmed draft ID: the server-minted row the input's handle+ /// resolved (and is now bound) to. Use it for server-addressed calls;+ /// the handle keeps working for queued saves and deletes.+ async fn draft_id(&self) -> ID {+ ID(self.draft_id.to_string())+ }++ /// The saved draft as a full message record — selected with the thread+ /// page's message fragment so the client cache can hold the draft as a+ /// complete entity (its optimistic layer must satisfy every field the+ /// thread page reads, or the whole page read misses).+ async fn draft(&self) -> &GraphqlSoupEmailMessage {+ &self.draft+ }++ /// The draft's thread, reloaded as its authoritative cache record.+ async fn thread(&self) -> &O::Thread {+ &self.thread+ }+}++/// Builds the payload's message record from the saved draft and its persisted+/// attachments. The service fails the save response if attachment loading fails.+fn saved_draft_message(saved: SavedUserDraft) -> Message {+ let SavedUserDraft {+ draft,+ link,+ created_at,+ updated_at,+ labels,+ attachments,+ attachments_draft,+ attachments_forwarded,+ } = saved;+ // Derived the way the thread loader derives it; the page fragment reads+ // it, so a null here would clobber the cached value on write-through.+ let body_replyless = email_utils::body_replyless::compute_body_replyless(+ Some(&draft.subject),+ draft.body_html.as_deref(),+ draft.body_text.as_deref(),+ );+ Message {+ db_id: draft.db_id,+ provider_id: draft.provider_id,+ thread_db_id: draft.thread_db_id,+ provider_thread_id: draft.provider_thread_id,+ replying_to_id: draft.replying_to_id,+ global_id: None,+ link_id: draft.link_id,+ subject: Some(draft.subject),+ snippet: None,+ provider_history_id: None,+ internal_date_ts: None,+ sent_at: None,+ size_estimate: None,+ is_read: true,+ is_starred: false,+ is_sent: false,+ is_draft: true,+ has_attachments: !attachments.is_empty()+ || !attachments_draft.is_empty()+ || !attachments_forwarded.is_empty(),+ scheduled_send_time: draft.send_time,+ from: Some(ContactInfo {+ email: String::from(link.email_address),+ name: None,+ photo_url: None,+ }),+ to: draft.to,+ cc: draft.cc,+ bcc: draft.bcc,+ labels,+ body_text: draft.body_text,+ body_html_sanitized: draft.body_html,+ body_macro: draft.body_macro,+ body_replyless,+ attachments,+ attachments_draft,+ attachments_forwarded,+ headers_json: draft.headers_json,+ created_at,+ updated_at,+ }+}++/// 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.+fn draft_mutation_error(error: &EmailErr) -> async_graphql::Error {+ let (message, code) = match error {+ EmailErr::MessageAlreadySent(_) => {+ ("email draft has already been sent", "DRAFT_ALREADY_SENT")+ }+ EmailErr::MessageNotFound(_) => ("referenced email message not found", "NOT_FOUND"),+ EmailErr::ThreadNotFound => ("email thread not found", "NOT_FOUND"),+ EmailErr::InboxNotFound => ("email inbox not found", "INBOX_NOT_FOUND"),+ EmailErr::CannotReplyToDraft => ("cannot reply to a draft", "INVALID"),+ EmailErr::Base64DecodeError(_) | EmailErr::Utf8Error(_) => {+ ("email draft body is invalid", "INVALID")+ }+ EmailErr::Unauthorized => ("not authorized to modify email draft", "UNAUTHORIZED"),+ EmailErr::RepoErr(_) => {+ return retryable_draft_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))+}++/// Draft writes use stable identities, so retrying an uncertain outcome is safe.+fn retryable_draft_error(error: async_graphql::Error) -> async_graphql::Error {+ error.extend_with(|_, extensions| {+ extensions.set("code", "INTERNAL");+ extensions.set("retryable", true);+ })+}+fn mutation_error(error: &EmailErr) -> async_graphql::Error {let message = match error {EmailErr::ThreadNotFound | EmailErr::ThreadEmpty => "email thread not found",@@ -242,4 +509,137 @@ wherereload_thread::<O>(ctx, user_id, thread_id).await}++ /// Create or update an email draft and return its thread's authoritative+ /// cache record. The client-generated handle resolves through a+ /// caller-scoped mapping to a server-minted row, so a save replayed from+ /// the offline mutation queue converges instead of duplicating.+ #[tracing::instrument(skip_all, err(Debug))]+ async fn save_email_draft(+ &self,+ ctx: &Context<'_>,+ input: SaveEmailDraftInput,+ ) -> async_graphql::Result<SaveEmailDraftPayload<O>> {+ let user_id = require_authenticated_user(ctx)?;+ let link_id = input+ .link_id+ .clone()+ .map(|id| parse_id(id, "linkId"))+ .transpose()?;+ let draft_input = draft_input_from_graphql(input)?;+ let service = ctx.data::<Arc<S>>()?;++ let saved = service+ .save_email_draft(user_id.clone(), link_id, draft_input)+ .await+ .map_err(|error| {+ tracing::error!(+ error = ?error,+ user_id = %user_id,+ "failed to save email draft"+ );+ draft_mutation_error(&error)+ })?;++ let draft_id = saved.draft.db_id;+ let thread = reload_thread::<O>(ctx, user_id, saved.draft.thread_db_id)+ .await+ .map_err(retryable_draft_error)?;+ Ok(SaveEmailDraftPayload {+ draft_id,+ draft: GraphqlSoupEmailMessage::from_content(EmailContentMessage::from(+ saved_draft_message(saved),+ )),+ thread,+ })+ }++ /// Delete an email draft. Idempotent: deleting an ID that is already+ /// gone succeeds with `deleted: false`, so a delete replayed from the+ /// offline mutation queue lands cleanly however late it arrives.+ /// Deleting a draft that has since been sent fails with+ /// `DRAFT_ALREADY_SENT`.+ #[tracing::instrument(skip_all, err(Debug))]+ async fn delete_email_draft(+ &self,+ ctx: &Context<'_>,+ input: DeleteEmailDraftInput,+ ) -> async_graphql::Result<DeleteEmailDraftPayload> {+ let user_id = require_authenticated_user(ctx)?;+ let draft_id = parse_id(input.draft_id, "draftId")?;+ let service = ctx.data::<Arc<S>>()?;++ let deleted = service+ .delete_email_draft(user_id.clone(), draft_id)+ .await+ .map_err(|error| {+ tracing::error!(+ error = ?error,+ user_id = %user_id,+ %draft_id,+ "failed to delete email draft"+ );+ draft_mutation_error(&error)+ })?;++ Ok(DeleteEmailDraftPayload {+ draft_id: ID(draft_id.to_string()),+ deleted: deleted.deleted,+ thread_deleted: deleted.thread_deleted,+ })+ }+}++/// Convert transport input into the domain draft input. Drafts carry no+/// actor: attribution happens when the draft is actually sent.+fn draft_input_from_graphql(input: SaveEmailDraftInput) -> async_graphql::Result<CreateDraftInput> {+ let send_time = input+ .send_time+ .as_deref()+ .map(|raw| {+ chrono::DateTime::parse_from_rfc3339(raw)+ .map(|time| time.with_timezone(&Utc))+ .map_err(|_| {+ async_graphql::Error::new("sendTime is not a valid RFC 3339 timestamp")+ .extend_with(|_, extensions| extensions.set("code", "INVALID"))+ })+ })+ .transpose()?;++ Ok(CreateDraftInput {+ db_id: Some(parse_id(input.draft_id, "draftId")?),+ provider_id: input.provider_id,+ replying_to_id: input+ .replying_to_id+ .map(|id| parse_id(id, "replyingToId"))+ .transpose()?,+ provider_thread_id: input.provider_thread_id,+ thread_db_id: input+ .thread_db_id+ .map(|id| parse_id(id, "threadDbId"))+ .transpose()?,+ subject: input.subject,+ to: contacts_from_inputs(input.to),+ cc: contacts_from_inputs(input.cc),+ bcc: contacts_from_inputs(input.bcc),+ body_text: input.body_text,+ body_html: input.body_html,+ body_macro: input.body_macro,+ headers_json: None,+ send_time,+ include_signature: None,+ actor: None,+ // Handle resolution (and any binding) is owned by the user-scoped+ // save, never by transport input.+ draft_client_binding: None,+ thread_client_binding: None,+ })+}++fn contacts_from_inputs(inputs: Option<Vec<SaveEmailDraftContactInput>>) -> Vec<ContactInfo> {+ inputs+ .unwrap_or_default()+ .into_iter()+ .map(ContactInfo::from)+ .collect()}diff --git a/crates/graphql_email/src/mutation/test.rs b/crates/graphql_email/src/mutation/test.rsindex c55d773794..9ffe67d858 100644--- a/crates/graphql_email/src/mutation/test.rs+++ b/crates/graphql_email/src/mutation/test.rs@@ -1,6 +1,7 @@use std::sync::Mutex;use async_graphql::{EmptySubscription, Object, Schema, SimpleObject};+use email::domain::models::{AttachmentDraft, AttachmentForwarded, MessageAttachment};use super::*;@@ -29,14 +30,36 @@ enum CapturedMutation {label_id: Uuid,value: bool,},+ Draft {+ user_id: String,+ link_id: Option<Uuid>,+ db_id: Option<Uuid>,+ replying_to_id: Option<Uuid>,+ subject: String,+ body_html: Option<String>,+ send_time: Option<String>,+ },+ DeleteDraft {+ user_id: String,+ draft_id: Uuid,+ },}#[derive(Default)]struct CapturingEmailMutationService {calls: Mutex<Vec<CapturedMutation>>,+ draft_fails_as_already_sent: std::sync::atomic::AtomicBool,+ delete_reports_missing: std::sync::atomic::AtomicBool,+ attachment_load_fails: bool,+ thread_load_fails: bool,+ attachments: Vec<MessageAttachment>,+ attachments_draft: Vec<AttachmentDraft>,+ attachments_forwarded: Vec<AttachmentForwarded>,reject_unread: bool,}+const TEST_THREAD_ID: Uuid = Uuid::from_u128(0x7ead);+impl EmailMutationService for CapturingEmailMutationService {async fn mark_email_thread_seen(&self,@@ -83,10 +106,138 @@ impl EmailMutationService for CapturingEmailMutationService {failed_ids: Vec::new(),})}++ async fn save_email_draft(+ &self,+ user_id: MacroUserIdStr<'static>,+ link_id: Option<Uuid>,+ input: CreateDraftInput,+ ) -> Result<SavedUserDraft, EmailErr> {+ if self+ .draft_fails_as_already_sent+ .load(std::sync::atomic::Ordering::SeqCst)+ {+ return Err(EmailErr::MessageAlreadySent(+ input.db_id.unwrap_or_default(),+ ));+ }+ self.calls.lock().unwrap().push(CapturedMutation::Draft {+ user_id: user_id.to_string(),+ link_id,+ db_id: input.db_id,+ replying_to_id: input.replying_to_id,+ subject: input.subject.clone(),+ body_html: input.body_html.clone(),+ send_time: input.send_time.map(|time| time.to_rfc3339()),+ });+ if self.attachment_load_fails {+ return Err(EmailErr::RepoErr(+ std::io::Error::other("attachment loading failed").into(),+ ));+ }+ Ok(SavedUserDraft {+ draft: email::domain::models::CreatedDraft {+ db_id: input.db_id.unwrap_or_default(),+ provider_id: input.provider_id,+ replying_to_id: input.replying_to_id,+ provider_thread_id: input.provider_thread_id,+ thread_db_id: TEST_THREAD_ID,+ link_id: link_id.unwrap_or_default(),+ subject: input.subject,+ to: input.to,+ cc: input.cc,+ bcc: input.bcc,+ body_text: input.body_text,+ body_html: input.body_html,+ body_macro: input.body_macro,+ headers_json: input.headers_json,+ send_time: input.send_time,+ },+ link: test_sending_link(link_id.unwrap_or_default()),+ created_at: "2020-01-02T03:04:05Z".parse().unwrap(),+ updated_at: "2026-02-03T04:05:06Z".parse().unwrap(),+ labels: vec![email::domain::models::MessageLabel {+ id: Some(Uuid::from_u128(7)),+ link_id: link_id.unwrap_or_default(),+ provider_label_id: "DRAFT".to_string(),+ name: Some("Drafts".to_string()),+ created_at: "2020-01-02T03:04:05Z".parse().unwrap(),+ message_list_visibility: None,+ label_list_visibility: None,+ type_: None,+ }],+ attachments: self.attachments.clone(),+ attachments_draft: self.attachments_draft.clone(),+ attachments_forwarded: self.attachments_forwarded.clone(),+ })+ }++ async fn delete_email_draft(+ &self,+ user_id: MacroUserIdStr<'static>,+ draft_id: Uuid,+ ) -> Result<DeletedUserDraft, EmailErr> {+ if self+ .draft_fails_as_already_sent+ .load(std::sync::atomic::Ordering::SeqCst)+ {+ return Err(EmailErr::MessageAlreadySent(draft_id));+ }+ self.calls+ .lock()+ .unwrap()+ .push(CapturedMutation::DeleteDraft {+ user_id: user_id.to_string(),+ draft_id,+ });+ if self+ .delete_reports_missing+ .load(std::sync::atomic::Ordering::SeqCst)+ {+ return Ok(DeletedUserDraft {+ deleted: false,+ thread_deleted: false,+ });+ }+ Ok(DeletedUserDraft {+ deleted: true,+ thread_deleted: true,+ })+ }+}++fn test_sending_link(id: Uuid) -> email::domain::models::Link {+ email::domain::models::Link {+ id,+ macro_id: MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ fusionauth_user_id: "fa-user".to_string(),+ email_address: macro_user_id::email::EmailStr::try_from("[email protected]".to_string())+ .unwrap(),+ provider: email::domain::models::UserProvider::Gmail,+ is_sync_active: true,+ is_primary: true,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ }}struct TestEmailThreadOutput;+#[test]+fn deterministic_draft_rejections_do_not_allow_retries() {+ for error in [+ EmailErr::MessageAlreadySent(Uuid::nil()),+ EmailErr::MessageNotFound(Uuid::nil()),+ EmailErr::ThreadNotFound,+ EmailErr::InboxNotFound,+ EmailErr::CannotReplyToDraft,+ EmailErr::Unauthorized,+ ] {+ let mapped = draft_mutation_error(&error);+ assert_eq!(mapped.extensions.as_ref().unwrap().get("retryable"), None);+ }+}+#[derive(SimpleObject)]struct TestEmailThread {id: ID,@@ -97,12 +248,18 @@ impl EmailThreadMutationOutput for TestEmailThreadOutput {type Thread = TestEmailThread;fn load_email_thread<'ctx>(- _ctx: &'ctx Context<'_>,+ ctx: &'ctx Context<'_>,_user_id: MacroUserIdStr<'static>,thread_id: Uuid,) -> Pin<Box<dyn Future<Output = async_graphql::Result<Option<Self::Thread>>> + Send + 'ctx>>{Box::pin(async move {+ if ctx+ .data::<Arc<CapturingEmailMutationService>>()?+ .thread_load_fails+ {+ return Err(async_graphql::Error::new("thread loading failed"));+ }Ok(Some(TestEmailThread {id: ID(thread_id.to_string()),is_read: true,@@ -254,3 +411,367 @@ async fn update_label_calls_the_email_service_and_returns_the_reloaded_thread()}]);}++#[tokio::test]+async fn save_email_draft_calls_the_service_and_returns_the_payload() {+ let service = Arc::new(CapturingEmailMutationService::default());+ let draft_id = Uuid::new_v4();+ let link_id = Uuid::new_v4();+ let replying_to_id = Uuid::new_v4();+ let response = schema(service.clone())+ .execute(format!(+ r#"mutation {{ saveEmailDraft(input: {{+ draftId: "{draft_id}",+ linkId: "{link_id}",+ replyingToId: "{replying_to_id}",+ subject: "Re: hello",+ bodyHtml: "PHA-aGk8L3A",+ sendTime: "2026-08-27T12:00:00+00:00"+ }}) {{ draftId draft {{ id isDraft isSent subject createdAt updatedAt labels {{ providerLabelId name }} from {{ email }} hasAttachments attachments {{ id }} attachmentsDraft {{ id }} attachmentsForwarded {{ attachmentId }} }} thread {{ id isRead }} }} }}"#+ ))+ .await;++ assert!(response.errors.is_empty(), "{:?}", response.errors);+ assert_eq!(+ response.data.into_json().unwrap()["saveEmailDraft"],+ serde_json::json!({+ "draftId": draft_id,+ "draft": {+ "id": draft_id,+ "isDraft": true,+ "isSent": false,+ "subject": "Re: hello",+ "createdAt": "2020-01-02T03:04:05+00:00",+ "updatedAt": "2026-02-03T04:05:06+00:00",+ "labels": [{ "providerLabelId": "DRAFT", "name": "Drafts" }],+ "from": { "email": "[email protected]" },+ "hasAttachments": false,+ "attachments": [],+ "attachmentsDraft": [],+ "attachmentsForwarded": [],+ },+ "thread": { "id": TEST_THREAD_ID, "isRead": true },+ })+ );+ assert_eq!(+ *service.calls.lock().unwrap(),+ vec![CapturedMutation::Draft {+ user_id: "macro|[email protected]".to_string(),+ link_id: Some(link_id),+ db_id: Some(draft_id),+ replying_to_id: Some(replying_to_id),+ subject: "Re: hello".to_string(),+ body_html: Some("PHA-aGk8L3A".to_string()),+ send_time: Some("2026-08-27T12:00:00+00:00".to_string()),+ }]+ );+}++#[tokio::test]+async fn save_email_draft_derives_the_replyless_body_the_thread_page_reads() {+ // The page fragment selects bodyReplyless; a null here would overwrite the+ // cached value when the mutation response is written through.+ let service = Arc::new(CapturingEmailMutationService::default());+ let draft_id = Uuid::new_v4();+ let response = schema(service)+ .execute(format!(+ r#"mutation {{ saveEmailDraft(input: {{+ draftId: "{draft_id}",+ subject: "hello",+ bodyHtml: "PHA-aGk8L3A"+ }}) {{ draft {{ bodyHtmlSanitized bodyReplyless }} }} }}"#+ ))+ .await;++ assert!(response.errors.is_empty(), "{:?}", response.errors);+ let draft = response.data.into_json().unwrap()["saveEmailDraft"]["draft"].clone();+ assert!(draft["bodyHtmlSanitized"].is_string());+ assert!(+ draft["bodyReplyless"].is_string(),+ "bodyReplyless should be derived from the saved body, got {draft}"+ );+}++#[tokio::test]+async fn save_email_draft_returns_each_kind_of_persisted_attachment() {+ let draft_id = Uuid::now_v7();+ let attachment_id = Uuid::now_v7();+ let services = [+ CapturingEmailMutationService {+ attachments: vec![MessageAttachment {+ db_id: attachment_id,+ provider_id: Some("provider-attachment".to_string()),+ filename: Some("provider.txt".to_string()),+ mime_type: Some("text/plain".to_string()),+ size_bytes: Some(42),+ sfs_id: None,+ content_id: None,+ }],+ ..Default::default()+ },+ CapturingEmailMutationService {+ attachments_draft: vec![AttachmentDraft {+ id: attachment_id,+ draft_id,+ file_name: "upload.txt".to_string(),+ content_type: "text/plain".to_string(),+ sha: "digest".to_string(),+ size: 42,+ s3_key: "uploads/file".to_string(),+ }],+ ..Default::default()+ },+ CapturingEmailMutationService {+ attachments_forwarded: vec![AttachmentForwarded {+ attachment_id,+ draft_id,+ provider_attachment_id: Some("forwarded-attachment".to_string()),+ message_provider_id: "original-message".to_string(),+ filename: Some("forwarded.txt".to_string()),+ mime_type: Some("text/plain".to_string()),+ size_bytes: Some(42),+ }],+ ..Default::default()+ },+ ];+ let expected_attachments = [+ serde_json::json!({"id": attachment_id, "filename": "provider.txt"}),+ serde_json::json!({"id": attachment_id, "draftId": draft_id, "fileName": "upload.txt"}),+ serde_json::json!({"attachmentId": attachment_id, "draftId": draft_id, "filename": "forwarded.txt"}),+ ];+ let fields = ["attachments", "attachmentsDraft", "attachmentsForwarded"];+ for (index, service) in services.into_iter().enumerate() {+ let response = schema(Arc::new(service))+ .execute(format!(+ r#"mutation {{ saveEmailDraft(input: {{ draftId: "{draft_id}", subject: "updated" }}) {{+ draft {{+ hasAttachments+ attachments {{ id filename }}+ attachmentsDraft {{ id draftId fileName }}+ attachmentsForwarded {{ attachmentId draftId filename }}+ }}+ }} }}"#+ ))+ .await;+ assert!(response.errors.is_empty(), "{:?}", response.errors);+ let data = response.data.into_json().unwrap();+ let draft = &data["saveEmailDraft"]["draft"];+ assert_eq!(draft["hasAttachments"], true);+ for (field_index, field) in fields.iter().enumerate() {+ let expected = if field_index == index {+ serde_json::json!([expected_attachments[index]])+ } else {+ serde_json::json!([])+ };+ assert_eq!(draft[field], expected);+ }+ }+}++#[tokio::test]+async fn save_email_draft_does_not_return_a_message_when_attachment_loading_fails() {+ let service = Arc::new(CapturingEmailMutationService {+ attachment_load_fails: true,+ ..Default::default()+ });+ let draft_id = Uuid::now_v7();+ let response = schema(service)+ .execute(format!(+ r#"mutation {{ saveEmailDraft(input: {{ draftId: "{draft_id}", subject: "s" }}) {{+ draft {{ id hasAttachments attachments {{ id }} attachmentsDraft {{ id }} attachmentsForwarded {{ attachmentId }} }}+ }} }}"#+ ))+ .await;++ assert_eq!(response.errors.len(), 1);+ assert!(format!("{:?}", response.errors[0].extensions).contains("INTERNAL"));+ assert_eq!(+ response.errors[0]+ .extensions+ .as_ref()+ .unwrap()+ .get("retryable"),+ Some(&async_graphql::Value::Boolean(true))+ );+ assert!(response.data.into_json().unwrap().is_null());+}++#[tokio::test]+async fn save_email_draft_can_retry_when_the_post_save_thread_reload_fails() {+ let service = Arc::new(CapturingEmailMutationService {+ thread_load_fails: true,+ ..Default::default()+ });+ let response = schema(service.clone())+ .execute(format!(+ r#"mutation {{ saveEmailDraft(input: {{ draftId: "{}", subject: "s" }}) {{ draftId thread {{ id }} }} }}"#,+ Uuid::now_v7()+ ))+ .await;++ assert_eq!(service.calls.lock().unwrap().len(), 1);+ assert_eq!(response.errors.len(), 1);+ let extensions = response.errors[0].extensions.as_ref().unwrap();+ assert_eq!(+ extensions.get("code"),+ Some(&async_graphql::Value::from("INTERNAL"))+ );+ assert_eq!(+ extensions.get("retryable"),+ Some(&async_graphql::Value::Boolean(true))+ );+ assert!(response.data.into_json().unwrap().is_null());+}++#[tokio::test]+async fn save_email_draft_defaults_to_the_primary_inbox() {+ let service = Arc::new(CapturingEmailMutationService::default());+ let draft_id = Uuid::new_v4();+ let response = schema(service.clone())+ .execute(format!(+ r#"mutation {{ saveEmailDraft(input: {{ draftId: "{draft_id}", subject: "s" }}) {{ draftId }} }}"#+ ))+ .await;++ assert!(response.errors.is_empty(), "{:?}", response.errors);+ match service.calls.lock().unwrap().as_slice() {+ [CapturedMutation::Draft { link_id, .. }] => assert_eq!(*link_id, None),+ other => panic!("unexpected calls: {other:?}"),+ }+}++#[tokio::test]+async fn save_email_draft_rejects_invalid_send_time() {+ let service = Arc::new(CapturingEmailMutationService::default());+ let draft_id = Uuid::new_v4();+ let response = schema(service.clone())+ .execute(format!(+ r#"mutation {{ saveEmailDraft(input: {{ draftId: "{draft_id}", subject: "s", sendTime: "tomorrow" }}) {{ draftId }} }}"#+ ))+ .await;++ assert_eq!(response.errors.len(), 1);+ assert!(response.errors[0].message.contains("sendTime"));+ assert!(format!("{:?}", response.errors[0].extensions).contains("INVALID"));+ assert!(service.calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn save_email_draft_maps_already_sent_to_a_machine_readable_code() {+ let service = Arc::new(CapturingEmailMutationService::default());+ service+ .draft_fails_as_already_sent+ .store(true, std::sync::atomic::Ordering::SeqCst);+ let draft_id = Uuid::new_v4();+ let response = schema(service.clone())+ .execute(format!(+ r#"mutation {{ saveEmailDraft(input: {{ draftId: "{draft_id}", subject: "s" }}) {{ draftId }} }}"#+ ))+ .await;++ assert_eq!(response.errors.len(), 1);+ assert_eq!(+ response.errors[0].message,+ "email draft has already been sent"+ );+ assert!(format!("{:?}", response.errors[0].extensions).contains("DRAFT_ALREADY_SENT"));+}++#[tokio::test]+async fn save_email_draft_rejects_a_malformed_draft_id() {+ let service = Arc::new(CapturingEmailMutationService::default());+ let response = schema(service.clone())+ .execute(+ r#"mutation { saveEmailDraft(input: { draftId: "not-a-uuid", subject: "s" }) { draftId } }"#,+ )+ .await;++ assert_eq!(response.errors.len(), 1);+ assert!(response.errors[0].message.contains("draftId"));+ assert!(service.calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn delete_email_draft_calls_the_service_and_returns_the_payload() {+ let service = Arc::new(CapturingEmailMutationService::default());+ let draft_id = Uuid::new_v4();+ let response = schema(service.clone())+ .execute(format!(+ r#"mutation {{ deleteEmailDraft(input: {{ draftId: "{draft_id}" }}) {{ draftId deleted threadDeleted }} }}"#+ ))+ .await;++ assert!(response.errors.is_empty(), "{:?}", response.errors);+ assert_eq!(+ response.data.into_json().unwrap()["deleteEmailDraft"],+ serde_json::json!({+ "draftId": draft_id,+ "deleted": true,+ "threadDeleted": true,+ })+ );+ assert_eq!(+ *service.calls.lock().unwrap(),+ vec![CapturedMutation::DeleteDraft {+ user_id: "macro|[email protected]".to_string(),+ draft_id,+ }]+ );+}++#[tokio::test]+async fn delete_email_draft_reports_an_absent_id_as_a_no_op() {+ let service = Arc::new(CapturingEmailMutationService::default());+ service+ .delete_reports_missing+ .store(true, std::sync::atomic::Ordering::SeqCst);+ let draft_id = Uuid::new_v4();+ let response = schema(service.clone())+ .execute(format!(+ r#"mutation {{ deleteEmailDraft(input: {{ draftId: "{draft_id}" }}) {{ draftId deleted threadDeleted }} }}"#+ ))+ .await;++ assert!(response.errors.is_empty(), "{:?}", response.errors);+ assert_eq!(+ response.data.into_json().unwrap()["deleteEmailDraft"],+ serde_json::json!({+ "draftId": draft_id,+ "deleted": false,+ "threadDeleted": false,+ })+ );+}++#[tokio::test]+async fn delete_email_draft_maps_already_sent_to_a_machine_readable_code() {+ let service = Arc::new(CapturingEmailMutationService::default());+ service+ .draft_fails_as_already_sent+ .store(true, std::sync::atomic::Ordering::SeqCst);+ let draft_id = Uuid::new_v4();+ let response = schema(service.clone())+ .execute(format!(+ r#"mutation {{ deleteEmailDraft(input: {{ draftId: "{draft_id}" }}) {{ draftId }} }}"#+ ))+ .await;++ assert_eq!(response.errors.len(), 1);+ assert_eq!(+ response.errors[0].message,+ "email draft has already been sent"+ );+ assert!(format!("{:?}", response.errors[0].extensions).contains("DRAFT_ALREADY_SENT"));+}++#[tokio::test]+async fn delete_email_draft_rejects_a_malformed_draft_id() {+ let service = Arc::new(CapturingEmailMutationService::default());+ let response = schema(service.clone())+ .execute(r#"mutation { deleteEmailDraft(input: { draftId: "not-a-uuid" }) { draftId } }"#)+ .await;++ assert_eq!(response.errors.len(), 1);+ assert!(response.errors[0].message.contains("draftId"));+ assert!(service.calls.lock().unwrap().is_empty());+}diff --git a/crates/graphql_email/src/objects.rs b/crates/graphql_email/src/objects.rsindex 3dd5c7f53f..25fc33e89c 100644--- a/crates/graphql_email/src/objects.rs+++ b/crates/graphql_email/src/objects.rs@@ -68,6 +68,12 @@ impl From<email::domain::models::EmailPreview> for GraphqlMailPreviewMessage {pub struct GraphqlSoupEmailMessage(EmailContentMessage);impl GraphqlSoupEmailMessage {+ /// Wraps a message produced outside the DataLoader path (e.g. a+ /// mutation payload's draft record).+ pub(crate) fn from_content(message: EmailContentMessage) -> Self {+ Self(message)+ }+fn parsed(&self) -> &ParsedMessage {self.0.parsed()}diff --git a/crates/macro_db_client/migrations/20260831182511_email_client_id_mappings.sql b/crates/macro_db_client/migrations/20260831182511_email_client_id_mappings.sqlnew file mode 100644index 0000000000..7ea86cd9f1--- /dev/null+++ b/crates/macro_db_client/migrations/20260831182511_email_client_id_mappings.sql@@ -0,0 +1,33 @@+-- Client-generated draft/thread identity as lookup aliases, never PKs.+--+-- Offline clients mint ids for drafts (and compose threads) so queued saves+-- replay idempotently. Those ids are untrusted input: they must not become+-- primary keys in the shared email tables (v7 index locality, id-space+-- squatting, create-on-unknown-id). Instead each client id maps to a+-- server-minted row, scoped by the binding inbox. Lookups scope to the+-- caller's accessible links, so identical client ids from different users+-- never interact. The (link_id, client_id) primary key is the idempotency+-- fence for replayed creates; ON DELETE CASCADE makes discard cleanup free.++CREATE TABLE email_draft_client_ids (+ client_id uuid NOT NULL,+ link_id uuid NOT NULL REFERENCES email_links (id) ON DELETE CASCADE,+ message_id uuid NOT NULL REFERENCES email_messages (id) ON DELETE CASCADE,+ created_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (link_id, client_id)+);++-- Cascade deletes and reverse lookups arrive by message id.+CREATE INDEX idx_email_draft_client_ids_message_id+ ON email_draft_client_ids (message_id);++CREATE TABLE email_thread_client_ids (+ client_id uuid NOT NULL,+ link_id uuid NOT NULL REFERENCES email_links (id) ON DELETE CASCADE,+ thread_id uuid NOT NULL REFERENCES email_threads (id) ON DELETE CASCADE,+ created_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (link_id, client_id)+);++CREATE INDEX idx_email_thread_client_ids_thread_id+ ON email_thread_client_ids (thread_id);diff --git a/crates/soup/src/inbound/axum_router/tests.rs b/crates/soup/src/inbound/axum_router/tests.rsindex bccbc16032..a586569b9e 100644--- a/crates/soup/src/inbound/axum_router/tests.rs+++ b/crates/soup/src/inbound/axum_router/tests.rs@@ -315,6 +315,23 @@ impl EmailService for MockEmail {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}+ async fn save_draft_for_user(+ &self,+ _macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ _link_id: Option<uuid::Uuid>,+ _input: email::domain::models::CreateDraftInput,+ ) -> Result<email::domain::models::SavedUserDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }++ async fn delete_draft_for_user(+ &self,+ _macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ _draft_id: uuid::Uuid,+ ) -> Result<email::domain::models::DeletedUserDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }+async fn send_message(&self,_link: &email::domain::models::Link,@@ -755,6 +772,23 @@ impl EmailService for MockEmailLinkResult {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}+ async fn save_draft_for_user(+ &self,+ _macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ _link_id: Option<uuid::Uuid>,+ _input: email::domain::models::CreateDraftInput,+ ) -> Result<email::domain::models::SavedUserDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }++ async fn delete_draft_for_user(+ &self,+ _macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ _draft_id: uuid::Uuid,+ ) -> Result<email::domain::models::DeletedUserDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }+async fn send_message(&self,_link: &email::domain::models::Link,diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 50f9e54544..7effec387f 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -380,6 +380,8 @@ 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 oneand press Enter or Space. Removal is a separate button named `Remove <filename>`.Removing a forwarded file keeps the received original.+When checking draft autosave, edit the body of a draft with uploaded or forwarded+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 subjectis not required to save the body.The three-dot button beneath a body reveals quoted content and a trimmed@@ -398,6 +400,22 @@ A failure from an older, unmounted editor must not overwrite a newer edited replA presentation or refresh error after successful delivery is not a reason to sendagain.+Send and schedule are refused with a notice while the device is offline, while a+draft is still syncing (its save was accepted locally but not yet confirmed by the+server; retry after a moment), or while an attachment has no completed upload. The+composer keeps its content in each case. Attachments cannot be added while+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.+Test this with a previously saved draft as well as a new one: a queued edit must+block Send and scheduling until a save commits. Reopening a cached draft while+offline must retain its uploaded attachments and confirmed scheduled time.+While a schedule change is pending, immediate send and further schedule changesare disabled. Reply recipients cannot be edited or dragged during scheduling,sending, or discarding. A failed schedule or unschedule keeps the last confirmed time.diff --git a/docs/EMAIL_FEATURE_ARCHITECTURE.md b/docs/EMAIL_FEATURE_ARCHITECTURE.mdindex 6060e6c15f..c09e399525 100644--- a/docs/EMAIL_FEATURE_ARCHITECTURE.md+++ b/docs/EMAIL_FEATURE_ARCHITECTURE.md@@ -155,6 +155,8 @@ The compose controllers now assemble these smaller responsibilities:| --- | --- || `attachment-persistence.ts` | Upload/remove operations and completion tracking. Receives attachment state and three transport capabilities. A saved attachment ID does not mean its content upload has finished; every save waits for outstanding uploads. || `email-send-schedule.ts` | Confirmed send time, pending changes, unscheduling and archive feedback. Scheduling saves the current draft and waits for its attachments even when a draft ID already exists; each operation retains its selected inbox. |+| `draft-session.ts` / `draft-persistence.ts` | Shared draft identity, queued-write status, rejection policy, and save/delete ordering. Server identity and a committed latest save are separate facts; REST send, schedule, and uploads wait for a committed save. |+| `send-readiness.ts` | Why an immediate send must be refused: offline, a draft the server cannot address yet (queued or unconfirmed handle), or an attachment whose upload never finished. Pure checks plus the one failure notice both controllers show. || `draft-autosave.ts` | One debounce and serialized write queue used by reply and standalone compose. Captures editor values before queueing, flushes pending edits on disposal, and exposes cancellation and completion for send/discard. || `reply-recipient-fields.ts` | Recipient field expansion, drag/drop and outside interaction. Receives values, a setter and a change callback; it knows nothing about saving or sending. || `reply-composer-focus.ts` | Deferred editor/recipient focus and the forward focus guard. Receives DOM accessors and an editor `focus()` capability. Its timers, animation frames and event listeners end with its owner. |diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 51f51b193e..08474785bf 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -131,6 +131,21 @@ type CompleteMutationRoot {Add or remove one label from an accessible email thread and return its authoritative cache record."""updateEmailThreadLabel(input: UpdateEmailThreadLabelInput!): GraphqlSoupEmailThread!+ """+ Create or update an email draft and return its thread's authoritative+ cache record. The client-generated handle resolves through a+ caller-scoped mapping to a server-minted row, so a save replayed from+ the offline mutation queue converges instead of duplicating.+ """+ saveEmailDraft(input: SaveEmailDraftInput!): SaveEmailDraftPayload!+ """+ Delete an email draft. Idempotent: deleting an ID that is already+ gone succeeds with `deleted: false`, so a delete replayed from the+ offline mutation queue lands cleanly however late it arrives.+ Deleting a draft that has since been sent fails with+ `DRAFT_ALREADY_SENT`.+ """+ deleteEmailDraft(input: DeleteEmailDraftInput!): DeleteEmailDraftPayload!}"""@@ -152,6 +167,40 @@ type CompleteSubscriptionRoot {activityUpdates: GraphqlActivityPatch!}+"""+Input for deleting an email draft.+"""+input DeleteEmailDraftInput {+ """+ Draft handle to delete: a client-generated ID or a server ID, resolved+ like a save's. A handle that is already gone (or was never bound — a+ discard can replay before its draft's first save ever committed)+ deletes nothing and still succeeds, so a delete queued offline lands+ cleanly however late it replays.+ """+ draftId: ID!+}++"""+Result of deleting an email draft.+"""+type DeleteEmailDraftPayload {+ """+ The requested draft ID, echoed for client cache bookkeeping.+ """+ draftId: ID!+ """+ Whether a draft row was actually deleted. `false` means the ID was+ already gone and the delete was an idempotent no-op.+ """+ deleted: Boolean!+ """+ Whether deleting the draft emptied its thread and removed the thread+ too (a discarded compose draft that never gained other messages).+ """+ threadDeleted: Boolean!+}+"""One entity duplication in a batch."""@@ -6006,6 +6055,124 @@ input ReorderFavoritesInput {favorites: [EntityRefInput!]!}+"""+One recipient of an email draft.+"""+input SaveEmailDraftContactInput {+ """+ Recipient email address.+ """+ email: String!+ """+ Recipient display name, when known.+ """+ name: String+ """+ Recipient photo URL, when known.+ """+ photoUrl: String+}++"""+Input for creating or updating an email draft.++The draft ID is a client-generated handle so a save queued offline stays+an idempotent upsert when it replays later — possibly after an app+restart, possibly more than once. Handles are untrusted input and never+become primary keys: the server resolves them through a caller-scoped+mapping to server-minted rows. Thread identifiers are hints: the server+derives authoritative thread linkage from the reply target or the+existing draft.+"""+input SaveEmailDraftInput {+ """+ Draft handle: a client-generated ID, or a server ID from a fetched+ draft. Resolved scoped to the caller's inboxes, and bound to the+ server row the save settles on, so replays converge on one draft.+ """+ draftId: ID!+ """+ Sending inbox. Absent means the caller's primary inbox. Carried as a+ variable (not a header) so queued offline saves replay with it.+ """+ linkId: ID+ """+ Message this draft replies to, when it is a reply.+ """+ replyingToId: ID+ """+ Provider-assigned draft ID, when the draft already exists upstream.+ """+ providerId: String+ """+ Provider-assigned thread ID hint.+ """+ providerThreadId: String+ """+ Thread handle. For replies this is a hint the server may override.+ For compose drafts (no reply target) it is client-generated: an+ unresolvable handle gets a fresh server-minted thread and is bound+ to it, so saves queued offline replay against one thread.+ """+ threadDbId: ID+ """+ Draft subject line.+ """+ subject: String!+ """+ To recipients.+ """+ to: [SaveEmailDraftContactInput!]+ """+ Cc recipients.+ """+ cc: [SaveEmailDraftContactInput!]+ """+ Bcc recipients.+ """+ bcc: [SaveEmailDraftContactInput!]+ """+ Plain text body.+ """+ bodyText: String+ """+ HTML body, base64 URL-safe (no padding) encoded; the server decodes+ and sanitizes it before storing.+ """+ bodyHtml: String+ """+ Macro body.+ """+ bodyMacro: String+ """+ Scheduled send time (RFC 3339), when the draft is scheduled.+ """+ sendTime: String+}++"""+Result of creating or updating an email draft.+"""+type SaveEmailDraftPayload {+ """+ Server-confirmed draft ID: the server-minted row the input's handle+ resolved (and is now bound) to. Use it for server-addressed calls;+ the handle keeps working for queued saves and deletes.+ """+ draftId: ID!+ """+ The saved draft as a full message record — selected with the thread+ page's message fragment so the client cache can hold the draft as a+ complete entity (its optimistic layer must satisfy every field the+ thread page reads, or the whole page read misses).+ """+ draft: GraphqlSoupEmailMessage!+ """+ The draft's thread, reloaded as its authoritative cache record.+ """+ thread: GraphqlSoupEmailThread!+}+"""Input for assigning or updating an entity property."""