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-compose): follow a queued send to its outcome (#8802)
teo45a6e60331eb
diff --git a/apps/web/src/features/email-compose/compose-adapter.ts b/apps/web/src/features/email-compose/compose-adapter.tsindex 0aae8ba58f..73095a6a86 100644--- a/apps/web/src/features/email-compose/compose-adapter.ts+++ b/apps/web/src/features/email-compose/compose-adapter.ts@@ -112,6 +112,7 @@ import {} from './queries/draft-lifecycle';import { createEmailInboxSource } from './queries/inbox-source';import { queuedDraftSaveArgs } from './queries/queued-draft';+import { watchEmailSendProgress } from './queries/send-progress';import {restoreDraftBodyAfterUndo,runQueuedUndoSend,@@ -573,6 +574,7 @@ export function createEmailComposeContext(emailSendMatchesDraft(intent, draftId) &&emailSendLocked(intent))),+ watchSend: watchEmailSendProgress,async sendMessage({ inboxId, ...input }) {if (!inboxSourcediff --git a/apps/web/src/features/email-compose/context/compose-capabilities.ts b/apps/web/src/features/email-compose/context/compose-capabilities.tsindex beff723127..d20c15d9fb 100644--- a/apps/web/src/features/email-compose/context/compose-capabilities.ts+++ b/apps/web/src/features/email-compose/context/compose-capabilities.ts@@ -235,6 +235,19 @@ export interface OutgoingEmail {>;}+/**+ * One queued send as this device's outbox last recorded it. `accepted` is+ * cancellable until the server's `undoUntil`; `pending` covers waiting,+ * delivering, and cancellation in progress.+ */+export type EmailSendProgress =+ | { state: 'pending' }+ | { state: 'accepted'; undoUntil: string }+ | { state: 'sent' }+ | { state: 'failed' }+ | { state: 'cancelled' }+ | { state: 'unconfirmed' };+export interface EmailDelivery {/** Whether sends can be persisted and replayed without connectivity. */queueActive?: (inboxId?: string) => boolean;@@ -242,6 +255,11 @@ export interface EmailDelivery {sendLocked?: (draftId: string | undefined) => boolean;/** Durable sends on their way; cancelled, failed and scheduled sends are excluded. */outgoing?: () => OutgoingEmail[];+ /** Reports each change until the send is sent, fails, is cancelled, or leaves this device. */+ watchSend?(+ sendAttemptId: string,+ changed: (progress: EmailSendProgress) => void+ ): () => void;sendMessage(input: SendEmailDraft): Promise<PersistedEmailIdentity>;unschedule(input: {draftGeneration?: number;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 f62180421c..bd1943e629 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@@ -687,8 +687,10 @@ it('does not mistake its own in-flight send for a delivery elsewhere', async ()expect(composeContext.notices.feedback.alert).not.toHaveBeenCalled();expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(- 'Email sent',- expect.anything()+ expect.any(String),+ expect.objectContaining({+ actions: [expect.objectContaining({ label: 'Undo' })],+ }));root.dispose();});@@ -721,8 +723,10 @@ it('does not announce a plain send as a scheduled one', async () => {);expect(composeContext.notices.feedback.alert).not.toHaveBeenCalled();expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(- 'Email sent',- expect.anything()+ expect.any(String),+ expect.objectContaining({+ actions: [expect.objectContaining({ label: 'Undo' })],+ }));root.dispose();});diff --git a/apps/web/src/features/email-compose/primitives/draft-transfer-identity.test.ts b/apps/web/src/features/email-compose/primitives/draft-transfer-identity.test.tsindex fb11fe7a8b..0b3f69b090 100644--- a/apps/web/src/features/email-compose/primitives/draft-transfer-identity.test.ts+++ b/apps/web/src/features/email-compose/primitives/draft-transfer-identity.test.ts@@ -165,6 +165,47 @@ it.each(directions)(});+it.each(directions)(+ 'keeps a draft moved from %s to %s when the host cannot show it',+ async (_from, _to, source, destination) => {+ const { context, moved } = createDeviceContext(source, destination);+ const navigation = new Error('Could not open the moved thread');+ const root = mountEmailComposer(+ context,+ {+ showMovedDraft: () => {+ throw navigation;+ },+ },+ {+ draft: message('draft', {+ is_draft: true,+ link_id: 'inbox',+ from: { email: source.email_address },+ }),+ }+ );+ try {+ root.edit('Moving draft');+ await root.state.flushLocal();+ root.state.context.onSelectInbox?.('other');+ expect(await moved).toEqual({+ saved: expect.objectContaining({+ inboxId: 'other',+ draft: expect.objectContaining({+ db_id: 'moved-draft',+ sender_email: destination.email_address,+ }),+ }),+ });+ expect(context.notices.feedback.failure).not.toHaveBeenCalled();+ expect(context.notices.reportError).toHaveBeenCalledWith(navigation);+ } finally {+ root.dispose();+ }+ }+);+it.each(directions)('keeps saving a reply locally after its sender moves it from %s to %s',async (_from, _to, source, destination) => {diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.tsindex 19dc759666..c2ddc778b2 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts@@ -79,6 +79,7 @@ import { createDraftSaveNotice } from './draft-save-notice';import { createDraftSession } from './draft-session';import { createDraftTransfer } from './draft-transfer';import { createEmailSendSchedule } from './email-send-schedule';+import { announceQueuedSend } from './queued-send-notice';import {pendingInlineMedia,refuseSend,@@ -840,33 +841,22 @@ export function createEmailComposer(props: EmailComposerOptions) {// 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(- offline ? 'Email queued to send' : 'Email sent',- {- actions: draftId- ? [- {- label: 'Undo',- onClick: () => {- if (toastId != null)- props.notices.feedback.dismiss(toastId);- void undoSend(- draftId,- threadId ?? undefined,- inboxId,- identity.sendAttemptId- ).catch(props.notices.reportError);- },- },- ]- : undefined,- duration: 5_000,- }- );- } catch (error) {- props.notices.reportError(error);- }+ announceQueuedSend({+ notices: props.notices,+ delivery: props.delivery,+ sendAttemptId: identity.sendAttemptId,+ queuedOffline: offline,+ undo: draftId+ ? () => {+ void undoSend(+ draftId,+ threadId ?? undefined,+ inboxId,+ identity.sendAttemptId+ ).catch(props.notices.reportError);+ }+ : undefined,+ });try {// The server has no thread to show until an offline send goes out.if (offline) props.host?.goBack?.();@@ -1296,6 +1286,15 @@ export function createEmailComposer(props: EmailComposerOptions) {autosave.cancel();},});+ // The move has committed, so a host that cannot show it must not turn the+ // switch into a failed inbox change.+ const showMovedDraft = (moved: { draftId: string; threadId: string }) => {+ try {+ props.host?.showMovedDraft?.(moved);+ } catch (error) {+ props.notices.reportError(error);+ }+ };const selectInbox = async (inboxId: string, senderEmail?: string) => {if (sendLocked() ||@@ -1332,7 +1331,7 @@ export function createEmailComposer(props: EmailComposerOptions) {// The save captures the new sender before the host can unmount this// composer to show the moved draft.const saved = autosave.save();- if (moved) props.host?.showMovedDraft?.(moved);+ if (moved) showMovedDraft(moved);await saved;} catch (error) {props.notices.reportError(error);diff --git a/apps/web/src/features/email-compose/primitives/queued-send-notice.ts b/apps/web/src/features/email-compose/primitives/queued-send-notice.tsnew file mode 100644index 0000000000..9c9b0bfa50--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/queued-send-notice.ts@@ -0,0 +1,88 @@+import { match } from 'ts-pattern';+import type {+ EmailComposeFeedback,+ EmailDelivery,+} from '../context/compose-capabilities';++/**+ * Tells the user only what a queued send has done. Undo stays on offer until+ * the server's own deadline, and the send is called sent once it is delivered.+ */+export function announceQueuedSend(options: {+ notices: EmailComposeFeedback;+ delivery: Pick<EmailDelivery, 'watchSend'>;+ sendAttemptId: string | undefined;+ queuedOffline: boolean;+ undo: (() => void) | undefined;+ /** The send failed or was cancelled, so nothing was delivered. */+ onUndelivered?: () => void;+}): void {+ const { notices, undo } = options;+ let undoNotice: number | undefined;+ let undoRequested = false;+ let accepted = false;+ const withdrawUndo = () => {+ if (undoNotice != null) notices.feedback.dismiss(undoNotice);+ undoNotice = undefined;+ };+ const offerUndo = (message: string, duration?: number) => {+ try {+ undoNotice = notices.feedback.success(message, {+ actions: undo+ ? [+ {+ label: 'Undo',+ onClick: () => {+ undoRequested = true;+ withdrawUndo();+ undo();+ },+ },+ ]+ : undefined,+ duration,+ });+ } catch (error) {+ notices.reportError(error);+ }+ };+ offerUndo(options.queuedOffline ? 'Email queued to send' : 'Sending…');+ if (!options.sendAttemptId) return;+ options.delivery.watchSend?.(options.sendAttemptId, (progress) =>+ match(progress)+ .with({ state: 'pending' }, () => {+ // After acceptance, pending means delivery or cancellation has begun.+ if (accepted) withdrawUndo();+ })+ .with({ state: 'accepted' }, ({ undoUntil }) => {+ accepted = true;+ const remaining = Date.parse(undoUntil) - Date.now();+ if (!undoRequested && remaining > 0) offerUndo('Sending…', remaining);+ else withdrawUndo();+ })+ .with({ state: 'sent' }, () => {+ withdrawUndo();+ notices.feedback.success('Email sent');+ })+ .with({ state: 'failed' }, () => {+ withdrawUndo();+ notices.feedback.failure('Email failed to send', {+ subtext:+ 'Open its conversation or Drafts and choose Cancel to recover the draft.',+ persistent: true,+ });+ options.onUndelivered?.();+ })+ .with({ state: 'cancelled' }, () => {+ withdrawUndo();+ options.onUndelivered?.();+ })+ .with({ state: 'unconfirmed' }, () => {+ withdrawUndo();+ notices.feedback.alert('Delivery unconfirmed', {+ subtext: 'Check your sent mail. We will not resend automatically.',+ });+ })+ .exhaustive()+ );+}diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.tsindex 159c33fce9..6119e5d531 100644--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts@@ -80,6 +80,7 @@ import {prepareMacroBody,TOGGLE_APPEND_EMAIL_THREAD_COMMAND,} from './prepare-email-body';+import { announceQueuedSend } from './queued-send-notice';import {createReplyComposerFocus,takesFocusOnMount,@@ -154,7 +155,7 @@ export type ReplyComposerOptions = {onUndoHandle?: (handle: EmailUndoHandle) => void;/** False keeps the view on this thread instead of opening the next one. */navigate?: boolean;- /** True once the send was undone; marking done may still be pending. */+ /** True once the send was undone or failed; marking done may still be pending. */cancelled?: () => boolean;}) => void;setShowReply?: Setter<boolean>;@@ -1361,9 +1362,18 @@ export function createReplyComposer(// Each undo action retains this send's inbox, thread and mark-done, even// if the composer sends again or navigation disposes the view.let markDoneUndoHandle: EmailUndoHandle | undefined;- // Advancing may archive after a page loads; an undo before then must- // not leave the restored thread marked done.- let sendUndone = false;+ // Advancing may archive after a page loads; an undo or failure before+ // then must not leave the thread marked done.+ let returnedToInbox = false;+ const returnToInbox = async () => {+ returnedToInbox = true;+ const doneHandle = markDoneUndoHandle;+ markDoneUndoHandle = undefined;+ await doneHandle?.undo({+ onError: () =>+ props.notices.feedback.failure('Failed to restore thread to inbox'),+ });+ };const undoSend = (draftId: string) =>props.delivery.undoSend({sendAttemptId: result.sendAttemptId,@@ -1371,47 +1381,30 @@ export function createReplyComposer(draftId,inboxId,onUndone: async (undo) => {- sendUndone = true;+ returnedToInbox = true;await restoreAfterUndoSend(draftId,result.threadId,inboxId,undo?.draftRestored);- const doneHandle = markDoneUndoHandle;- markDoneUndoHandle = undefined;- await doneHandle?.undo({- onError: () =>- props.notices.feedback.failure(- 'Failed to restore thread to inbox'- ),- });+ await returnToInbox();},});// 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(- offline ? 'Email queued to send' : 'Email sent',- {- actions: draftId- ? [- {- label: 'Undo',- onClick: () => {- if (toastId != null)- props.notices.feedback.dismiss(toastId);- void undoSend(draftId).catch(props.notices.reportError);- },- },- ]- : undefined,- duration: 5_000,- }- );- } catch (error) {- props.notices.reportError(error);- }+ announceQueuedSend({+ notices: props.notices,+ delivery: props.delivery,+ sendAttemptId: result.sendAttemptId,+ queuedOffline: offline,+ undo: draftId+ ? () => {+ void undoSend(draftId).catch(props.notices.reportError);+ }+ : undefined,+ onUndelivered: () => fireAndForget(returnToInbox(), 'email-compose'),+ });for (const mention of prepared.mentions) {try {props.recordMention(sourceEntityId, mention.documentId);@@ -1427,10 +1420,13 @@ export function createReplyComposer(silent: true,onUndoHandle: (handle) => {markDoneUndoHandle = handle;+ // Marking done can finish after the send was undone or failed.+ if (returnedToInbox)+ fireAndForget(returnToInbox(), 'email-compose');},navigate: markDone,cancelled: () =>- sendUndone || sendOperation !== sendOperationVersion,+ returnedToInbox || sendOperation !== sendOperationVersion,});} catch (error) {props.notices.reportError(error);diff --git a/apps/web/src/features/email-compose/primitives/send-outcome.test.ts b/apps/web/src/features/email-compose/primitives/send-outcome.test.tsnew file mode 100644index 0000000000..fcf992b9a5--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/send-outcome.test.ts@@ -0,0 +1,307 @@+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type {+ EmailComposeContext,+ EmailInbox,+ EmailSendProgress,+ EmailUndoHandle,+} from '../context/compose-capabilities';+import type { EmailRecipient } from '../core/email-recipient';+import type { ReplyType } from '../core/reply-type';+import { createComposeContext } from '../tests/capabilities';+import { mountEmailComposer } from '../tests/composer';+import { mountReplyComposer } from '../tests/reply';+import type { ReplyComposerOptions } from './reply-composer';++beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++const providers = ['GMAIL', 'OUTLOOK'] as const;+const teammate: EmailRecipient = {+ kind: 'custom',+ id: '[email protected]',+ data: {+ id: '[email protected]',+ email: '[email protected]',+ invalid: false,+ },+};++/** A composer whose queued send reports its progress as the outbox does. */+function outbox(provider: EmailInbox['provider']) {+ const context = createComposeContext();+ context.accounts.inboxes = () => [+ { id: 'inbox', email_address: '[email protected]', provider, settings: {} },+ ];+ context.delivery.sendMessage = vi.fn(async () => ({+ sendAttemptId: 'attempt',+ persistence: 'queued' as const,+ draftId: 'draft',+ threadId: 'thread',+ inboxId: 'inbox',+ }));+ const watchers = new Map<string, (progress: EmailSendProgress) => void>();+ context.delivery.watchSend = vi.fn((sendAttemptId, changed) => {+ watchers.set(sendAttemptId, changed);+ return () => watchers.delete(sendAttemptId);+ });+ return {+ context,+ report: (progress: EmailSendProgress) =>+ watchers.get('attempt')?.(progress),+ };+}++/** A thread in the inbox, completed by its send; `undo` returns it to the inbox. */+function inboxThread() {+ const undo = vi.fn(async () => {});+ const onMarkDone = vi.fn<NonNullable<ReplyComposerOptions['onMarkDone']>>(+ (options) => options?.onUndoHandle?.({ id: 'done', undo, dispose() {} })+ );+ return { undo, onMarkDone };+}++/** The notice the user sees last, whichever kind it is. */+function lastNotice(context: EmailComposeContext) {+ const { success, failure, alert } = context.notices.feedback;+ return (+ [+ ['success', vi.mocked(success).mock],+ ['failure', vi.mocked(failure).mock],+ ['alert', vi.mocked(alert).mock],+ ] as const+ )+ .flatMap(([kind, mock]) =>+ mock.invocationCallOrder.map((order) => ({ kind, order }))+ )+ .sort((left, right) => left.order - right.order)+ .at(-1)?.kind;+}++/** When the newest Undo offer ends, on this device's clock. */+function undoOfferEnds(context: EmailComposeContext) {+ const offer = vi+ .mocked(context.notices.feedback.success)+ .mock.calls.filter(([, options]) =>+ options?.actions?.some((action) => action.label === 'Undo')+ )+ .at(-1);+ const duration = offer?.[1]?.duration;+ return duration === undefined ? undefined : Date.now() + duration;+}++/** Undo offers still on screen, given notices that return their ids. */+function openUndoOffers(context: EmailComposeContext) {+ const { success, dismiss } = vi.mocked(context.notices.feedback);+ const dismissed = new Set(dismiss.mock.calls.map(([id]) => id));+ return success.mock.calls.filter(+ ([, options], index) =>+ options?.actions?.some((action) => action.label === 'Undo') &&+ !dismissed.has(success.mock.results[index]?.value)+ ).length;+}++it.each(providers)(+ '%s: keeps a delivered reply done and offers Undo until the server deadline',+ async (provider) => {+ const { context, report } = outbox(provider);+ const thread = inboxThread();+ const reply = mountReplyComposer(+ context,+ undefined,+ { onMarkDone: thread.onMarkDone },+ { inboxVisible: true }+ );+ try {+ await reply.sendEmail();+ expect(thread.onMarkDone).toHaveBeenCalledOnce();++ const undoUntil = new Date(Date.now() + 9_640).toISOString();+ report({ state: 'pending' });+ report({ state: 'accepted', undoUntil });+ expect(undoOfferEnds(context)).toBe(Date.parse(undoUntil));++ report({ state: 'pending' });+ report({ state: 'sent' });+ await vi.advanceTimersByTimeAsync(0);+ expect(thread.undo).not.toHaveBeenCalled();+ expect(thread.onMarkDone).toHaveBeenCalledOnce();+ expect(lastNotice(context)).toBe('success');+ } finally {+ reply.dispose();+ }+ }+);++it.each(+ providers.flatMap((provider) =>+ (['reply', 'forward'] as const).map((kind) => [provider, kind] as const)+ )+)(+ '%s: returns the thread to the inbox when a %s fails after it was queued',+ async (provider, kind: ReplyType) => {+ const { context, report } = outbox(provider);+ const thread = inboxThread();+ const [replyType, setReplyType] = createSignal<ReplyType | undefined>(kind);+ const reply = mountReplyComposer(+ context,+ undefined,+ { onMarkDone: thread.onMarkDone },+ {+ inboxVisible: true,+ replyRequest: { replyType, clear: () => setReplyType(undefined) },+ }+ );+ try {+ await vi.advanceTimersByTimeAsync(0);+ if (kind === 'forward') reply.form.setRecipients('to', [teammate]);+ await reply.sendEmail();+ expect(thread.onMarkDone).toHaveBeenCalledOnce();++ report({+ state: 'accepted',+ undoUntil: new Date(Date.now() + 10_000).toISOString(),+ });+ report({ state: 'pending' });+ report({ state: 'failed' });+ await vi.advanceTimersByTimeAsync(0);++ expect(thread.undo).toHaveBeenCalledOnce();+ expect(lastNotice(context)).toBe('failure');+ } finally {+ reply.dispose();+ }+ }+);++it.each(providers)(+ '%s: leaves the thread in the inbox when its failed send is restored',+ async (provider) => {+ const { context, report } = outbox(provider);+ const thread = inboxThread();+ const reply = mountReplyComposer(+ context,+ undefined,+ { onMarkDone: thread.onMarkDone },+ { inboxVisible: true }+ );+ try {+ await reply.sendEmail();+ report({ state: 'failed' });+ await vi.advanceTimersByTimeAsync(0);+ report({ state: 'cancelled' });+ await vi.advanceTimersByTimeAsync(0);++ expect(thread.undo).toHaveBeenCalledOnce();+ expect(thread.onMarkDone).toHaveBeenCalledOnce();+ expect(lastNotice(context)).toBe('failure');+ } finally {+ reply.dispose();+ }+ }+);++it.each(providers)(+ '%s: does not archive a thread whose send failed before the advance completed',+ async (provider) => {+ const { context, report } = outbox(provider);+ let cancelled: (() => boolean) | undefined;+ const reply = mountReplyComposer(+ context,+ undefined,+ {+ onMarkDone: (options) => {+ cancelled = options?.cancelled;+ },+ },+ { inboxVisible: true }+ );+ try {+ await reply.sendEmail(true);+ expect(cancelled?.()).toBe(false);+ report({ state: 'failed' });+ await vi.advanceTimersByTimeAsync(0);+ expect(cancelled?.()).toBe(true);+ } finally {+ reply.dispose();+ }+ }+);++it.each(providers)(+ '%s: withdraws Undo when the server accepts the send after its deadline',+ async (provider) => {+ const { context, report } = outbox(provider);+ let notice = 0;+ vi.mocked(context.notices.feedback.success).mockImplementation(+ () => ++notice+ );+ const reply = mountReplyComposer(context);+ try {+ await reply.sendEmail();+ expect(openUndoOffers(context)).toBe(1);++ report({+ state: 'accepted',+ undoUntil: new Date(Date.now() - 1_000).toISOString(),+ });+ expect(openUndoOffers(context)).toBe(0);+ } finally {+ reply.dispose();+ }+ }+);++it.each(providers)(+ '%s: returns the thread to the inbox when it is marked done after its send failed',+ async (provider) => {+ const { context, report } = outbox(provider);+ const undo = vi.fn(async () => {});+ let markedDone: ((handle: EmailUndoHandle) => void) | undefined;+ const reply = mountReplyComposer(+ context,+ undefined,+ {+ onMarkDone: (options) => {+ markedDone = options?.onUndoHandle;+ },+ },+ { inboxVisible: true }+ );+ try {+ await reply.sendEmail(true);+ report({ state: 'failed' });+ await vi.advanceTimersByTimeAsync(0);+ markedDone?.({ id: 'done', undo, dispose() {} });+ await vi.advanceTimersByTimeAsync(0);++ expect(undo).toHaveBeenCalledOnce();+ } finally {+ reply.dispose();+ }+ }+);++it.each(providers)(+ '%s: offers Undo until the server deadline and reports a new message that fails',+ async (provider) => {+ const { context, report } = outbox(provider);+ const root = mountEmailComposer(context);+ try {+ root.edit('Quarterly numbers attached');+ await vi.advanceTimersByTimeAsync(600);+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();++ const undoUntil = new Date(Date.now() + 9_910).toISOString();+ report({ state: 'accepted', undoUntil });+ expect(undoOfferEnds(context)).toBe(Date.parse(undoUntil));++ report({ state: 'failed' });+ expect(lastNotice(context)).toBe('failure');+ } finally {+ root.dispose();+ }+ }+);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 b1be20e5d6..1636b2bbb2 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@@ -25,6 +25,15 @@ function hoursFromNow(hours: number): Date {return new Date(Date.now() + hours * 60 * 60 * 1000);}+/** The send notice that offers Undo. */+function undoOffer(context: EmailComposeContext) {+ return vi+ .mocked(context.notices.feedback.success)+ .mock.calls.find(([, options]) =>+ options?.actions?.some((action) => action.label === 'Undo')+ );+}+it.each(['standalone', 'reply'] as const)('%s refreshes lifecycle after a queued cancellation before accepting an old sent observation',async (kind) => {@@ -582,9 +591,7 @@ describe('send and schedule ordering', () => {try {state.edit('Earlier reply');await state.sendEmail();- const sentNotice = vi- .mocked(context.notices.feedback.success)- .mock.calls.find(([text]) => text === 'Email sent');+ const sentNotice = undoOffer(context);state.edit('Newer reply that must survive');sentNotice?.[1]?.actions?.[0].onClick();@@ -623,9 +630,7 @@ describe('send and schedule ordering', () => {try {const send = state.sendEmail(true);await vi.advanceTimersByTimeAsync(0);- const sentNotice = vi- .mocked(composeContext.notices.feedback.success)- .mock.calls.find(([text]) => text === 'Email sent');+ const sentNotice = undoOffer(composeContext);expect(onMarkDone).toHaveBeenCalledOnce();// Send and mark done moves on to the next thread, like Mark done.expect(onMarkDone).toHaveBeenCalledWith(@@ -1270,9 +1275,7 @@ describe('send and schedule ordering', () => {expect(composeContext.delivery.sendMessage).toHaveBeenCalledWith(expect.objectContaining({ inboxId: 'secondary' }));- const notice = vi- .mocked(composeContext.notices.feedback.success)- .mock.calls.find(([text]) => text === 'Email sent');+ const notice = undoOffer(composeContext);if (remount) state.dispose();notice?.[1]?.actions?.[0].onClick();await vi.advanceTimersByTimeAsync(0);diff --git a/apps/web/src/features/email-compose/queries/send-progress.test.ts b/apps/web/src/features/email-compose/queries/send-progress.test.tsnew file mode 100644index 0000000000..55eba680b3--- /dev/null+++ b/apps/web/src/features/email-compose/queries/send-progress.test.ts@@ -0,0 +1,248 @@+import 'fake-indexeddb/auto';+import { createEmailSendDispatcher } from '@queries/email/email-send-dispatcher';+import {+ emailStorageSession,+ localDraftStore,+} from '@queries/email/local-drafts';+import {+ cancelEmailSendQueued,+ type EmailSendIntent,+} from '@queries/email/send-queue';+import type { EmailSendAttemptFieldsFragment } from '@service-storage/graphql/generated/graphql';+import { CombinedError } from '@urql/core';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { EmailSendProgress } from '../context/compose-capabilities';+import { watchEmailSendProgress } from './send-progress';++vi.mock('@queries/email/local-drafts', async () => {+ const { createLocalDraftStore } = await import(+ '@queries/email/local-draft-store'+ );+ const localDraftStore = createLocalDraftStore(crypto.randomUUID());+ const session = localDraftStore.activate('owner');+ return {+ localDraftStore,+ emailStorageSession: () => session,+ readLocalEmailSends: async () => localDraftStore.sends(await session),+ persistLocalEmailSend: async (intent: EmailSendIntent, reserve = false) =>+ localDraftStore.putSend(await session, intent, reserve),+ watchLocalEmailSends: (changed: () => void) =>+ localDraftStore.subscribe(changed),+ };+});++const inboxes = [+ { provider: 'Gmail', linkId: 'gmail-inbox', email: '[email protected]' },+ { provider: 'Outlook', linkId: 'outlook-inbox', email: '[email protected]' },+] as const;+type Inbox = (typeof inboxes)[number];++const stops: (() => void)[] = [];+const runners: ReturnType<typeof createEmailSendDispatcher>[] = [];++beforeEach(() => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ vi.setSystemTime(new Date('2026-10-20T19:00:00Z'));+ vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(true);+});+afterEach(() => {+ for (const stop of stops.splice(0)) stop();+ for (const runner of runners.splice(0)) runner.dispose();+ vi.useRealTimers();+ vi.restoreAllMocks();+});++function intent(inbox: Inbox): EmailSendIntent {+ const id = crypto.randomUUID();+ return {+ uuid: id,+ dispatchVersion: 2,+ phase: 'pending',+ locallyCancelled: false,+ metadata: {+ kind: 'email-send-v1',+ payload: {+ input: {+ attempt: { attemptId: id, linkId: inbox.linkId },+ message: {+ draftId: `draft-${id}`,+ subject: 'Fwd: Quarterly numbers',+ bodyText: 'See the attached numbers',+ },+ attachmentIds: [],+ forwardedAttachmentIds: [],+ },+ draft: {+ draftId: `draft-${id}`,+ threadDbId: 'thread',+ subject: 'Fwd: Quarterly numbers',+ senderEmail: inbox.email,+ senderLinkId: inbox.linkId,+ optimisticBodyHtml: null,+ },+ },+ },+ };+}++function attempt(+ queued: EmailSendIntent,+ status: EmailSendAttemptFieldsFragment['status']+): EmailSendAttemptFieldsFragment {+ return {+ attemptId: queued.uuid,+ status,+ message: null,+ threadId: 'thread',+ sendTime: '2026-10-20T19:00:10.640Z',+ };+}++/** Records one send's progress; `reached` resolves once a state is reported. */+function follow(sendAttemptId: string) {+ const updates: EmailSendProgress[] = [];+ const waiting = new Map<EmailSendProgress['state'], () => void>();+ stops.push(+ watchEmailSendProgress(sendAttemptId, (progress) => {+ updates.push(progress);+ waiting.get(progress.state)?.();+ })+ );+ return {+ updates,+ reached: (state: EmailSendProgress['state']) =>+ new Promise<void>((resolve) => {+ if (updates.some((update) => update.state === state)) resolve();+ else waiting.set(state, resolve);+ }),+ };+}++async function queue(inbox: Inbox) {+ const session = await emailStorageSession();+ const queued = await localDraftStore.putSend(session, intent(inbox), true);+ return { session, queued, progress: follow(queued.uuid) };+}++function dispatch(+ session: Awaited<ReturnType<typeof emailStorageSession>>,+ server: Pick<+ Parameters<typeof createEmailSendDispatcher>[0],+ 'submit' | 'cancel' | 'status'+ >+) {+ const runner = createEmailSendDispatcher({+ session,+ journal: localDraftStore,+ report: vi.fn(),+ ...server,+ });+ runners.push(runner);+ return runner;+}++it.each(inboxes)(+ 'reports a $provider send as undoable until the server deadline, then failed',+ async (inbox) => {+ const { session, queued, progress } = await queue(inbox);+ await progress.reached('pending');+ const runner = dispatch(session, {+ submit: async () => attempt(queued, 'ACCEPTED'),+ cancel: vi.fn(),+ status: async () => attempt(queued, 'FAILED'),+ });+ await runner.wake();+ await progress.reached('accepted');+ vi.setSystemTime(Date.now() + 5_000);+ await runner.wake();+ await progress.reached('failed');++ expect(progress.updates).toEqual([+ { state: 'pending' },+ { state: 'accepted', undoUntil: '2026-10-20T19:00:10.640Z' },+ { state: 'failed' },+ ]);+ }+);++it.each(inboxes)(+ 'reports a $provider send the server rejects as failed',+ async (inbox) => {+ const { session, progress } = await queue(inbox);+ await progress.reached('pending');+ const runner = dispatch(session, {+ submit: async () => {+ throw new CombinedError({+ graphQLErrors: [+ {+ message: 'Attachment unavailable',+ extensions: { code: 'INVALID' },+ },+ ],+ });+ },+ cancel: vi.fn(),+ status: vi.fn(),+ });+ await runner.wake();+ await progress.reached('failed');++ expect(progress.updates).toEqual([+ { state: 'pending' },+ { state: 'failed' },+ ]);+ }+);++it.each(inboxes)(+ 'stops offering Undo for a $provider send once cancellation is requested',+ async (inbox) => {+ const { session, queued, progress } = await queue(inbox);+ await progress.reached('pending');+ const runner = dispatch(session, {+ submit: async () => attempt(queued, 'ACCEPTED'),+ cancel: async () => attempt(queued, 'CANCELLED'),+ status: async () => attempt(queued, 'ACCEPTED'),+ });+ await runner.wake();+ await progress.reached('accepted');+ const current = (await localDraftStore.sends(session)).find(+ (row) => row.uuid === queued.uuid+ );+ if (!current) throw new Error('The accepted send left the outbox');+ await cancelEmailSendQueued(current);+ await runner.wake();+ await progress.reached('cancelled');++ expect(progress.updates).toEqual([+ { state: 'pending' },+ { state: 'accepted', undoUntil: '2026-10-20T19:00:10.640Z' },+ { state: 'pending' },+ { state: 'cancelled' },+ ]);+ }+);++it.each(inboxes)(+ 'reports a delivered $provider send as sent',+ async (inbox) => {+ const { session, queued, progress } = await queue(inbox);+ await progress.reached('pending');+ const runner = dispatch(session, {+ submit: async () => attempt(queued, 'ACCEPTED'),+ cancel: vi.fn(),+ status: async () => attempt(queued, 'SENT'),+ });+ await runner.wake();+ await progress.reached('accepted');+ vi.setSystemTime(Date.now() + 5_000);+ await runner.wake();+ await progress.reached('sent');++ expect(progress.updates).toEqual([+ { state: 'pending' },+ { state: 'accepted', undoUntil: '2026-10-20T19:00:10.640Z' },+ { state: 'sent' },+ ]);+ }+);diff --git a/apps/web/src/features/email-compose/queries/send-progress.ts b/apps/web/src/features/email-compose/queries/send-progress.tsnew file mode 100644index 0000000000..c9571ffcda--- /dev/null+++ b/apps/web/src/features/email-compose/queries/send-progress.ts@@ -0,0 +1,95 @@+import { deepEqual } from '@core/util/compareUtils';+import { fireAndForget } from '@core/util/fireAndForget';+import {+ type EmailSendIntent,+ emailSendLocked,+ readEmailSendIntents,+ settledSendAttempt,+ watchEmailSends,+} from '@queries/email/send-queue';+import { recordEmailSend } from '@queries/email/send-telemetry';+import type { EmailSendProgress } from '../context/compose-capabilities';++function emailSendProgress(intent: EmailSendIntent): EmailSendProgress {+ const attempt = settledSendAttempt(intent);+ if (attempt?.status === 'SENT') return { state: 'sent' };+ if (+ attempt?.status === 'CANCELLED' ||+ (intent.cancellationRequested && !emailSendLocked(intent))+ )+ return { state: 'cancelled' };+ // Undo owns the outcome once requested; it reports its own result.+ if (intent.cancellationRequested) return { state: 'pending' };+ if (attempt?.status === 'DELIVERY_UNCONFIRMED')+ return { state: 'unconfirmed' };+ if (intent.phase === 'failed' || attempt?.status === 'FAILED')+ return { state: 'failed' };+ if (attempt?.status === 'ACCEPTED' && attempt.sendTime)+ return { state: 'accepted', undoUntil: attempt.sendTime };+ return { state: 'pending' };+}++export function watchEmailSendProgress(+ sendAttemptId: string,+ changed: (progress: EmailSendProgress) => void+): () => void {+ const started = performance.now();+ let last: EmailSendProgress | undefined;+ let stopped = false;+ let reading = false;+ let rerun = false;+ const stop = () => {+ stopped = true;+ unsubscribe();+ };+ const read = async () => {+ const intent = (await readEmailSendIntents()).find(+ (row) => row.uuid === sendAttemptId+ );+ if (stopped) return;+ // Retired after delivery or restored after cancellation, possibly by another tab.+ if (!intent) return stop();+ const progress = emailSendProgress(intent);+ if (last && deepEqual(last, progress)) return;+ last = progress;+ if (progress.state !== 'pending' && progress.state !== 'accepted')+ recordEmailSend(+ {+ operation: 'status',+ outcome: 'observed',+ status: settledSendAttempt(intent)?.status,+ durationMs: performance.now() - started,+ },+ intent+ );+ if (+ progress.state === 'sent' ||+ progress.state === 'failed' ||+ progress.state === 'cancelled'+ )+ stop();+ changed(progress);+ };+ const drain = async () => {+ reading = true;+ try {+ do {+ rerun = false;+ await read();+ } while (rerun && !stopped);+ } finally {+ reading = false;+ }+ };+ const refresh = () => {+ if (stopped) return;+ if (reading) {+ rerun = true;+ return;+ }+ fireAndForget(drain(), 'email-compose');+ };+ const unsubscribe = watchEmailSends(refresh);+ refresh();+ return stop;+}diff --git a/apps/web/src/features/email-compose/views/reply-input.tsx b/apps/web/src/features/email-compose/views/reply-input.tsxindex ee5d3a61e2..8e206dea02 100644--- a/apps/web/src/features/email-compose/views/reply-input.tsx+++ b/apps/web/src/features/email-compose/views/reply-input.tsx@@ -751,7 +751,7 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {<Tooltip label={quoteToggleLabel()}><KToggleButtonas={Button}- aria-label={quoteToggleLabel()}+ aria-label={quotedContent()}variant="ghost"size="icon-sm"class="size-5 rounded bg-transparent p-0 text-ink-extra-muted hover:text-ink-muted"diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-done-action.tsindex ef16b14637..4d04d49a19 100644--- a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.ts@@ -96,7 +96,7 @@ type MarkDoneVariables = {notificationEntities: NotificationEntityRef[];restoreFocus?: () => void;/** Suppress the "Marked as done" toast, e.g. for send-triggered mark done- * where it would replace the "Email sent" toast. */+ * where it would replace the send toast. */silent?: boolean;/** Receives the undo handle once the mark-done is pushed onto the undo* stack, so callers (e.g. undo-send) can reverse it programmatically. */diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.tsindex 0ec1e57a25..a9be41d909 100644--- a/apps/web/src/lib/queries/email/thread.ts+++ b/apps/web/src/lib/queries/email/thread.ts@@ -450,7 +450,7 @@ type ArchiveThreadParams = {/** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */linkId?: string;/** Suppress the success toast, e.g. for a send-triggered archive where the- * "Email sent" toast (with its undo-send action) is already up and this+ * send toast (with its undo-send action) is already up and this* toast's own Undo would reverse only the archive, not the send. */silent?: boolean;/** Receives the undo handle once the archive is pushed onto the undodiff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 8db38fc78b..66f5bb0777 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -617,7 +617,8 @@ local copy, or Undo still reads **Forwarding** with a `Forward — @mention…`placeholder: Forward keeps its recipients, and Reply turns it into a replywithout the forwarded message. A reply quoting a message that was itselfforwarded stays a reply. Collapsed content is named: **Show forwarded message**-on a forward, **Show quoted text** on a reply.+on a forward, **Show quoted text** on a reply. The toggle beside the editor keeps+the name `forwarded message` or `quoted text` and reports whether it is pressed.Check recipient suggestions from a Gmail and an Outlook inbox. Typing a fulladdress and pressing Enter commits that address, ahead of longer matches suchas `[email protected]`, whether or not it is a saved contact. A name or@@ -765,7 +766,9 @@ Send and mark done (Shift+Cmd+Enter) and Mark done open the next email, countedfrom where the thread sat when it was opened (a reply draft lifts its thread tothe top of Signal while it is written). If the user has already moved toanother thread when the send finishes, the replied thread is marked done-without navigating; Undo before then leaves it in the inbox.+without navigating; Undo before then leaves it in the inbox. A delivered send+keeps the thread done. If the send fails after it was queued, or is cancelled or+restored, the thread returns to Inbox; verify this for Gmail and Outlook.Sending a message shows it in the open thread immediately, while delivery isstill pending. It stays visible until the thread refresh confirms it, with noduplicate message. Failed delivery removes that message and restores the reply@@ -776,7 +779,7 @@ focus belongs to the sent message card in the same thread pane, even whilethe thread refresh is still pending. Replying again requires clicking Replyor using a reply shortcut.-After a successful send, the `Email sent` notice offers `Undo`. Undo restores the+After a send is queued, its notice offers `Undo`. Undo restores thesent envelope and editable content, including when the reply used another inbox;a slow background refresh must not keep the restored editor disabled. A rejectedsend reports failure and restores its original reply editor if it is still mounted.@@ -806,11 +809,15 @@ status panel with **Cancel**.An authenticated app-level dispatcher submits online immediately and retries thesame attempt independently of unrelated draft, archive, and property mutations.-An online send shows **Email sent** with **Undo**: a new message opens its+An online send shows **Sending…** with **Undo**: a new message opens itsconversation 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+there immediately, before the server or provider confirms it. Once the server+accepts the send, **Undo** stays on offer until the server's undo deadline (the+accepted attempt's `sendTime`), not for a fixed client duration. The notice says+**Email sent** only after delivery. A send that fails after it was queued shows+a persistent **Email failed to send**, and **Delivery unconfirmed** reports a+send the provider did not confirm. An offline send shows **Email queued to+send** and returns to the email list. The status panel shows a send only while it waits on thisdevice (**Queued on this device**), needs attention, or is scheduled(**Scheduled**). On phones the panel sits below the safe area and the floatingheader. Only one active send can own a draft across tabs; queued composersdiff --git a/docs/architecture/email.md b/docs/architecture/email.mdindex 47dfa24df5..4c96256a75 100644--- a/docs/architecture/email.md+++ b/docs/architecture/email.md@@ -102,7 +102,7 @@ test exercises this ordering.| `EmailReplySession` | Thread identity, recipient options, personal-reply classification, a targeted reply request, and host intents for leaving the composer or removing its draft || `EmailDraftStorage` | Save/delete and restore an undone draft, and drop a moved draft's working copy; inputs use domain inbox IDs and completion intent || `EmailAttachmentStorage` | Upload, forward, and remove draft attachments |-| `EmailDelivery` | Send, undo, schedule, unschedule, and archive operations |+| `EmailDelivery` | Send, undo, schedule, unschedule, and archive operations, and each queued send's progress || `EmailComposeFeedback` | User notices and error reporting || `EmailComposeAccounts` | Inbox identities, availability, and the primary inbox || `EmailComposePresentation` | View-only device state, signature visibility, upgrade action, and link preparation |@@ -264,6 +264,7 @@ its failure handling. Adapter tests therefore exercise real TanStack mutations.| --- | --- || Draft save/delete or attachment write | Existing shared mutation reports the write failure; callers do not add a second schedule/save notice. || Send | Composer reports the failed send once. A failed reply restores only its original still-mounted editor; a newer editor's work is preserved. |+| Queued send that fails later | The send notice reports the failure; a reply that marked its thread done returns it to the inbox. || Schedule/unschedule | Schedule workflow reports the failed request and keeps the last confirmed time. || Post-send refresh/navigation/analytics | Report the presentation/cache error; do not report that delivery failed or enable a duplicate send. || Archive after scheduling | Keep the confirmed schedule and identify the archive failure separately. |@@ -276,6 +277,12 @@ and undo handle; sending again must preserve the earlier notification's undoaction. Standalone compose marks completion before its navigation callback, sodisposal cannot autosave or resend the successful message.+The send notice follows each queued send through `EmailDelivery.watchSend`,+which reads the device outbox. Undo stays on offer until the deadline the server+returned with the accepted attempt. A reply whose send fails, is cancelled, or is+restored reverses its mark-done through the same undo handle, including when+marking done finishes later.+`EmailThreadSource.refresh()` and `fetchOlder()` require `Promise<void>`. Theiradapters await the underlying query, and callers that need fresh messages awaitthat completion. They must not launch the request and resolve early.