Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): restore immediate send feedback, Send Later, and the full-screen phone composer (#8606)
Peter Chinman95bf125fa5a1
diff --git a/apps/web/src/features/email-compose/components/draft-sync-status.test.tsx b/apps/web/src/features/email-compose/components/draft-sync-status.test.tsxdeleted file mode 100644index 8589958f47..0000000000--- a/apps/web/src/features/email-compose/components/draft-sync-status.test.tsx+++ /dev/null@@ -1,77 +0,0 @@-import { cleanup, render, screen } from '@solidjs/testing-library';-import { createSignal } from 'solid-js';-import { afterEach, expect, it, vi } from 'vitest';-import type { DraftSyncViewState } from '../core/local-draft';-import { DraftSyncStatus } from './draft-sync-status';--afterEach(() => {- cleanup();- vi.useRealTimers();-});--const saved = (version: string): DraftSyncViewState => ({- message: 'Draft saved',- savedVersion: version,- failed: false,- canKeepEditing: false,-});--it('hides after two seconds and restarts only for another saved version', () => {- vi.useFakeTimers();- const [state, setState] = createSignal(saved('1'));- render(() => (- <DraftSyncStatus- state={state()}- busy={false}- onRetry={() => {}}- onKeepEditing={() => {}}- />- ));- const label = screen.getByText('Draft saved');- expect(label.getAttribute('aria-hidden')).toBe('false');- vi.advanceTimersByTime(1_500);- // Reading the same version again during queue settlement must not extend it.- setState(saved('1'));- vi.advanceTimersByTime(500);- expect(label.getAttribute('aria-hidden')).toBe('true');- setState(saved('2'));- expect(label.getAttribute('aria-hidden')).toBe('false');- vi.advanceTimersByTime(1_500);- setState(saved('3'));- vi.advanceTimersByTime(500);- expect(label.getAttribute('aria-hidden')).toBe('false');- vi.advanceTimersByTime(1_500);- expect(label.getAttribute('aria-hidden')).toBe('true');-});--it('keeps retry visible until recovery, then briefly acknowledges success', () => {- vi.useFakeTimers();- const [state, setState] = createSignal(saved('1'));- render(() => (- <DraftSyncStatus- state={state()}- busy={false}- onRetry={() => {}}- onKeepEditing={() => {}}- />- ));- setState({- message: 'Draft could not be synced',- failed: true,- action: 'retry',- canKeepEditing: false,- });- vi.advanceTimersByTime(10_000);- expect(screen.getByRole('button', { name: 'Retry' })).toBeDefined();- setState(saved('1'));- expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();- expect(screen.getByText('Draft saved').getAttribute('aria-hidden')).toBe(- 'false'- );- vi.advanceTimersByTime(2_000);- expect(screen.getByText('Draft saved').getAttribute('aria-hidden')).toBe(- 'true'- );- cleanup();- expect(vi.getTimerCount()).toBe(0);-});diff --git a/apps/web/src/features/email-compose/components/draft-sync-status.tsx b/apps/web/src/features/email-compose/components/draft-sync-status.tsxindex 481da80f06..87501f41b0 100644--- a/apps/web/src/features/email-compose/components/draft-sync-status.tsx+++ b/apps/web/src/features/email-compose/components/draft-sync-status.tsx@@ -1,13 +1,8 @@-import {- createEffect,- createMemo,- createSignal,- onCleanup,- Show,-} from 'solid-js';+import { Button } from '@ui';+import { Show } from 'solid-js';import type { DraftSyncViewState } from '../core/local-draft';-/** Durable recovery remains visible after remounting a failed draft. */+/** In-composer banner for draft failures; saving itself stays silent. */export function DraftSyncStatus(props: {state?: DraftSyncViewState;busy: boolean;@@ -15,66 +10,38 @@ export function DraftSyncStatus(props: {onRetry(): void;onKeepEditing(): void;}) {- const [showSaved, setShowSaved] = createSignal(false);- const savedVersion = createMemo(() =>- props.state?.failed || props.error ? undefined : props.state?.savedVersion- );- createEffect(() => {- if (!savedVersion()) {- setShowSaved(false);- return;- }- setShowSaved(true);- const timer = setTimeout(() => setShowSaved(false), 2_000);- onCleanup(() => clearTimeout(timer));- });return (<Show when={props.state}>{(state) => (<div- class="mr-2 flex shrink-0 items-center gap-2 whitespace-nowrap text-xs text-ink-muted"- role={state().failed || props.error ? 'alert' : 'status'}- title={- state().failed || props.error- ? (props.error ?? state().detail ?? state().message)- : undefined- }+ class="flex flex-wrap items-center gap-2 border-b border-edge-muted p-3 text-sm"+ role="alert">- <Show- when={state().action || props.error}- fallback={- <span- class="transition-opacity duration-200 motion-reduce:transition-none"- classList={{ 'opacity-0': !showSaved() }}- aria-hidden={!showSaved()}- >- {state().message}- </span>- }- >- <button- type="button"- class="text-failure-ink underline disabled:opacity-50"+ <div class="min-w-0 flex-1">+ <p>{state().message}</p>+ <Show when={props.error ?? state().detail}>+ {(detail) => <p class="text-xs text-ink-muted">{detail()}</p>}+ </Show>+ </div>+ <Show when={state().action || props.error}>+ <Button+ size="sm"+ variant="outline"disabled={props.busy}onClick={props.onRetry}>{state().action === 'retry-discard' ? 'Retry discard' : 'Retry'}- </button>+ </Button></Show><Show when={state().canKeepEditing}>- <button- type="button"- class="underline"+ <Button+ size="sm"+ variant="outline"disabled={props.busy}onClick={props.onKeepEditing}>Keep editing- </button>- </Show>- <Show when={state().failed || props.error}>- <span class="sr-only">- {props.error ?? state().detail ?? state().message}- </span>+ </Button></Show></div>)}diff --git a/apps/web/src/features/email-compose/components/mobile-compose-actions.tsx b/apps/web/src/features/email-compose/components/mobile-compose-actions.tsxindex bdc4722b6a..6bf629258a 100644--- a/apps/web/src/features/email-compose/components/mobile-compose-actions.tsx+++ b/apps/web/src/features/email-compose/components/mobile-compose-actions.tsx@@ -5,7 +5,6 @@ import { type JSX, Show } from 'solid-js';/** Shared header actions for new emails, replies, and forwards. */export function MobileComposeActions(props: {- status?: JSX.Element;attachRef?: (element: HTMLButtonElement) => void;editingDisabled: boolean;scheduleControl?: JSX.Element;@@ -17,7 +16,6 @@ export function MobileComposeActions(props: {}) {return (<HeaderIsland class="h-(--mobile-chrome-button-size) p-[5px]">- {props.status}<Show when={props.attachRef}><Buttonref={props.attachRef}diff --git a/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx b/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsxindex 6f01efdb08..ce8c48cb6e 100644--- a/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx+++ b/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx@@ -15,7 +15,6 @@ export function MobileReplyToolbar(props: {editingDisabled: boolean;scheduleSummary?: JSX.Element;scheduleControl?: JSX.Element;- status?: JSX.Element;}) {return (<div class="sticky top-0 z-10 flex shrink-0 flex-wrap items-center justify-between gap-2 bg-surface px-(--mobile-chrome-gutter) pb-3 pt-[calc(var(--safe-top,0px)+12px)]">diff --git a/apps/web/src/features/email-compose/compose-adapter.ts b/apps/web/src/features/email-compose/compose-adapter.tsindex 1dd7fd82f8..624934f866 100644--- a/apps/web/src/features/email-compose/compose-adapter.ts+++ b/apps/web/src/features/email-compose/compose-adapter.ts@@ -78,6 +78,7 @@ import {emailSendLocked,emailSendMatchesDraft,sendEmailQueued,+ settledSendAttempt,} from '@queries/email/send-queue';import { serverEmailSends } from '@queries/email/server-sends';import {@@ -505,6 +506,57 @@ export function createEmailComposeContext(},delivery: {queueActive: () => true,+ outgoing: () =>+ sends.intents().flatMap((intent) => {+ const attempt = settledSendAttempt(intent);+ const { draft, input } = intent.metadata.payload;+ if (+ !emailSendLocked(intent) ||+ intent.phase === 'failed' ||+ attempt?.status === 'FAILED' ||+ input.message.sendTime+ )+ return [];+ const contacts = (list: typeof draft.to) =>+ (list ?? []).map((contact) => ({+ email: contact.email,+ name: contact.name,+ photo_url: contact.photoUrl,+ }));+ const ids = (values: (string | null | undefined)[]) => [+ ...new Set(values.filter((value) => !!value).map(String)),+ ];+ return [+ {+ sendAttemptId: intent.uuid,+ messageIds: ids([+ String(input.message.draftId),+ intent.resolvedDraftId,+ attempt?.message?.id,+ ]),+ threadIds: ids([+ draft.threadDbId,+ intent.resolvedThreadId,+ attempt?.threadId,+ ]),+ inboxId: draft.senderLinkId,+ delivered: attempt?.status === 'SENT',+ message: {+ to: contacts(draft.to),+ cc: contacts(draft.cc),+ bcc: contacts(draft.bcc),+ subject: draft.subject,+ body_text: draft.bodyText,+ body_macro: draft.bodyMacro,+ body_html_sanitized: draft.optimisticBodyHtml,+ replying_to_id:+ draft.replyingToId == null+ ? null+ : String(draft.replyingToId),+ },+ },+ ];+ }),sendLocked: (draftId) =>!sends.ready() ||(!!draftId &&diff --git a/apps/web/src/features/email-compose/context/compose-capabilities.ts b/apps/web/src/features/email-compose/context/compose-capabilities.tsindex cba6448d76..404a4f9394 100644--- a/apps/web/src/features/email-compose/context/compose-capabilities.ts+++ b/apps/web/src/features/email-compose/context/compose-capabilities.ts@@ -211,11 +211,35 @@ export interface EmailAttachmentStorage {removeForwardedAttachment(input: EmailAttachmentChange): Promise<void>;}+/** An approved immediate send the thread read may not show yet. */+export interface OutgoingEmail {+ sendAttemptId: string;+ /** The approved draft's handles and, once accepted, the server's message id. */+ messageIds: string[];+ threadIds: string[];+ inboxId: string;+ /** The provider confirmed delivery, so a fresh thread read shows it. */+ delivered: boolean;+ message: Pick<+ EmailMessage,+ | 'to'+ | 'cc'+ | 'bcc'+ | 'subject'+ | 'body_text'+ | 'body_macro'+ | 'body_html_sanitized'+ | 'replying_to_id'+ >;+}+export interface EmailDelivery {/** Whether sends can be persisted and replayed without connectivity. */queueActive?: (inboxId?: string) => boolean;/** Persisted locks, scoped to the composing surface's owner. */sendLocked?: (draftId: string | undefined) => boolean;+ /** Durable sends on their way; cancelled, failed and scheduled sends are excluded. */+ outgoing?: () => OutgoingEmail[];sendMessage(input: SendEmailDraft): Promise<PersistedEmailIdentity>;unschedule(input: {draftGeneration?: number;diff --git a/apps/web/src/features/email-compose/core/local-draft.ts b/apps/web/src/features/email-compose/core/local-draft.tsindex cb0209d5df..048117fea7 100644--- a/apps/web/src/features/email-compose/core/local-draft.ts+++ b/apps/web/src/features/email-compose/core/local-draft.ts@@ -80,8 +80,6 @@ export type DraftAttempt = {/** Presentation of local persistence and explicit server recovery. */export type DraftSyncViewState = {message: string;- /** Identifies a saved version to acknowledge after editing pauses. */- savedVersion?: string;detail?: string;failed: boolean;action?: 'retry' | 'retry-discard';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 5bf09411fc..dd38618103 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@@ -20,51 +20,6 @@ const response: PersistedEmailIdentity = {beforeEach(() => vi.useFakeTimers());afterEach(() => vi.useRealTimers());-it.each(['standalone', 'reply'] as const)(- 'does not acknowledge the %s pre-send save, including after failed delivery',- async (surface) => {- const context = createComposeContext();- context.drafts.saveLocalDraft = vi.fn(async (input) =>- localSnapshot(input)- );- const delivery = Promise.withResolvers<PersistedEmailIdentity>();- vi.mocked(context.delivery.sendMessage).mockReturnValueOnce(- delivery.promise- );- const root =- surface === 'standalone'- ? mountEmailComposer(context)- : mountReplyComposer(context);- const state = 'state' in root ? root.state : root;- try {- root.edit('Send without flashing Draft saved');- await vi.advanceTimersByTimeAsync(0);- let sending: Promise<unknown> | undefined;- if ('state' in root) root.state.context.onSend();- else sending = root.sendEmail();- expect(state.acknowledgeSaved()).toBe(false);- await vi.advanceTimersByTimeAsync(0);- expect(context.delivery.sendMessage).toHaveBeenCalledOnce();- expect(state.localSaveState()).toBe('saved');- expect(state.acknowledgeSaved()).toBe(false);- delivery.reject(new Error('Delivery failed'));- await vi.advanceTimersByTimeAsync(0);- expect(state.acknowledgeSaved()).toBe(false);- root.edit('Keep editing after failure');- await vi.advanceTimersByTimeAsync(500);- expect(state.acknowledgeSaved()).toBe(true);- await sending;- } finally {- delivery.resolve({- draftId: 'sent',- threadId: 'thread',- inboxId: 'inbox',- });- root.dispose();- }- }-);-it('flushes the latest pending body and envelope exactly once on disposal', async () => {const composeContext = createComposeContext();const root = mountEmailComposer(composeContext);diff --git a/apps/web/src/features/email-compose/primitives/draft-autosave.test.ts b/apps/web/src/features/email-compose/primitives/draft-autosave.test.tsindex 54c1735e13..07c6871325 100644--- a/apps/web/src/features/email-compose/primitives/draft-autosave.test.ts+++ b/apps/web/src/features/email-compose/primitives/draft-autosave.test.ts@@ -8,43 +8,7 @@ afterEach(() => {vi.useRealTimers();});-it.each([false, true])(- 'suppresses a delivery flush acknowledgement until another edit (failure=%s)',- async (fails) => {- vi.useFakeTimers();- const persist = vi.fn(async () => {- if (fails) throw new Error('Delivery preparation failed');- });- const local = vi.fn(async () => {});- const autosave = createRoot((dispose) => {- disposers.push(dispose);- return createDraftAutosave({- capture: () => 'draft',- persist,- saveLocalSnapshot: local,- paused: () => false,- });- });- autosave.schedule();- await autosave.flushLocal();- const flush = autosave.save(undefined, { acknowledge: false });- expect(autosave.acknowledgeSaved()).toBe(false);- if (fails)- await expect(flush).rejects.toThrow('Delivery preparation failed');- else await flush;- expect(local).toHaveBeenCalledTimes(2);- await vi.advanceTimersByTimeAsync(2_000);- expect(autosave.acknowledgeSaved()).toBe(false);- fails = false;- autosave.schedule();- await autosave.flushLocal();- expect(autosave.acknowledgeSaved()).toBe(false);- await vi.advanceTimersByTimeAsync(500);- expect(autosave.acknowledgeSaved()).toBe(true);- }-);--it('keeps input active through continuous edits without delaying local saves', async () => {+it('saves locally on every edit and persists once input pauses', async () => {vi.useFakeTimers();const local = vi.fn(async () => {});const persist = vi.fn(async () => {});@@ -61,26 +25,18 @@ it('keeps input active through continuous edits without delaying local saves', aautosave.schedule();await autosave.flushLocal();expect(autosave.localSaveState()).toBe('saved');- expect(autosave.acknowledgeSaved()).toBe(false);expect(local).toHaveBeenCalledTimes(edit + 1);await vi.advanceTimersByTimeAsync(200);- expect(autosave.acknowledgeSaved()).toBe(false);expect(persist).not.toHaveBeenCalled();}await vi.advanceTimersByTimeAsync(299);- expect(autosave.acknowledgeSaved()).toBe(false);+ expect(persist).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(1);- expect(autosave.acknowledgeSaved()).toBe(true);await autosave.settled();expect(persist).toHaveBeenCalledOnce();-- autosave.schedule();- expect(autosave.acknowledgeSaved()).toBe(false);- autosave.cancel();- expect(autosave.acknowledgeSaved()).toBe(true);});-it('distinguishes a typing pause from a slow local save', async () => {+it('reports a slow local save as saving after input pauses', async () => {vi.useFakeTimers();const write = Promise.withResolvers<void>();const autosave = createRoot((dispose) => {@@ -94,7 +50,6 @@ it('distinguishes a typing pause from a slow local save', async () => {});autosave.schedule();await vi.advanceTimersByTimeAsync(500);- expect(autosave.acknowledgeSaved()).toBe(true);expect(autosave.localSaveState()).toBe('saving');write.resolve();await autosave.settled();diff --git a/apps/web/src/features/email-compose/primitives/draft-autosave.ts b/apps/web/src/features/email-compose/primitives/draft-autosave.tsindex 10f7c9bee5..63d1e852b6 100644--- a/apps/web/src/features/email-compose/primitives/draft-autosave.ts+++ b/apps/web/src/features/email-compose/primitives/draft-autosave.ts@@ -16,8 +16,6 @@ export function createDraftAutosave<Snapshot, Result>(options: {let queue: Promise<Result | undefined> = Promise.resolve(undefined);let localWrites: Promise<void> = Promise.resolve();let newestSnapshot = 0;- const [inputIdle, setInputIdle] = createSignal(true);- const [shouldAcknowledge, setShouldAcknowledge] = createSignal(true);const [localSaveState, setLocalSaveState] = createSignal<'saving' | 'saved' | 'failed'>('saved');@@ -54,7 +52,6 @@ export function createDraftAutosave<Snapshot, Result>(options: {const cancel = () => {scheduled.clear();pending = undefined;- setInputIdle(true);};const enqueue = (snapshot: Snapshot, local: Promise<void>) => {const write = async () => {@@ -64,16 +61,11 @@ export function createDraftAutosave<Snapshot, Result>(options: {queue = queue.then(write, write);return queue;};- const save = (- snapshot = options.capture(),- saveOptions: { acknowledge?: boolean } = {}- ) => {- setShouldAcknowledge(saveOptions.acknowledge !== false);+ const save = (snapshot = options.capture()) => {cancel();return enqueue(snapshot, saveLocally(snapshot));};const scheduled = debounce(() => {- setInputIdle(true);if (options.paused()) return;void save().catch((error) => options.onError?.(error));}, 500);@@ -97,11 +89,8 @@ export function createDraftAutosave<Snapshot, Result>(options: {settled: () => queue,flushLocal,localSaveState,- acknowledgeSaved: () => inputIdle() && shouldAcknowledge(),schedule() {if (options.paused()) return;- setShouldAcknowledge(true);- setInputIdle(false);const snapshot = options.capture();pending = { snapshot };void saveLocally(snapshot).catch((error) => options.onError?.(error));diff --git a/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts b/apps/web/src/features/email-compose/primitives/draft-sync-status.test.tsindex 4a9a895930..b412eeb281 100644--- a/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts+++ b/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts@@ -39,7 +39,6 @@ it('offers retry discard when a crash interrupted deletion before admission', asdrafts: context.drafts,draftId: () => 'draft',localSaveState: () => 'saved',- acknowledgeSaved: () => true,retry: vi.fn(),discard,});@@ -65,7 +64,6 @@ it('shows a failed status read without throwing into the composer error boundarydrafts: context.drafts,draftId: () => 'draft',localSaveState: () => 'saved',- acknowledgeSaved: () => true,retry: vi.fn(),discard: vi.fn(),});@@ -76,11 +74,13 @@ it('shows a failed status read without throwing into the composer error boundaryexpect(status.state()?.failed).toBe(true);});-it('acknowledges saved edits only after input pauses and stays stable through background sync', async () => {+it('stays silent once a failed save recovers', async () => {const context = createComposeContext();- const [local, setLocal] = createSignal<LocalDraft | undefined>();- const [disk, setDisk] = createSignal<'saving' | 'saved' | 'failed'>('saving');- const [inputIdle, setInputIdle] = createSignal(false);+ const [local, setLocal] = createSignal<LocalDraft>({+ ...draft,+ status: 'failed',+ });+ const [disk, setDisk] = createSignal<'saving' | 'saved' | 'failed'>('saved');let changed = () => {};context.drafts.saveLocalDraft = vi.fn();context.drafts.readDraft = vi.fn(async () => ({@@ -98,44 +98,16 @@ it('acknowledges saved edits only after input pauses and stays stable through badrafts: context.drafts,draftId: () => 'draft',localSaveState: disk,- acknowledgeSaved: inputIdle,retry,discard: vi.fn(),});});- await vi.waitFor(() => expect(context.drafts.readDraft).toHaveBeenCalled());- expect(status.state()).toBeUndefined();- for (const phase of [- 'dirty',- 'queued',- 'synced',- 'dirty',- 'queued',- 'synced',- ] as const) {- setLocal({ ...draft, status: phase });- changed();- setDisk('saved');- await vi.waitFor(() => expect(status.state()?.message).toBe('Draft saved'));- expect(status.state()?.savedVersion).toBeUndefined();- setInputIdle(true);- const version = status.state()?.savedVersion;- expect(version).toBe('generation:1');- changed();- await vi.waitFor(() => expect(status.state()?.savedVersion).toBe(version));- setDisk('saving');- expect(status.state()?.savedVersion).toBeUndefined();- setDisk('saved');- expect(status.state()?.savedVersion).toBe(version);- setInputIdle(false);- expect(status.state()?.savedVersion).toBeUndefined();- setDisk('saving');- expect(status.state()).toMatchObject({- message: 'Draft saved',- failed: false,- });- expect(status.state()?.action).toBeUndefined();- }+ await vi.waitFor(() =>+ expect(status.state()).toMatchObject({ failed: true, action: 'retry' })+ );+ setLocal({ ...draft, status: 'synced' });+ changed();+ await vi.waitFor(() => expect(status.state()).toBeUndefined());setDisk('failed');expect(status.state()).toMatchObject({ failed: true, action: 'retry' });status.retry();@@ -155,7 +127,6 @@ it('offers retry for server failures while newer edits remain saved locally', asdrafts: context.drafts,draftId: () => 'draft',localSaveState: () => 'saving',- acknowledgeSaved: () => false,retry: vi.fn(),discard: vi.fn(),});@@ -182,7 +153,6 @@ it('keeps local edits visible with an actionable synchronization status during rdrafts: context.drafts,draftId: () => 'draft',localSaveState: () => 'saved',- acknowledgeSaved: () => true,retry: vi.fn(),discard: vi.fn(),});@@ -196,5 +166,5 @@ it('keeps local edits visible with an actionable synchronization status during rsetAvailability('recovering');expect(status.state()?.action).toBeUndefined();setAvailability('ready');- expect(status.state()?.message).toBe('Draft saved');+ expect(status.state()).toBeUndefined();});diff --git a/apps/web/src/features/email-compose/primitives/draft-sync-status.ts b/apps/web/src/features/email-compose/primitives/draft-sync-status.tsindex 068202aa8c..1012f8f1a1 100644--- a/apps/web/src/features/email-compose/primitives/draft-sync-status.ts+++ b/apps/web/src/features/email-compose/primitives/draft-sync-status.ts@@ -15,7 +15,6 @@ export function createDraftSyncStatus(options: {drafts: EmailDraftStorage;draftId: Accessor<string | undefined>;localSaveState: Accessor<'saving' | 'saved' | 'failed'>;- acknowledgeSaved: Accessor<boolean>;retry(): Promise<unknown>;discard(): Promise<unknown>;}) {@@ -40,7 +39,7 @@ export function createDraftSyncStatus(options: {(local()?.status === 'deleting' &&(!local()?.queuedAttemptId ||local()?.queuedAttemptId !== local()?.latestAttemptId));- const state = createMemo<DraftSyncViewState | undefined>((previous) => {+ const state = createMemo<DraftSyncViewState | undefined>(() => {if (!options.drafts.saveLocalDraft || !options.draftId()) return;const disk = options.localSaveState();const draft = local();@@ -75,24 +74,8 @@ export function createDraftSyncStatus(options: {canKeepEditing: false,};}- // Only a newly persisted version restarts the brief acknowledgement.- // Queue notifications and identity adoption do not count as another save.- if (!failed) {- if (!draft && (disk === 'saving' || saved.loading))- return previous && { ...previous, savedVersion: undefined };- if (!draft && !saved.latest?.draft) return;- return {- message: 'Draft saved',- savedVersion:- disk === 'saved' && options.acknowledgeSaved()- ? draft- ? `${draft.generation}:${draft.revision}`- : saved.latest?.draft?.updated_at- : undefined,- failed: false,- canKeepEditing: false,- };- }+ // Saving is silent; only failures that need the user surface here.+ if (!failed) return;return {message:disk === 'failed'diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.tsindex 4c9b26a11d..233faa508d 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts@@ -568,16 +568,13 @@ export function createEmailComposer(props: EmailComposerOptions) {);try {return persistence.confirmed(- await autosave.save(- {- draft: collectDraft(true),- inboxId: activeInboxId(),- generation: identityVersion,- revision: editVersion,- attachments: [...form.attachments.list()],- },- { acknowledge: false }- )+ await autosave.save({+ draft: collectDraft(true),+ inboxId: activeInboxId(),+ generation: identityVersion,+ revision: editVersion,+ attachments: [...form.attachments.list()],+ }));} finally {cleanupWatermark();@@ -795,14 +792,12 @@ export function createEmailComposer(props: EmailComposerOptions) {) => {const draftId = identity.draftId;const threadId = identity.threadId;+ // The outbox delivers an online send right away; offline it waits on this device.+ const offline = props.connectivity.looksOffline();if (draftId) endUndoSend(draftId);try {const toastId = props.notices.feedback.success(- identity.sendAttemptId- ? identity.persistence === 'queued'- ? 'Email queued to send'- : 'Email sending'- : 'Email sent',+ offline ? 'Email queued to send' : 'Email sent',{actions: draftId? [@@ -828,7 +823,9 @@ export function createEmailComposer(props: EmailComposerOptions) {props.notices.reportError(error);}try {- if (threadId) props.host?.showThread?.(threadId);+ // The server has no thread to show until an offline send goes out.+ if (offline) props.host?.goBack?.();+ else if (threadId) props.host?.showThread?.(threadId);} catch (error) {props.notices.reportError(error);}@@ -901,31 +898,15 @@ export function createEmailComposer(props: EmailComposerOptions) {return refuseSend(props.notices, 'media-not-uploaded');if (attachmentLinks.uploading())return refuseSend(props.notices, 'files-uploading');+ // Send Later schedules the saved draft; only immediate sends use the outbox.const scheduleAction = schedule.action();- const queuedLater =- scheduleAction === 'schedule' &&- !!props.delivery.queueActive?.(activeInboxId());- const selectedTime = queuedLater ? schedule.selectedTime() : undefined;- if (- queuedLater &&- (!selectedTime ||- !Number.isFinite(selectedTime.getTime()) ||- selectedTime.getTime() <= Date.now())- ) {- props.notices.feedback.alert('Choose a future send time.');- return;- }- const sendTime = selectedTime?.toISOString();if (scheduleAction === 'unavailable') {props.notices.feedback.alert(`This email is scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`);return;}- if (- (scheduleAction === 'schedule' && !queuedLater) ||- scheduleAction === 'update'- ) {+ if (scheduleAction === 'schedule' || scheduleAction === 'update') {const result = await schedule.submit();if (result === 'scheduled') {const scheduledDraftId = currentDraftId();@@ -964,7 +945,7 @@ export function createEmailComposer(props: EmailComposerOptions) {await autosave.saveLocal();} else {try {- await autosave.save(undefined, { acknowledge: false });+ await autosave.save();} catch {// Legacy standalone sends can proceed without a saved draft.}@@ -990,8 +971,7 @@ export function createEmailComposer(props: EmailComposerOptions) {completed() ||terminalState() ||schedule.pending() ||- (schedule.action() !== 'send' &&- !(queuedLater && schedule.selectedTime()?.toISOString() === sendTime))+ schedule.action() !== 'send')return;@@ -1022,7 +1002,6 @@ export function createEmailComposer(props: EmailComposerOptions) {try {setSendPhase('sending');const result = await props.delivery.sendMessage({- sendTime,expectedLocalVersion,clientHandles: {draftId: currentDraftId()!,@@ -1562,7 +1541,6 @@ export function createEmailComposer(props: EmailComposerOptions) {retryDraft,flushLocal: autosave.flushLocal,localSaveState: autosave.localSaveState,- acknowledgeSaved: autosave.acknowledgeSaved,context: ctxValue,editor,form,diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.tsindex 87fad8402d..16ac2e08ec 100644--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts@@ -141,7 +141,11 @@ export type ReplyComposerOptions = {* undo-send restore. The parent latches the seed key on it so the input* stops remounting on later draft versions. */onEngaged?: () => void;- sideEffectOnSend?: (newMessageId: string | null) => void | Promise<void>;+ sideEffectOnSend?: (+ newMessageId: string | null,+ /** Offline sends wait on this device, so the thread cannot show them yet. */+ sent?: { queuedOffline: boolean }+ ) => void | Promise<void>;onMarkDone?: (opts?: {silent?: boolean;onUndoHandle?: (handle: EmailUndoHandle) => void;@@ -912,7 +916,7 @@ export function createReplyComposer();try {return persistence.confirmed(- await autosave.save(captureSave(false, true), { acknowledge: false })+ await autosave.save(captureSave(false, true)));} finally {cleanupWatermark();@@ -1113,31 +1117,15 @@ export function createReplyComposer(},});};+ // Send Later schedules the saved draft; only immediate sends use the outbox.const scheduleAction = schedule.action();- const queuedLater =- scheduleAction === 'schedule' &&- !!props.delivery.queueActive?.(sendingInbox()?.id);- const selectedTime = queuedLater ? schedule.selectedTime() : undefined;- if (- queuedLater &&- (!selectedTime ||- !Number.isFinite(selectedTime.getTime()) ||- selectedTime.getTime() <= Date.now())- ) {- props.notices.feedback.alert('Choose a future send time.');- return;- }- const sendTime = selectedTime?.toISOString();if (scheduleAction === 'unavailable') {props.notices.feedback.alert(`This email is scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`);return;}- if (- (scheduleAction === 'schedule' && !queuedLater) ||- scheduleAction === 'update'- ) {+ if (scheduleAction === 'schedule' || scheduleAction === 'update') {const result = await schedule.submit();if (result === 'scheduled') {const scheduledDraftId = savedDraftId();@@ -1183,10 +1171,7 @@ export function createReplyComposer((form.attachments.list().length === 0 || session.serverConfirmed()))await autosave.saveLocal(captureSave(willMarkDone));- else- await autosave.save(captureSave(willMarkDone), {- acknowledge: false,- });+ else await autosave.save(captureSave(willMarkDone));} catch (error) {props.notices.reportError(error);if (session.isStale(epochBeforeSave)) return;@@ -1220,11 +1205,7 @@ export function createReplyComposer(// Remember by draft so sends in separate composers cannot replace each other.rememberCurrentReply();- if (- scheduling() ||- (schedule.action() !== 'send' &&- !(queuedLater && schedule.selectedTime()?.toISOString() === sendTime))- ) {+ if (scheduling() || schedule.action() !== 'send') {return;}@@ -1259,7 +1240,6 @@ export function createReplyComposer(setSendPhase('sending');const pendingSend = props.delivery.sendMessage({- sendTime,expectedLocalVersion,clientHandles: {draftId: currentDraftId!,@@ -1365,13 +1345,11 @@ export function createReplyComposer(});},});+ // The outbox delivers an online send right away; offline it waits on this device.+ const offline = props.connectivity.looksOffline();try {const toastId = props.notices.feedback.success(- result.sendAttemptId- ? result.persistence === 'queued'- ? 'Email queued to send'- : 'Email sending'- : 'Email sent',+ offline ? 'Email queued to send' : 'Email sent',{actions: draftId? [@@ -1420,9 +1398,12 @@ export function createReplyComposer(}try {// Presentation refresh must not keep a successfully sent or undone reply disabled.- void Promise.resolve(props.sideEffectOnSend?.(draftId ?? null)).catch(- props.notices.reportError- );+ void Promise.resolve(+ props.sideEffectOnSend?.(draftId ?? null, {+ // Send and mark done already leaves the thread.+ queuedOffline: offline && !markDone,+ })+ ).catch(props.notices.reportError);} catch (error) {props.notices.reportError(error);}@@ -1765,7 +1746,6 @@ export function createReplyComposer(retryDraft,flushLocal: autosave.flushLocal,localSaveState: autosave.localSaveState,- acknowledgeSaved: autosave.acknowledgeSaved,onContentChange: handleChange,handleUserMention,scrollContainer,diff --git a/apps/web/src/features/email-compose/queued-send-status.test.tsx b/apps/web/src/features/email-compose/queued-send-status.test.tsxindex 1e9a3e7f2b..3c9dff37e6 100644--- a/apps/web/src/features/email-compose/queued-send-status.test.tsx+++ b/apps/web/src/features/email-compose/queued-send-status.test.tsx@@ -42,7 +42,11 @@ beforeEach(() => {function showStatus(status: 'ACCEPTED' | 'FAILED' | 'DELIVERY_UNCONFIRMED',- cancellationPending = false+ {+ cancellationPending = false,+ sendTime = null as string | null,+ failures = 0,+ } = {}) {mocks.intents = [{@@ -51,6 +55,7 @@ function showStatus(locallyCancelled: false,dispatchVersion: 2,cancellationRequested: cancellationPending,+ dispatch: { generation: 1, leaseUntil: 0, nextAttemptAt: 0, failures },metadata: {kind: 'email-send-v1',payload: {@@ -67,6 +72,7 @@ function showStatus(message: {draftId: 'draft',subject: 'Saved message',+ sendTime,},attachmentIds: [],forwardedAttachmentIds: [],@@ -89,16 +95,26 @@ function showStatus(return render(() => <QueuedSendStatus />);}-it('keeps an accepted preparation cancellable while waiting to submit', async () => {+it('stays silent while an immediate send is accepted and delivering', () => {showStatus('ACCEPTED');- expect(screen.getByRole('status').textContent).toBe('Accepted by server');+ expect(screen.queryByLabelText('Queued email sends')).toBeNull();+});++it('keeps an accepted scheduled send cancellable until its send time', async () => {+ showStatus('ACCEPTED', { sendTime: '2026-10-23T09:00:00.000Z' });+ expect(screen.getByRole('status').textContent).toContain('Scheduled');fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));await waitFor(() => expect(mocks.cancel).toHaveBeenCalledOnce());expect(mocks.restore).not.toHaveBeenCalled();});-it('keeps a pending cancellation visible after an accepted preparation', () => {- showStatus('ACCEPTED', true);+it('stays silent while an Undo is confirming with the server', () => {+ showStatus('ACCEPTED', { cancellationPending: true });+ expect(screen.queryByLabelText('Queued email sends')).toBeNull();+});++it('shows a cancellation that cannot reach the server', () => {+ showStatus('ACCEPTED', { cancellationPending: true, failures: 1 });expect(screen.getByRole('status').textContent).toBe('Cancellation pending');expect(screen.getByRole('button', { name: 'Cancel' }).hasAttribute('disabled')diff --git a/apps/web/src/features/email-compose/queued-send-status.tsx b/apps/web/src/features/email-compose/queued-send-status.tsxindex 00d271310c..28b04bf5d9 100644--- a/apps/web/src/features/email-compose/queued-send-status.tsx+++ b/apps/web/src/features/email-compose/queued-send-status.tsx@@ -1,3 +1,4 @@+import { deviceLooksOffline } from '@core/util/connectivity';import { fireAndForget } from '@core/util/fireAndForget';import { cancelServerEmailSend } from '@queries/email/cancel-server-send';import { useQueuedEmailSends } from '@queries/email/queued-sends';@@ -21,6 +22,33 @@ import {import { Button } from '@ui';import { createSignal, For, Show } from 'solid-js';+/**+ * Routine delivery is silent. A send shows here only while it waits on this+ * device, needs the user, or is scheduled for later.+ */+function sendNeedsNotice(intent: EmailSendIntent, offline: boolean) {+ const status = settledSendAttempt(intent)?.status;+ if (status === 'SENT') return false;+ if (+ intent.metadata.payload.input.message.sendTime ||+ !emailSendLocked(intent) ||+ intent.dispatch?.paused ||+ intent.phase === 'failed' ||+ status === 'FAILED' ||+ status === 'DELIVERY_UNCONFIRMED'+ )+ return true;+ // Delivery and Undo in progress stay silent unless they are stuck.+ if (+ !intent.cancellationRequested &&+ (status === 'ACCEPTED' ||+ status === 'SENDING' ||+ intent.phase === 'committed')+ )+ return false;+ return offline || (intent.dispatch?.failures ?? 0) > 0;+}+/** App-facing persistent send status, shared by Drafts and conversation hosts. */export function QueuedSendStatus(props: {threadId?: string;@@ -32,7 +60,7 @@ export function QueuedSendStatus(props: {const { draft, input } = intent.metadata.payload;const attempt = settledSendAttempt(intent);return (- attempt?.status !== 'SENT' &&+ sendNeedsNotice(intent, deviceLooksOffline()) &&(!props.threadId ||intent.resolvedThreadId === props.threadId ||draft.threadDbId === props.threadId ||@@ -51,8 +79,9 @@ export function QueuedSendStatus(props: {local.uuid === row.attempt.attemptId &&local.metadata.payload.input.attempt.linkId === row.linkId) &&- row.attempt.status !== 'SENT' &&- row.attempt.status !== 'CANCELLED' &&+ (row.attempt.status === 'FAILED' ||+ row.attempt.status === 'DELIVERY_UNCONFIRMED' ||+ (row.attempt.status === 'ACCEPTED' && !!row.attempt.sendTime)) &&(!props.threadId || row.attempt.threadId === props.threadId) &&(!props.inboxIds?.length || props.inboxIds.includes(row.linkId)));@@ -65,8 +94,10 @@ export function QueuedSendStatus(props: {emailSendStorageWarning()}>+ {/* Full-frame phone views leave the top inset to their content. This+ panel sits above that content, so it takes the inset in its place. */}<div- class="shrink-0 border-b border-edge-muted p-3"+ class="shrink-0 border-b border-edge-muted p-3 touch:pt-[calc(var(--mobile-content-inset-top,0px)+0.75rem)] touch:[&~*]:[--mobile-content-inset-top:0px]"aria-label="Queued email sends"><For each={visible()}>@@ -130,7 +161,7 @@ function ServerSendStatus(props: { row: ServerEmailSend }) {</div><div class="text-xs text-ink-muted" role="status">{status() === 'ACCEPTED'- ? 'Accepted by server'+ ? 'Scheduled': status() === 'FAILED'? 'Send failed before delivery. Cancel to recover this draft.': status() === 'DELIVERY_UNCONFIRMED'@@ -175,7 +206,7 @@ function SendStatus(props: {return 'Send needs attention. Cancel to recover this draft.';if (emailSendLocked(props.intent) && props.intent.cancellationRequested)return 'Cancellation pending';- if (status() === 'ACCEPTED') return 'Accepted by server';+ if (status() === 'ACCEPTED') return 'Scheduled';if (status() === 'SENDING' || props.intent.phase === 'committed')return 'Sending';return props.intent.submissionStarteddiff --git a/apps/web/src/features/email-compose/undo-send.test.ts b/apps/web/src/features/email-compose/undo-send.test.tsindex edc40cf713..0e0a666937 100644--- a/apps/web/src/features/email-compose/undo-send.test.ts+++ b/apps/web/src/features/email-compose/undo-send.test.ts@@ -1,4 +1,5 @@import {+ EmailSendCancellationPending,EmailSendCancellationTooLate,EmailSendDeliveryUnconfirmed,type EmailSendIntent,@@ -10,8 +11,8 @@ import { runQueuedUndoSend } from './undo-send';const mocks = vi.hoisted(() => ({read: vi.fn(),- cancel: vi.fn(),- restore: vi.fn(),+ confirm: vi.fn(),+ promise: vi.fn(async (pending: Promise<unknown>) => await pending),success: vi.fn(),failure: vi.fn(),alert: vi.fn(),@@ -26,9 +27,8 @@ vi.mock('@queries/soup/cache', () => ({}));vi.mock('./primitives/prepare-email-body', () => ({}));vi.mock('@queries/email/send-queue', () => ({readEmailSendIntents: mocks.read,- cancelEmailSendQueued: mocks.cancel,- restoreCancelledEmailSend: mocks.restore,- emailSendLocked: (intent: EmailSendIntent) => !intent.locallyCancelled,+ cancelEmailSendAndConfirm: mocks.confirm,+ EmailSendCancellationPending: class extends Error {},EmailSendCancellationTooLate: class extends Error {},EmailSendDeliveryUnconfirmed: class extends Error {constructor() {@@ -72,15 +72,13 @@ const intent: EmailSendIntent = {},};-const cancelled = { ...intent, locallyCancelled: true };const onUndone = vi.fn();const options = { draftId: 'draft', attemptId: intent.uuid, onUndone };beforeEach(() => {vi.clearAllMocks();endUndoSend(options.draftId);mocks.read.mockResolvedValue([intent]);- mocks.cancel.mockResolvedValue(cancelled);- mocks.restore.mockResolvedValue(undefined);+ mocks.confirm.mockResolvedValue(undefined);});it('restores the persisted cancellation and reopens the draft after navigation disposes the composer', async () => {@@ -90,24 +88,24 @@ it('restores the persisted cancellation and reopens the draft after navigation dreturn undo;});await undo();- expect(mocks.restore).toHaveBeenCalledWith(cancelled);+ expect(mocks.confirm).toHaveBeenCalledWith(intent);expect(onUndone).toHaveBeenCalledOnce();expect(mocks.success).toHaveBeenCalledWith('Send cancelled');await undo();- expect(mocks.cancel).toHaveBeenCalledOnce();+ expect(mocks.confirm).toHaveBeenCalledOnce();});-it('keeps uncertain cancellation locked, gives feedback, and allows a confirmed retry', async () => {- mocks.cancel.mockResolvedValueOnce(intent);+it('keeps unconfirmed cancellation locked, gives feedback, and allows a confirmed retry', async () => {+ mocks.confirm.mockRejectedValueOnce(new EmailSendCancellationPending());await runQueuedUndoSend(options);- expect(mocks.restore).not.toHaveBeenCalled();expect(onUndone).not.toHaveBeenCalled();+ expect(mocks.failure).not.toHaveBeenCalled();expect(mocks.alert).toHaveBeenCalledWith('Cancellation pending — waiting for confirmation');await runQueuedUndoSend(options);- expect(mocks.restore).toHaveBeenCalledWith(cancelled);expect(onUndone).toHaveBeenCalledOnce();+ expect(mocks.success).toHaveBeenCalledWith('Send cancelled');});it.each([@@ -116,6 +114,7 @@ it.each(['Too late to undo — delivery has already started',],[new Error('storage unavailable'), 'Failed to undo send'],+ [new Error('restore failed'), 'Failed to undo send'],[new EmailSendDeliveryUnconfirmed(),'Delivery unconfirmed; check your sent mail. We will not resend automatically.',@@ -123,23 +122,13 @@ it.each([])('shows cancellation failures and allows retry: %s',async (error, message) => {- mocks.cancel.mockRejectedValueOnce(error);+ mocks.confirm.mockRejectedValueOnce(error);await runQueuedUndoSend(options);expect(mocks.failure).toHaveBeenCalledWith(message);expect(mocks.error).toHaveBeenCalledWith(error);- expect(mocks.restore).not.toHaveBeenCalled();+ expect(mocks.success).not.toHaveBeenCalled();expect(onUndone).not.toHaveBeenCalled();await runQueuedUndoSend(options);expect(onUndone).toHaveBeenCalledOnce();});--it('reports failed restoration without claiming success or losing the recovery intent', async () => {- mocks.restore.mockRejectedValueOnce(new Error('restore failed'));- await runQueuedUndoSend(options);- expect(mocks.failure).toHaveBeenCalledWith('Failed to undo send');- expect(mocks.success).not.toHaveBeenCalled();- expect(onUndone).not.toHaveBeenCalled();- await runQueuedUndoSend(options);- expect(onUndone).toHaveBeenCalledOnce();-});diff --git a/apps/web/src/features/email-compose/undo-send.ts b/apps/web/src/features/email-compose/undo-send.tsindex 1118cdaa94..1df5db32af 100644--- a/apps/web/src/features/email-compose/undo-send.ts+++ b/apps/web/src/features/email-compose/undo-send.ts@@ -5,12 +5,11 @@ import { saveEmailComposeDraft } from '@queries/email/graphql/compose';import { unscheduleEmailMessage } from '@queries/email/integration';import { emailKeys } from '@queries/email/keys';import {- cancelEmailSendQueued,+ cancelEmailSendAndConfirm,+ EmailSendCancellationPending,EmailSendCancellationTooLate,EmailSendDeliveryUnconfirmed,- emailSendLocked,readEmailSendIntents,- restoreCancelledEmailSend,} from '@queries/email/send-queue';import { invalidateSoupEntity } from '@queries/soup/cache';import type { EmailDraft } from './core/email-draft';@@ -62,17 +61,19 @@ export async function runQueuedUndoSend(options: {(row) => row.uuid === attemptId);if (!intent) throw new Error('This send is no longer available to undo');- const updated = await cancelEmailSendQueued(intent);- if (emailSendLocked(updated)) {- endUndoSend(draftId);- toast.alert('Cancellation pending — waiting for confirmation');- return;- }- await restoreCancelledEmailSend(updated);+ // A submitted send waits for the server to confirm the cancellation,+ // which online takes a moment; only then is the draft restored.+ await toast.promise(cancelEmailSendAndConfirm(intent), {+ loading: 'Cancelling send…',+ });await options.onUndone();toast.success('Send cancelled');} catch (error) {endUndoSend(draftId);+ if (error instanceof EmailSendCancellationPending) {+ toast.alert('Cancellation pending — waiting for confirmation');+ return;+ }Telemetry.error(error instanceof Error ? error : new Error('Failed to undo send'));diff --git a/apps/web/src/features/email-compose/views/compose-toolbar.tsx b/apps/web/src/features/email-compose/views/compose-toolbar.tsxindex d47b4e9589..9b926ab71b 100644--- a/apps/web/src/features/email-compose/views/compose-toolbar.tsx+++ b/apps/web/src/features/email-compose/views/compose-toolbar.tsx@@ -15,7 +15,7 @@ import TextAa from '@phosphor/text-aa.svg';import Trash from '@phosphor/trash.svg';import { Button, SendButton } from '@ui';import { FORMAT_TEXT_COMMAND, type LexicalEditor } from 'lexical';-import { createSignal, type JSX, Show } from 'solid-js';+import { createSignal, Show } from 'solid-js';import { EmailDateSelector } from '../components/email-date-selector';import { EmailScheduleSummary } from '../components/email-schedule-summary';import { MobileComposeActions } from '../components/mobile-compose-actions';@@ -23,7 +23,6 @@ import { useCompose } from '../context/compose-context';export function EmailComposeToolbar(props: {editor?: () => LexicalEditor | undefined;- status?: JSX.Element;/** Embedded drafts keep their controls in the card on phones too. */inline?: boolean;}) {@@ -31,10 +30,7 @@ export function EmailComposeToolbar(props: {const [showFormatRibbon, setShowFormatRibbon] = createSignal(false);return (- <Show- when={props.inline || !ctx.isMobile()}- fallback={<MobileToolbar status={props.status} />}- >+ <Show when={props.inline || !ctx.isMobile()} fallback={<MobileToolbar />}><Show when={showFormatRibbon() && !ctx.disabled()}><div class="flex flex-row w-full gap-2 items-center p-2 -ml-3"><FormatButtons@@ -50,7 +46,6 @@ export function EmailComposeToolbar(props: {</Show><div class="mt-2 flex min-w-0 justify-end"><div class="flex shrink-0 items-center gap-1">- {props.status}<Show when={ctx.hasDraft()}><ButtononClick={ctx.onDelete}@@ -115,7 +110,7 @@ export function EmailComposeToolbar(props: {);}-function MobileToolbar(props: { status?: JSX.Element }) {+function MobileToolbar() {const ctx = useCompose();const hasScheduleSummary = () => {const state = ctx.schedule.state();@@ -139,7 +134,6 @@ function MobileToolbar(props: { status?: JSX.Element }) {</SplitHeaderLeft><SplitHeaderRight><MobileComposeActions- status={props.status}attachRef={ctx.hideAttachments? undefineddiff --git a/apps/web/src/features/email-compose/views/email-compose.tsx b/apps/web/src/features/email-compose/views/email-compose.tsxindex d7a651c4a3..9826549c7a 100644--- a/apps/web/src/features/email-compose/views/email-compose.tsx+++ b/apps/web/src/features/email-compose/views/email-compose.tsx@@ -144,7 +144,6 @@ function LoadedEmailComposeView(drafts: composeContext.drafts,draftId: state.draftId,localSaveState: state.localSaveState,- acknowledgeSaved: state.acknowledgeSaved,retry: state.retryDraft,discard: state.deleteDraftAndReset,});@@ -271,10 +270,8 @@ function LoadedEmailComposeView(</Show>{/* No overflow clipping on desktop: the card clips its own content, andclipping here would slice the composer shadow flat at the top and- bottom while the side padding lets it show. Full-frame mobile/tablet- carries the bottom inset here so the body, signature and attachment- pills rest above the floating chrome (ComposeLayout owns the top). */}- <div class="macro-message-width sm:macro-message-padding mx-auto w-full min-h-120 max-h-full my-2 sm:my-12 touch:my-0 px-2 sm:px-4 touch:px-0 touch:pb-(--mobile-content-inset-bottom) touch:overflow-y-auto touch:scrollbar-hidden touch:min-h-full">+ bottom while the side padding lets it show. */}+ <div class="macro-message-width sm:macro-message-padding mx-auto w-full min-h-120 max-h-full my-2 sm:my-12 touch:my-0 px-2 sm:px-4 touch:px-0 touch:overflow-y-auto touch:scrollbar-hidden touch:min-h-full"><WrapUnlessMobilewrapper={(children) => (// The same card as the chat composer and the thread's message@@ -300,11 +297,18 @@ function LoadedEmailComposeView()}><ComposeLayout- toolbar={- <EmailComposeToolbar editor={editor} status={<SyncStatus />} />+ toolbar={<EmailComposeToolbar editor={editor} />}+ notice={+ hasInboxError() ? (+ <EmailPermissionsBanner />+ ) : sync.state() ? (+ <SyncStatus />+ ) : undefined}- notice={hasInboxError() ? <EmailPermissionsBanner /> : undefined}- class="size-full p-4 touch:bg-surface max-h-full touch:max-h-none overflow-hidden flex flex-col min-h-0 touch:min-h-full"+ // Full-frame mobile/tablet: the surface runs under the floating+ // chrome while the body, signature and attachment pills rest+ // above it (ComposeLayout owns the top inset).+ class="size-full p-4 touch:pb-[calc(var(--mobile-content-inset-bottom,0px)+1rem)] touch:bg-surface max-h-full touch:max-h-none overflow-hidden flex flex-col min-h-0 touch:min-h-full"/></WrapUnlessMobile></div>diff --git a/apps/web/src/features/email-compose/views/reply-input.tsx b/apps/web/src/features/email-compose/views/reply-input.tsxindex 259853ebe2..a6fd38844b 100644--- a/apps/web/src/features/email-compose/views/reply-input.tsx+++ b/apps/web/src/features/email-compose/views/reply-input.tsx@@ -171,7 +171,6 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {drafts: composeContext.drafts,draftId: state.savedDraftId,localSaveState: state.localSaveState,- acknowledgeSaved: state.acknowledgeSaved,retry: state.retryDraft,discard: state.deleteDraftAndReset,});@@ -535,7 +534,6 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {</Show><Show when={isMobileCompose()}><MobileReplyToolbar- status={<SyncStatus />}onBack={requestClose}attachRef={(element) =>fileSelector(element, () => ({@@ -573,6 +571,7 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {}/></Show>+ <SyncStatus /><ReplyEnvelopefields={state.recipients}values={form.recipients}@@ -790,7 +789,6 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {class="shrink-0 flex min-w-0 justify-end pt-1.5"><div class="flex shrink-0 items-center gap-1">- <SyncStatus /><ButtononClick={deleteDraftAndReset}tooltip={savedDraftId() ? 'Delete draft' : 'Discard'}diff --git a/apps/web/src/features/email-thread/email-thread.tsx b/apps/web/src/features/email-thread/email-thread.tsxindex 0f4893b840..0c7581eed2 100644--- a/apps/web/src/features/email-thread/email-thread.tsx+++ b/apps/web/src/features/email-thread/email-thread.tsx@@ -58,14 +58,10 @@ export function EmailThread(props: EmailThreadProps) {const contacts = useContacts();const viewerEmail = useEmail();const user = useUserContext();- const composeContext = createEmailComposeContext({+ const compose = createEmailComposeContext({threadTransport: props.threadTransport,});- const { source, delivery } = createOptimisticThreadSend(- props.source,- composeContext- );- const compose = { ...composeContext, delivery };+ const source = createOptimisticThreadSend(props.source, compose);const threadContext: EmailThreadContext = {source,viewerEmail,diff --git a/apps/web/src/features/email-thread/primitives/email-thread-state.ts b/apps/web/src/features/email-thread/primitives/email-thread-state.tsindex 2de277ca8c..847a416396 100644--- a/apps/web/src/features/email-thread/primitives/email-thread-state.ts+++ b/apps/web/src/features/email-thread/primitives/email-thread-state.ts@@ -89,6 +89,8 @@ export type EmailThreadState = {};archiveThread: (opts?: ArchiveThreadOptions) => boolean;+ /** Closes an embedded thread back to its list, when the host has one. */+ returnToList?: () => void;/** Marks the thread done and opens the next one in the host's list. */archiveThreadAndAdvance: (opts?: ArchiveThreadOptions) => boolean;/** True when the thread is archived, i.e. currently marked done. */@@ -280,6 +282,7 @@ export function createEmailThreadState(recipientOptions: recipients.options,onRecipientsChange: recipients.add,...commands,+ returnToList: host.returnToList,archiveThreadAndAdvance,messagesContainerRef,messagesListRef,diff --git a/apps/web/src/features/email-thread/primitives/optimistic-send.test.ts b/apps/web/src/features/email-thread/primitives/optimistic-send.test.tsindex fb4eea5fef..71bf63bf75 100644--- a/apps/web/src/features/email-thread/primitives/optimistic-send.test.ts+++ b/apps/web/src/features/email-thread/primitives/optimistic-send.test.ts@@ -1,31 +1,27 @@import { createRoot, createSignal } from 'solid-js';import { expect, it, vi } from 'vitest';-import type {- PersistedEmailIdentity,- SendEmailDraft,-} from '../../email-compose/context/compose-capabilities';+import type { OutgoingEmail } from '../../email-compose/context/compose-capabilities';import { createComposeContext } from '../../email-compose/tests/capabilities';import { createThreadContext, message, thread } from '../tests/fixtures';import { createOptimisticThreadSend } from './optimistic-send';-const input: SendEmailDraft = {+const outgoing: OutgoingEmail = {+ sendAttemptId: 'attempt',+ messageIds: ['draft'],+ threadIds: ['thread'],inboxId: 'inbox',+ delivered: false,message: {- db_id: 'draft',- thread_db_id: 'thread',subject: 'Final subject',body_text: 'café',- body_html: 'PHA+Y2Fmw6k8L3A+',+ body_html_sanitized: '<p>café</p>',to: [{ email: '[email protected]' }],+ cc: [],+ bcc: [],},};-const identity = {- draftId: 'draft',- threadId: 'thread',- inboxId: 'inbox',-} satisfies PersistedEmailIdentity;-function setup(queueActive = false) {+function setup() {return createRoot((dispose) => {const draft = message('draft', {is_draft: true,@@ -45,255 +41,143 @@ function setup(queueActive = false) {const [snapshot, setSnapshot] = createSignal(thread([message('received'), draft]));+ const [sends, setSends] = createSignal<OutgoingEmail[]>([]);+ const refresh = vi.fn(async () => {});const compose = createComposeContext();- compose.delivery.queueActive = () => queueActive;- const request = Promise.withResolvers<PersistedEmailIdentity>();- vi.mocked(compose.delivery.sendMessage).mockReturnValue(request.promise);- const optimistic = createOptimisticThreadSend(- createThreadContext({ thread: snapshot }).source,+ compose.delivery.outgoing = sends;+ const source = createOptimisticThreadSend(+ createThreadContext({ thread: snapshot, refresh }).source,compose);- return { ...optimistic, compose, request, snapshot, setSnapshot, dispose };+ return { source, snapshot, setSnapshot, setSends, refresh, dispose };});}-it('leaves durable queued sends in the draft projection until the authoritative source changes', async () => {- const state = setup(true);+it('shows an approved send in place of its draft until the thread read shows it', () => {+ const state = setup();try {- const send = state.delivery.sendMessage(input);- expect(state.compose.delivery.sendMessage).toHaveBeenCalledWith(input);- expect(state.source.thread()).toBe(state.snapshot());+ state.setSends([outgoing]);+ expect(+ state.source.thread()?.messages.map((message) => message.db_id)+ ).toEqual(['received', 'draft']);expect(state.source.thread()?.messages[1]).toMatchObject({- is_draft: true,- body_text: 'Older body',- labels: [{ provider_label_id: 'DRAFT' }],+ is_draft: false,+ subject: 'Final subject',+ body_text: 'café',+ body_html_sanitized: '<p>café</p>',+ body_replyless: null,+ from: { email: '[email protected]' },+ to: [{ email: '[email protected]' }],+ labels: [],+ attachments_draft: [{ id: 'file' }],+ sent_at: expect.any(String),});- const queued = {- ...identity,- sendAttemptId: 'send-attempt',- persistence: 'queued' as const,- };- state.request.resolve(queued);- await expect(send).resolves.toEqual(queued);- expect(state.source.thread()).toBe(state.snapshot());- state.setSnapshot(thread([message('received')]));- expect(state.source.thread()?.messages.map((value) => value.db_id)).toEqual(- ['received']+ // The projection never changes the underlying draft snapshot.+ expect(state.snapshot().messages[1].is_draft).toBe(true);+ state.setSnapshot(+ thread([+ message('received'),+ message('draft', { body_text: 'Server body' }),+ ]));+ expect(+ state.source.thread()?.messages.map((message) => message.body_text)+ ).toEqual([undefined, 'Server body']);+ // A later deletion must not resurrect the confirmed send.+ state.setSnapshot(thread([message('received')]));+ expect(state.source.thread()?.messages).toHaveLength(1);} finally {state.dispose();}});-it.each([true, false])(- 'propagates Undo restoration ownership (draftRestored=%s)',- async (draftRestored) => {- const state = setup(true);- try {- const result = { draftRestored };- vi.mocked(state.compose.delivery.undoSend).mockImplementation(- async ({ onUndone }) => {- await onUndone(result);- }- );- const onUndone = vi.fn();- await state.delivery.undoSend({- ...identity,- sendAttemptId: 'send-attempt',- onUndone,- });- expect(onUndone).toHaveBeenCalledExactlyOnceWith(result);- expect(state.compose.delivery.undoSend).toHaveBeenCalledWith(- expect.objectContaining({ sendAttemptId: 'send-attempt' })- );- expect(state.source.thread()).toBe(state.snapshot());- } finally {- state.dispose();- }- }-);--it.each(['reply', 'standalone'] as const)(- 'shows a %s before send settles and retains it until the thread refreshes',- async (kind) => {- const state = setup();- try {- const sendInput =- kind === 'standalone'- ? { ...input, message: { ...input.message, thread_db_id: undefined } }- : input;- const send = state.delivery.sendMessage(sendInput);- expect(state.compose.delivery.sendMessage).toHaveBeenCalledWith(- sendInput- );- expect(- state.source.thread()?.messages.map((message) => message.db_id)- ).toEqual(['received', 'draft']);- expect(state.source.thread()?.messages[1]).toMatchObject({- is_draft: false,- subject: 'Final subject',- body_text: 'café',- body_html_sanitized: '<p>café</p>',- body_replyless: null,- from: { email: '[email protected]' },- to: [{ email: '[email protected]' }],- labels: [],- attachments_draft: [{ id: 'file' }],- sent_at: expect.any(String),- });- // The optimistic projection never changes the underlying draft snapshot.- expect(state.snapshot().messages[1].is_draft).toBe(true);- state.request.resolve(identity);- await expect(send).resolves.toEqual(identity);- expect(state.source.thread()?.messages[1].is_draft).toBe(false);- state.setSnapshot(- thread([- message('received'),- message('draft', { body_text: 'Server body' }),- ])- );- expect(- state.source.thread()?.messages.map((message) => message.body_text)- ).toEqual([undefined, 'Server body']);- state.setSnapshot(thread([message('received')]));- expect(state.source.thread()?.messages).toHaveLength(1);- } finally {- state.dispose();- }+it('shows a send from a new thread that the read has no draft for', () => {+ const state = setup();+ try {+ state.setSnapshot(thread([]));+ state.setSends([outgoing]);+ expect(state.source.thread()?.messages).toMatchObject([+ { db_id: 'draft', thread_db_id: 'thread', is_draft: false },+ ]);+ } finally {+ state.dispose();}-);+});-it('removes a failed optimistic send while preserving a newer draft edit', async () => {+it('returns the draft and reads the thread again when the send is cancelled or fails', () => {const state = setup();try {- const send = state.delivery.sendMessage(input);- const rejected = expect(send).rejects.toThrow('Delivery failed');- state.setSnapshot(- thread([- message('received'),- message('draft', { is_draft: true, body_text: 'Newer edit' }),- ])- );- state.request.reject(new Error('Delivery failed'));- await rejected;+ state.setSends([outgoing]);+ expect(state.source.thread()?.messages[1].is_draft).toBe(false);+ state.setSends([]);expect(state.source.thread()?.messages[1]).toMatchObject({is_draft: true,- body_text: 'Newer edit',+ body_text: 'Older body',});+ // Admission already made the server's copy a sent message.+ expect(state.refresh).toHaveBeenCalledOnce();} finally {state.dispose();}});-it('adopts the server identity without duplicating the draft or the sent message', async () => {+it('keeps a delivered send after it leaves the outbox and reads the thread once', () => {const state = setup();try {- const send = state.delivery.sendMessage(input);- state.request.resolve({ ...identity, draftId: 'server-message' });- await send;- expect(- state.source.thread()?.messages.map((message) => message.db_id)- ).toEqual(['received', 'server-message']);- state.setSnapshot(- thread([- message('received'),- message('server-message', { body_text: 'Confirmed' }),- ])- );- expect(state.source.thread()?.messages).toHaveLength(2);- expect(state.source.thread()?.messages[1].body_text).toBe('Confirmed');+ state.setSends([outgoing]);+ expect(state.refresh).not.toHaveBeenCalled();+ state.setSends([{ ...outgoing, delivered: true }]);+ expect(state.refresh).toHaveBeenCalledOnce();+ state.setSends([]);+ expect(state.source.thread()?.messages[1].is_draft).toBe(false);+ expect(state.refresh).toHaveBeenCalledOnce();} finally {state.dispose();}});-it('rolls back only the failed send when multiple sends are in flight', async () => {+it('reads the thread again when a send the read already shows is undone', () => {const state = setup();try {- const second = Promise.withResolvers<PersistedEmailIdentity>();- vi.mocked(state.compose.delivery.sendMessage)- .mockReturnValueOnce(state.request.promise)- .mockReturnValueOnce(second.promise);- const firstSend = state.delivery.sendMessage(input);- const failed = expect(firstSend).rejects.toThrow();- const secondSend = state.delivery.sendMessage({- ...input,- message: { ...input.message, db_id: 'second', body_text: 'Second reply' },- });- state.request.reject(new Error('Failed'));- await failed;- expect(state.source.thread()?.messages.at(-1)).toMatchObject({- db_id: 'second',- is_draft: false,- body_text: 'Second reply',- });- expect(state.source.thread()?.messages[1].is_draft).toBe(true);- second.resolve({ ...identity, draftId: 'second' });- await secondSend;+ state.setSends([outgoing]);+ // The read caught up after admission, so nothing is projected.+ state.setSnapshot(+ thread([message('received'), message('draft', { body_text: 'Sent' })])+ );+ expect(state.source.thread()).toBe(state.snapshot());+ state.setSends([]);+ expect(state.refresh).toHaveBeenCalledOnce();} finally {state.dispose();}});-it('removes the optimistic message only after Undo Send succeeds', async () => {+it('adopts the server identity without duplicating the sent message', () => {const state = setup();try {- const send = state.delivery.sendMessage(input);- state.request.resolve(identity);- await send;- const onUndone = vi.fn();- const undo = { draftId: 'draft', inboxId: 'inbox', onUndone };- vi.mocked(state.compose.delivery.undoSend).mockRejectedValueOnce(- new Error('Undo failed')- );- await expect(state.delivery.undoSend(undo)).rejects.toThrow('Undo failed');- expect(state.source.thread()?.messages[1].is_draft).toBe(false);- vi.mocked(state.compose.delivery.undoSend).mockImplementation(- async ({ onUndone }) => {- await onUndone();- }+ state.setSends([{ ...outgoing, messageIds: ['draft', 'server-message'] }]);+ state.setSnapshot(+ thread([+ message('received'),+ message('server-message', { body_text: 'Confirmed' }),+ ]));- await state.delivery.undoSend(undo);- expect(state.source.thread()?.messages[1].is_draft).toBe(true);- expect(onUndone).toHaveBeenCalledOnce();+ expect(state.source.thread()?.messages).toHaveLength(2);+ expect(state.source.thread()?.messages[1].body_text).toBe('Confirmed');} finally {state.dispose();}});-it('keeps optimistic sends scoped to their thread when the source navigates', async () => {+it('keeps approved sends scoped to their thread when the source navigates', () => {const state = setup();try {- const send = state.delivery.sendMessage(input);+ state.setSends([outgoing]);state.setSnapshot(thread([message('other')], { db_id: 'other-thread' }));expect(state.source.thread()?.messages.map((message) => message.db_id)).toEqual(['other']);- state.request.resolve(identity);- await send;- expect(state.source.thread()?.messages).toHaveLength(1);} finally {state.dispose();}});--it.each([- ['gmail', true],- ['outlook', false],-] as const)(- 'uses the selected %s inbox to decide optimistic send ownership',- async (inboxId, queued) => {- const state = setup();- try {- const queueActive = vi.fn((selected?: string) => selected === 'gmail');- state.compose.delivery.queueActive = queueActive;- const send = state.delivery.sendMessage({ ...input, inboxId });- expect(queueActive).toHaveBeenCalledWith(inboxId);- expect(state.source.thread()?.messages[1].is_draft).toBe(queued);- state.request.resolve({ ...identity, inboxId });- await send;- } finally {- state.dispose();- }- }-);diff --git a/apps/web/src/features/email-thread/primitives/optimistic-send.ts b/apps/web/src/features/email-thread/primitives/optimistic-send.tsindex a4b341a157..8543a00499 100644--- a/apps/web/src/features/email-thread/primitives/optimistic-send.ts+++ b/apps/web/src/features/email-thread/primitives/optimistic-send.ts@@ -1,178 +1,144 @@-import { createMemo, createSignal } from 'solid-js';+import { fireAndForget } from '@core/util/fireAndForget';+import { createEffect, createMemo, on } from 'solid-js';import type {EmailComposeContext,- SendEmailDraft,+ OutgoingEmail,} from '../../email-compose/context/compose-capabilities';-import { decodeBase64Utf8 } from '../../email-compose/core/decode-base64';import type { EmailMessage } from '../../email-message/core/email-message';import type { EmailThreadSource } from '../context/email-thread-context';+import type { EmailThread } from '../core/email-thread';-type PendingMessage = {- token: symbol;- originalId: string;- message: EmailMessage;-};+type PendingSend = { send: OutgoingEmail; shownAt: string };-/** Keep REST sends visible in this surface until the thread read catches up. */+/** Show approved sends as sent in this surface until the thread read catches up. */export function createOptimisticThreadSend(source: EmailThreadSource,compose: Pick<EmailComposeContext, 'delivery' | 'accounts' | 'viewerEmail'>-) {- const [pending, setPending] = createSignal<PendingMessage[]>([]);- // Remember server acknowledgement so a later deletion or undo cannot- // resurrect a message from an older optimistic snapshot.- const confirmed = createMemo<Set<symbol>>((previous) => {- const messages = source.thread()?.messages ?? [];- return new Set(- pending()- .filter(- (entry) =>- previous?.has(entry.token) ||- messages.some(- (message) =>- !message.is_draft && message.db_id === entry.message.db_id- )- )- .map((entry) => entry.token)- );- });- const remove = (token: symbol) =>- setPending((entries) => entries.filter((entry) => entry.token !== token));+): EmailThreadSource {+ const outgoing = createMemo(() => compose.delivery.outgoing?.() ?? []);+ const tracked = createMemo(+ (previous: { pending: PendingSend[]; confirmed: Set<string> }) => {+ const messages = source.thread()?.messages ?? [];+ const live = outgoing();+ const confirmed = new Set(previous.confirmed);+ const pending: PendingSend[] = [];+ for (const send of [+ ...live,+ // A delivered send leaves the outbox before this read may show it.+ ...previous.pending+ .map((entry) => entry.send)+ .filter(+ (send) =>+ send.delivered &&+ !live.some((row) => row.sendAttemptId === send.sendAttemptId)+ ),+ ]) {+ if (confirmed.has(send.sendAttemptId)) continue;+ if (+ messages.some(+ (message) =>+ !message.is_draft && send.messageIds.includes(message.db_id)+ )+ ) {+ // Once the read shows it, a later deletion must not resurrect it.+ confirmed.add(send.sendAttemptId);+ continue;+ }+ pending.push({+ send,+ shownAt:+ previous.pending.find(+ (entry) => entry.send.sendAttemptId === send.sendAttemptId+ )?.shownAt ?? new Date().toISOString(),+ });+ }+ return { pending, confirmed };+ },+ { pending: [], confirmed: new Set<string>() }+ );- function prepare(input: SendEmailDraft): PendingMessage | undefined {- const current = source.thread();- const draft = input.message;- if (- !current ||- !draft.db_id ||- (draft.thread_db_id && draft.thread_db_id !== current.db_id)- )- return;- const existing = current.messages.find(- (message) => message.db_id === draft.db_id+ // The server's copy changes on delivery, and again when a cancelled or+ // failed send returns to a draft; read the thread at either moment.+ createEffect(+ on(outgoing, (current, previous: OutgoingEmail[] = []) => {+ const id = source.id();+ const find = (list: OutgoingEmail[], send: OutgoingEmail) =>+ list.find((row) => row.sendAttemptId === send.sendAttemptId);+ const delivered = current.some(+ (send) =>+ send.delivered &&+ send.threadIds.includes(id) &&+ !find(previous, send)?.delivered+ );+ const returned = previous.some(+ (send) =>+ !send.delivered && send.threadIds.includes(id) && !find(current, send)+ );+ if (delivered || returned)+ fireAndForget(source.refresh(), 'email-thread-send');+ })+ );++ function sentMessage(current: EmailThread, entry: PendingSend): EmailMessage {+ const { send, shownAt } = entry;+ const existing = current.messages.find((message) =>+ send.messageIds.includes(message.db_id));- // Standalone composers send only the draft ID; replies also carry a thread ID.- if (!existing && !draft.thread_db_id) return;const inbox = compose.accounts.inboxes()- .find((inbox) => inbox.id === (input.inboxId ?? current.link_id));- const now = new Date().toISOString();+ .find((inbox) => inbox.id === send.inboxId);return {- token: Symbol('send'),- originalId: draft.db_id,- message: {- ...existing,- db_id: draft.db_id,- thread_db_id: current.db_id,- link_id: inbox?.id ?? current.link_id,- from: inbox- ? {- email: inbox.email_address,- name: inbox.displayName,- photo_url: inbox.photo_url,- }- : (existing?.from ?? { email: compose.viewerEmail() ?? '' }),- to: draft.to ?? [],- cc: draft.cc ?? [],- bcc: draft.bcc ?? [],- subject: draft.subject,- body_text: draft.body_text,- body_macro: draft.body_macro,- body_html_sanitized: draft.body_html- ? decodeBase64Utf8(draft.body_html)- : null,- body_replyless: null,- replying_to_id: draft.replying_to_id,- is_draft: false,- is_read: existing?.is_read ?? true,- scheduled_send_time: null,- created_at: existing?.created_at ?? now,- updated_at: now,- internal_date_ts: now,- sent_at: now,- attachments: existing?.attachments ?? [],- attachments_draft: existing?.attachments_draft ?? [],- attachments_forwarded: existing?.attachments_forwarded ?? [],- labels:- existing?.labels.filter(- (label) => label.provider_label_id !== 'DRAFT'- ) ?? [],- },+ ...existing,+ ...send.message,+ db_id: existing?.db_id ?? send.messageIds[0],+ thread_db_id: current.db_id,+ link_id: inbox?.id ?? current.link_id,+ from: inbox+ ? {+ email: inbox.email_address,+ name: inbox.displayName,+ photo_url: inbox.photo_url,+ }+ : (existing?.from ?? { email: compose.viewerEmail() ?? '' }),+ body_replyless: null,+ is_draft: false,+ is_read: existing?.is_read ?? true,+ scheduled_send_time: null,+ scheduled_send_status: null,+ created_at: existing?.created_at ?? shownAt,+ updated_at: shownAt,+ internal_date_ts: shownAt,+ sent_at: shownAt,+ attachments: existing?.attachments ?? [],+ attachments_draft: existing?.attachments_draft ?? [],+ attachments_forwarded: existing?.attachments_forwarded ?? [],+ labels:+ existing?.labels.filter(+ (label) => label.provider_label_id !== 'DRAFT'+ ) ?? [],};}const thread = () => {const current = source.thread();if (!current) return;- const messages = pending().filter(- (entry) =>- !confirmed().has(entry.token) &&- entry.message.thread_db_id === current.db_id- );- if (!messages.length) return current;- const ids = new Set(- messages.flatMap((entry) => [entry.originalId, entry.message.db_id])+ const sends = tracked().pending.filter(+ ({ send }) =>+ send.threadIds.includes(current.db_id) ||+ current.messages.some((message) =>+ send.messageIds.includes(message.db_id)+ ));+ if (!sends.length) return current;+ const ids = new Set(sends.flatMap(({ send }) => send.messageIds));return {...current,messages: [...current.messages.filter((message) => !ids.has(message.db_id)),- ...messages.map((entry) => entry.message),+ ...sends.map((entry) => sentMessage(current, entry)),],};};- const delivery: EmailComposeContext['delivery'] = {- ...compose.delivery,- async sendMessage(input) {- if (compose.delivery.queueActive?.(input.inboxId))- return await compose.delivery.sendMessage(input);- const entry = prepare(input);- if (!entry) return await compose.delivery.sendMessage(input);- const acknowledged = confirmed();- setPending((entries) => [- ...entries.filter((entry) => !acknowledged.has(entry.token)),- entry,- ]);- try {- const result = await compose.delivery.sendMessage(input);- setPending((entries) =>- entries.map((pending) =>- pending.token === entry.token- ? {- ...pending,- message: {- ...pending.message,- db_id: result.draftId ?? pending.message.db_id,- thread_db_id:- result.threadId ?? pending.message.thread_db_id,- link_id: result.inboxId,- },- }- : pending- )- );- return result;- } catch (error) {- remove(entry.token);- throw error;- }- },- async undoSend(input) {- await compose.delivery.undoSend({- ...input,- onUndone: async (result) => {- setPending((entries) =>- entries.filter(- (entry) =>- entry.originalId !== input.draftId &&- entry.message.db_id !== input.draftId- )- );- await input.onUndone(result);- },- });- },- };- return { source: { ...source, thread }, delivery };+ return { ...source, thread };}diff --git a/apps/web/src/features/email-thread/views/thread-reply-input.tsx b/apps/web/src/features/email-thread/views/thread-reply-input.tsxindex 7863b7bf1f..5090d82abc 100644--- a/apps/web/src/features/email-thread/views/thread-reply-input.tsx+++ b/apps/web/src/features/email-thread/views/thread-reply-input.tsx@@ -82,10 +82,17 @@ function ThreadReplyInputSession(props: ThreadReplyInputProps) {return !!card;}- async function afterSend(newMessageId: string | null) {+ async function afterSend(+ newMessageId: string | null,+ sent?: { queuedOffline: boolean }+ ) {// Collapse the input after sending (Gmail-style).props.setShowReply?.(false);+ if (sent?.queuedOffline) {+ (ctx.returnToList ?? viewContext.composeHost?.goBack)?.();+ return;+ }if (!newMessageId) return;focusMessage(newMessageId);diff --git a/apps/web/src/lib/queries/email/send-queue.ts b/apps/web/src/lib/queries/email/send-queue.tsindex 8afcaeeba8..4b49988ffe 100644--- a/apps/web/src/lib/queries/email/send-queue.ts+++ b/apps/web/src/lib/queries/email/send-queue.ts@@ -149,6 +149,13 @@ export class EmailSendCancellationTooLate extends Error {}}+export class EmailSendCancellationPending extends Error {+ constructor() {+ super('Cancellation is pending. Check email send status before editing.');+ this.name = 'EmailSendCancellationPending';+ }+}+export class EmailSendDeliveryUnconfirmed extends Error {constructor() {super(@@ -192,10 +199,7 @@ export async function cancelEmailSendAndConfirm(throw new EmailSendCancellationTooLate();if (status === 'DELIVERY_UNCONFIRMED')throw new EmailSendDeliveryUnconfirmed();- if (Date.now() >= deadline)- throw new Error(- 'Cancellation is pending. Check email send status before editing.'- );+ if (Date.now() >= deadline) throw new EmailSendCancellationPending();await new Promise<void>((resolve) => setTimeout(resolve, 250));const latest = (await readEmailSendIntents()).find((row) => row.uuid === intent.uuiddiff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 8f3eb21b5c..a4dc76a5a2 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -485,16 +485,12 @@ inbox after inboxes load. Repeat on mobile using the expanded `Cc/Bcc, From:` roWith GraphQL draft queuing enabled, working copies and pending attachment bytesare saved on this device independently of the mutation queue. A failed serversave must leave the draft discoverable in **Drafts** (including grouped views)-and in its reply thread. **Draft saved** sits immediately left of the desktop-delete button after editing pauses for 500 ms and the latest local save completes,-then fades out after two seconds, including offline saves. Resuming typing hides-it immediately; another pause and saved version restart the timer. Background-sync updates do not. Failures replace it with persistent **Retry** in the same place; hover for details.-Clicking Send must not show the badge for its preparatory draft save, including-when delivery fails. Later edits can show it again after the usual pause.-Verify the label does not cycle through saving/syncing text on each edit and-that retry remains accessible beside the actions on mobile. Editing while failed-continues saving locally without repeatedly submitting the rejected request.+and in its reply thread. Saving is silent on desktop and mobile: no saved or+syncing text appears, including offline. A failure shows a banner inside the+composer, above the recipients, with **Retry** (or **Retry discard**); it never+appears in the toolbar or the mobile header actions. Verify the banner on mobile+sits below the header and that editing while failed continues saving locally+without repeatedly submitting the rejected request.Local draft storage reopens unexpectedly closed IndexedDB connections. If creatinga transaction fails because the connection is closing, it retries once beforerunning any writes. Verify by closing the draft database connection, then editing:@@ -598,19 +594,31 @@ final sent update, then switching offline and opening Sent. Existing providertimestamps and timestamps from repeated finalization remain unchanged; an unsentor cancelled draft must not acquire Sent membership.-**Send** and **Send Later** always persist new messages, replies, and forwards-for Gmail and Outlook in device email storage; no outbox feature flag is required.-This works with either thread read transport, including when normalized-cache+**Send** always persists new messages, replies, and forwards for Gmail and+Outlook in device email storage; no outbox feature flag is required. This works+with either thread read transport, including when normalized-cacheinitialization has failed. Recipients, inbox, sender alias, body, displayed-signature, attachment references, and any scheduled time are frozen under one-attempt ID. Completed uploads are required; adding files offline is unavailable.+signature, and attachment references are frozen under one attempt ID. Completed+uploads are required; adding files offline is unavailable.++**Send Later** schedules the saved draft through the schedule endpoint instead+of the outbox. It shows **Email scheduled** with the send time, **Undo**, and+**View message**; the message stays a draft, is listed under **Scheduled**, and+opens with **Scheduled for …** and **Cancel**. Cancelling leaves it an editable+draft. Sends scheduled through the outbox before this change still show in the+status panel with **Cancel**.An authenticated app-level dispatcher submits online immediately and retries thesame attempt independently of unrelated draft, archive, and property mutations.-**Queued on this device** means the app must run again to submit. **Accepted by-server** means delivery continues after the browser closes. Never equate local-queueing or server acceptance with provider delivery. Only one active send can-own a draft across tabs; queued composers remain read-only.+An online send shows **Email sent** with **Undo**: a new message opens its+conversation and a reply closes its composer, and the message appears as sent+there immediately, before the server or provider confirms it. An offline send+shows **Email queued to send** and returns to the email list. Routine delivery+is otherwise silent: the status panel shows a send only while it waits on this+device (**Queued on this device**), needs attention, or is scheduled+(**Scheduled**). On phones the panel sits below the safe area and the floating+header. Only one active send can own a draft across tabs; queued composers+remain read-only.Queued sends remain visible in **Drafts** and their conversation with a persistentstatus and **Cancel** action. A never-attempted send can be cancelled offline.@@ -625,9 +633,12 @@ authority commit together. It preserves newer edits and fences callbacks frombefore cancellation; older autosaves cannot overwrite or delete the restored copy. A failed queue attempt retains recovery content;cancel it before restoring and sending again. The server starts the undo delayat first admission, so reconnecting does not consume that delay while offline.-The send toast's **Undo** works after navigation closes the composer. It restores-the draft only after cancellation is confirmed. Pending cancellation, an expired-undo window, and failed cancellation each display a notice. Delivered attempts+The send toast's **Undo** works after navigation closes the composer. It shows+**Cancelling send…** until the server confirms, then **Send cancelled**, and+restores the draft only after that confirmation. The open conversation reads the+thread again, so the cancelled message never stays visible as sent beside the+restored draft. Cancellation that cannot be confirmed in time, an expired undo+window, and failed cancellation each display a notice. Delivered attemptsremain complete even if the sent message is later deleted from the provider.After Undo, delay the accepted cache record's refresh: the newer restored draftmust still reopen with its body and attachments. A later confirmed send must still@@ -663,8 +674,7 @@ Verify: queue a new message and a reply offline, close and reopen the app, andcheck their persistent status and read-only content. Cancel one before reconnectand confirm its send mutation is never issued. Reconnect the other and checkthat one stable attempt is replayed even after a lost response. Also test a-cancel racing admission, unavailable local storage, and a pending upload. Queue-admission means **Email queued to send** or **Email sending**, not provider delivery.+cancel racing admission, unavailable local storage, and a pending upload.Send a standalone message, let it open its thread, then use the toast's Undo andconfirm the original draft reopens. Repeat after delivery starts and check thevisible failure notice. Cancel a draft-only thread and check it returns to Drafts@@ -693,8 +703,8 @@ the stale submission, and old send cleanup must preserve a restored draft andits attachments. Logout should warn about queued sends even after their originallocal working copies have been retired; it must not claim to cancel server sends.Approved local sends survive sign-out, are hidden from other accounts, and resume-only when the same account signs back in. The status panel also lists pending and-failed server attempts from other devices, with pagination. Cancelling one must+only when the same account signs back in. The status panel also lists failed,+unconfirmed, and scheduled server attempts from other devices, with pagination. Cancelling one mustpreserve this device's unsynced edits. A malformed or newer-version journal recordshows a recovery warning, retains its recognizable draft locks, and does not stopunrelated valid sends. Reconnecting an expired email account requires **Checkdiff --git a/docs/architecture/email.md b/docs/architecture/email.mdindex 00e21ce45a..5ed3a27a6a 100644--- a/docs/architecture/email.md+++ b/docs/architecture/email.md@@ -154,7 +154,7 @@ The compose controllers now assemble these smaller responsibilities:| Module | Responsibility and boundary || --- | --- || `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. Send Later freezes its deadline in the send intent; updating an existing legacy schedule saves first. Cancellation only unlocks editing after confirmation. |+| `email-send-schedule.ts` | Confirmed send time, pending changes, unscheduling and archive feedback. Send Later and schedule updates save the draft first, then schedule it through the REST endpoint. Cancellation only unlocks editing after confirmation. || `draft-session.ts` / `draft-persistence.ts` | Shared draft identity, queued-write status, rejection policy, and save/delete ordering. Server identity and a committed latest save are separate facts; uploads and updates to existing legacy schedules wait for a committed save. || `send-readiness.ts` | Outbox admission allows offline delivery with complete attachment references and rejects unfinished uploads. || `draft-autosave.ts` | One debounce and serialized write queue used by reply and standalone compose. Captures editor values before queueing, flushes pending edits on disposal, and exposes cancellation and completion for send/discard. |@@ -502,8 +502,11 @@ boundaries and exclusive all-day ends without mounting a calendar grid.## Independent send outbox-All composer sends use a device email journal for Gmail and Outlook,-independent of GraphQL normalized-cache availability and read transport.+All immediate composer sends use a device email journal for Gmail and Outlook,+independent of GraphQL normalized-cache availability and read transport. Send+Later schedules the saved draft through the REST schedule endpoint, so it stays a+draft listed by `/email/drafts/scheduled`; outbox admission makes a message+non-draft, which that list excludes.`send-queue.ts` freezes approval and reserves the draft in IndexedDB beforereturning local acceptance. `outbox-session.ts` runs dispatch and recovery fromthe authenticated app shell; mounted composers only observe them.@@ -563,7 +566,12 @@ attachment handles retain the generation captured at reservation.The status panel combines device intents with actor/inbox-authorized, cursor-paged`pendingEmailSends`, with batched message hydration. Server listing grants observation and cancellation authority,never automatic resubmission. Delivery state distinguishes local queueing,-server acceptance, provider processing, sent, failed, and unconfirmed outcomes.+server acceptance, provider processing, sent, failed, and unconfirmed outcomes,+but the panel stays silent for routine delivery: it lists a send only while it+waits on this device, needs attention, or is scheduled. Thread surfaces project+approved immediate sends from the journal as sent messages+(`email-thread/primitives/optimistic-send.ts`) until the thread read shows them,+and read the thread once when delivery is confirmed.Deploy schema/migrations and all generation-aware backend writers beforereleasing this frontend, including before applying `ios-update`: that workflow