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): make undo send more reliable (#5956)
Peter Chinmaneecc8483cb8e
diff --git a/apps/web/src/features/block-email/component/BaseInput.tsx b/apps/web/src/features/block-email/component/BaseInput.tsxindex 50618605f8..4af3580275 100644--- a/apps/web/src/features/block-email/component/BaseInput.tsx+++ b/apps/web/src/features/block-email/component/BaseInput.tsx@@ -77,6 +77,7 @@ import { invalidateSoupEntity, refetchSoupEntity } from '@queries/soup/cache';import type { UndoHandle } from '@queries/undo';import { emailClient } from '@service-email/client';import type {+ ApiDraftInput,ApiDraftOutputDbId,ApiMessage,} from '@service-email/generated/schemas';@@ -106,12 +107,18 @@ import {clearEmailBody,hasDraftContent,prepareEmailBody,+ prepareEmailBodyFromHtml,prepareMacroBody,registerToggleAppendedThread,TOGGLE_APPEND_EMAIL_THREAD_COMMAND,} from '../util/prepareEmailBody';import { convertEmailRecipientToContactInfo } from '../util/recipientConversion';import { getReplyTypeFromDraft } from '../util/replyType';+import {+ endUndoSend,+ tryBeginUndoSend,+ unscheduleWithRetry,+} from '../util/undoSendGuard';import { SignaturePreview } from './compose/SignaturePreview';import {type EmailRecipient,@@ -191,6 +198,15 @@ type UndoReplySnapshot = {bodyHtml: string;attachments: DraftFormAttachment[];includeSignature: boolean;+ /** Whether the quoted thread was appended in the editor at send time.+ * Restored so the quoted-text toggle matches the restored body — otherwise+ * it reads as "not appended" and appends a duplicate quote block. */+ replyAppended: boolean;+ /** Draft payload for restoring the server-side draft on undo. The+ * unscheduled message keeps the sent body (appended reply chain, injected+ * signature), so undo re-saves the draft with the pre-send content —+ * bodyHtml above, prepared at undo time, fills body_html. */+ draftRestore: ApiDraftInput;};// Set on send, persists across navigation, only consumed by undoSend.let undoSendSnapshot: UndoReplySnapshot | null = null;@@ -353,8 +369,12 @@ export function BaseInput(props: {// Gmail-style sizing: the composer opens compact and grows to the full cap// once the user scrolls the contentconst [composerExpanded, setComposerExpanded] = createSignal(false);- // Appended quoted thread starts hidden behind a "⋯" pill (desktop)- const [quoteCollapsed, setQuoteCollapsed] = createSignal(true);+ // Appended quoted thread starts hidden behind a "⋯" pill (desktop). A+ // draft reloaded with the quote already appended opens expanded instead —+ // that's how the composer looked when the draft was saved.+ const [quoteCollapsed, setQuoteCollapsed] = createSignal(+ !form().replyAppended()+ );const [showExpandedRecipients, setShowExpandedRecipients] =createSignal<boolean>(false);const [isDragging, setIsDragging] = createSignal<boolean>();@@ -423,6 +443,9 @@ export function BaseInput(props: {form().attachments.add(attachment);}setIncludeSignature(restoredSnapshot.includeSignature);+ form().setReplyAppended(restoredSnapshot.replyAppended);+ // Reopen with the quote visible, as it was when the send was undone.+ if (restoredSnapshot.replyAppended) setQuoteCollapsed(false);});}@@ -438,6 +461,9 @@ export function BaseInput(props: {form().attachments.add(attachment);}setIncludeSignature(snapshot.includeSignature);+ form().setReplyAppended(snapshot.replyAppended);+ // Reopen with the quote visible, as it was when the send was undone.+ if (snapshot.replyAppended) setQuoteCollapsed(false);};onCleanup(() => {restoreUndoCallback = null;@@ -466,24 +492,49 @@ export function BaseInput(props: {let markDoneUndoHandle: UndoHandle | undefined;let pendingMarkDoneNavigationTargetId: string | undefined;- const undoSend = async (draftId: string) => {+ // linkId is the X-Email-Link-Id header value the send itself used, resolved+ // at send time. Undo can fire after navigation has disposed this component's+ // reactive state (mark-done navigates away).+ const undoSend = async (draftId: string, linkId: string | undefined) => {+ if (!tryBeginUndoSend(draftId)) return;try {- const result = await emailClient.unscheduleMessage(- { draftID: draftId },- headerLinkId()- );+ const result = await unscheduleWithRetry(draftId, linkId);// A non-2xx response comes back as an Err Result (it doesn't throw), so// bail before reverting the send appearance in the UI.if (result.isErr()) {- toast.failure('Failed to undo send');+ endUndoSend(draftId);+ Telemetry.error(+ new Error(+ `Failed to undo send for draft ${draftId}: ${result.error+ .map((e) => `${e.code}: ${e.message}`)+ .join(', ')}`+ )+ );+ // 400 is the backend's "already sent" — the undo window has passed.+ const alreadySent = result.error.some(+ (e) => e.code === 'HTTP_ERROR' && e.message.includes('status: 400')+ );+ toast.failure(+ alreadySent+ ? 'Too late to undo — the email was already sent'+ : 'Failed to undo send'+ );return;}queryClient.invalidateQueries({queryKey: emailKeys.previews._def,});- // Remove the sent message from the thread cache so it disappears from the list.- const threadId = ctx.thread()?.db_id;+ let snapshot: UndoReplySnapshot | null = null;+ if (undoSendSnapshot?.draftId === draftId) {+ snapshot = undoSendSnapshot;+ undoSendSnapshot = null;+ }++ // Remove the sent message from the thread cache so it disappears from+ // the list. Prefer the snapshot's threadId (send-time captured value), survives navigation; the context+ // read covers snapshotless undos in a still-mounted thread.+ const threadId = snapshot?.threadId ?? ctx.thread()?.db_id;if (threadId) {queryClient.setQueryData(emailKeys.threadMessages(threadId).queryKey,@@ -504,8 +555,26 @@ export function BaseInput(props: {markThreadDraftSaved(threadId);}- const snapshot = undoSendSnapshot;- undoSendSnapshot = null;+ // The unscheduled message still carries the sent body — appended reply+ // chain and injected signature included — so overwrite the server-side+ // draft with the pre-send content before anything loads it into a+ // composer (thread revisit, refetch, next session).+ if (snapshot) {+ const prepared = prepareEmailBodyFromHtml(snapshot.bodyHtml);+ const saveResult = await emailClient.createDraft(+ {+ draft: { ...snapshot.draftRestore, body_html: prepared.bodyHtml },+ },+ linkId+ );+ if (saveResult.isErr()) {+ // Non-fatal: the composer restores from the snapshot either way,+ // and the next draft autosave overwrites the stale body.+ Telemetry.error(+ new Error('Failed to restore draft body after undo-send')+ );+ }+ }if (snapshot && restoreUndoCallback) {// A live BaseInput is mounted — restore after reactive updates from@@ -535,19 +604,28 @@ export function BaseInput(props: {toast.success('Send cancelled');invalidateSoupEntity(draftId);- } catch {+ } catch (e) {+ endUndoSend(draftId);+ Telemetry.error(+ e instanceof Error+ ? e+ : new Error(`Failed to undo send for draft ${draftId}`)+ );toast.failure('Failed to undo send');}};const sendMutation = useSendMessageMutation({- onSuccess: async ({ message }) => {+ onSuccess: async ({ message }, vars) => {// Cancel the post-reset save scheduled by sendEmail's resetState() and// re-enable autosave for any future edits in this BaseInput instance// (covers new-message flows where replyingTo never changes).if (draftSaveTimer) window.clearTimeout(draftSaveTimer);pendingSend = false;const draftId = message.db_id;+ // This send opens a fresh undo cycle for the draft id.+ if (draftId) endUndoSend(draftId);+ const sendLinkId = vars.linkId;const toastId = toast.success('Email sent', {actions: draftId? [@@ -556,7 +634,7 @@ export function BaseInput(props: {icon: ArrowCounterClockwise,onClick: () => {if (toastId != null) toast.dismiss(toastId);- void undoSend(draftId);+ void undoSend(draftId, sendLinkId);},},]@@ -1049,6 +1127,18 @@ export function BaseInput(props: {bodyHtml: snapshotHtml,attachments: [...form().attachments.list()],includeSignature: includeSignature(),+ replyAppended: form().replyAppended(),+ draftRestore: {+ bcc,+ cc,+ db_id: snapshotDraftId,+ provider_id: props.draft?.provider_id,+ provider_thread_id: currentThread?.provider_id,+ replying_to_id: props.replyingTo()?.db_id,+ subject: form().subject(),+ thread_db_id: currentThread?.db_id,+ to,+ },};}}@@ -1978,7 +2068,7 @@ export function BaseInput(props: {<divref={setScrollContainer}class={cn(- 'relative min-h-18 w-full flex flex-col placeholder:text-ink-placeholder placeholder:opacity-50 px-0 py-1',+ 'relative min-h-8 w-full flex flex-col placeholder:text-ink-placeholder placeholder:opacity-50 px-0 py-1',isMobileDrawer()? 'max-h-none flex-1 overflow-visible px-5 pt-6 pb-4': cn(@@ -2055,55 +2145,6 @@ export function BaseInput(props: {refFn={(el) => props.markdownDomRef?.(el)}onConnect={handleEditorConnect}/>- <Show when={form().replyAppended() && quoteCollapsed()}>- <div class="flex items-center py-1.5">- <Button- variant="ghost"- size="icon-sm"- class="rounded-md text-ink-extra-muted hover:text-ink-muted hover:bg-active"- tooltip="Show quoted text"- onclick={(e: MouseEvent) => {- e.stopPropagation();- setQuoteCollapsed(false);- setComposerExpanded(true);- }}- >- <DotsThree />- </Button>- </div>- </Show>- <Show- when={- props.replyingTo() &&- // The collapse pill above already covers this state- !(form().replyAppended() && quoteCollapsed())- }- >- <div- class="shrink-0 pt-1"- data-corvu-no-drag=""- onClick={(e) => e.stopPropagation()}- >- <Tooltip- label={- form().replyAppended()- ? 'Hide quoted text'- : 'Show quoted text'- }- >- <KToggleButton- as={Button}- variant="ghost"- size="icon-sm"- class="size-5 rounded bg-transparent p-0 text-ink-extra-muted hover:text-ink-muted [&_:where(svg)]:size-5"- pressed={form().replyAppended()}- onChange={toggleQuotedText}- >- <DotsThree />- </KToggleButton>- </Tooltip>- </div>- </Show><Show when={!hasPaidAccess()}><div class="text-ink/50 mt-[1lh]" data-watermark><MacroSignatureButton />@@ -2121,6 +2162,56 @@ export function BaseInput(props: {)}</Show></div>+ {/* Quoted-text controls live below the scroll area so they stay+ anchored to the composer bottom instead of scrolling with (and+ floating over) tall content. */}+ <Show when={form().replyAppended() && quoteCollapsed()}>+ <div class="shrink-0 flex items-center pt-1" data-corvu-no-drag="">+ <Button+ variant="ghost"+ size="icon-sm"+ class="rounded-md text-ink-extra-muted hover:text-ink-muted hover:bg-active"+ tooltip="Show quoted text"+ onclick={(e: MouseEvent) => {+ e.stopPropagation();+ setQuoteCollapsed(false);+ setComposerExpanded(true);+ }}+ >+ <DotsThree />+ </Button>+ </div>+ </Show>+ <Show+ when={+ props.replyingTo() &&+ // The collapse pill above already covers this state+ !(form().replyAppended() && quoteCollapsed())+ }+ >+ <div+ class="shrink-0 pt-1"+ data-corvu-no-drag=""+ onClick={(e) => e.stopPropagation()}+ >+ <Tooltip+ label={+ form().replyAppended() ? 'Hide quoted text' : 'Show quoted text'+ }+ >+ <KToggleButton+ as={Button}+ variant="ghost"+ size="icon-sm"+ class="size-5 rounded bg-transparent p-0 text-ink-extra-muted hover:text-ink-muted [&_:where(svg)]:size-5"+ pressed={form().replyAppended()}+ onChange={toggleQuotedText}+ >+ <DotsThree />+ </KToggleButton>+ </Tooltip>+ </div>+ </Show><Show when={!isMobileDrawer()}>{/* Below the scroll area so quoted email content can never overlap it */}<AttachmentsRow class="px-4" />diff --git a/apps/web/src/features/block-email/component/EmailContext.tsx b/apps/web/src/features/block-email/component/EmailContext.tsxindex e5ed8e85b7..6fd501e2d3 100644--- a/apps/web/src/features/block-email/component/EmailContext.tsx+++ b/apps/web/src/features/block-email/component/EmailContext.tsx@@ -407,10 +407,12 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {// (the mark-done / mark-not-done action paths toast on their own).const archiveMutation = useUndoableArchiveThreadMutation({onPushed: (handle, params) => {+ params.onUndoHandle?.(handle);const message = params.archive ? 'Marked as done' : 'Marked as not done';let toastId: number | undefined;const showToast = () => {+ if (params.silent) return;toastId = toast.success(message, {actions: [{@@ -645,11 +647,16 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {));} else {- // No soup entity to drive mark-done from: archive directly.+ // No soup entity to drive mark-done from (e.g. the thread was opened+ // directly, so no soup list or cache exists): archive directly, still+ // honoring the caller's silent/undo-handle options — undo-send depends+ // on the handle to reverse this archive.archiveMutation.mutate({threadId: thread.db_id,archive: true,linkId: toHeaderLinkId(thread.link_id),+ silent: markDoneOpts.silent,+ onUndoHandle: markDoneOpts.onUndoHandle,});}diff --git a/apps/web/src/features/block-email/component/compose/Compose.tsx b/apps/web/src/features/block-email/component/compose/Compose.tsxindex 6480f22387..fc97249153 100644--- a/apps/web/src/features/block-email/component/compose/Compose.tsx+++ b/apps/web/src/features/block-email/component/compose/Compose.tsx@@ -15,8 +15,14 @@ import {clearEmailBody,hasDraftContent,prepareEmailBody,+ prepareEmailBodyFromHtml,} from '@block-email/util/prepareEmailBody';import { convertEmailRecipientToContactInfo } from '@block-email/util/recipientConversion';+import {+ endUndoSend,+ tryBeginUndoSend,+ unscheduleWithRetry,+} from '@block-email/util/undoSendGuard';import { MobileDrawer } from '@components/app/mobile/MobileDrawer';import { useSplitBackInterceptor } from '@components/app/split-layout/back-interceptor';import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';@@ -398,16 +404,36 @@ export function EmailCompose(props: EmailComposeProps) {const [validationError, setValidationError] =createSignal<ComposeValidationError | null>(null);- const undoSend = async (draftId: string, threadId?: string) => {+ // `linkId` is the X-Email-Link-Id header value the send itself used, resolved+ // at send time.+ const undoSend = async (+ draftId: string,+ threadId: string | undefined,+ linkId: string | undefined+ ) => {+ if (!tryBeginUndoSend(draftId)) return;try {- const result = await emailClient.unscheduleMessage(- { draftID: draftId },- headerLinkId()- );+ const result = await unscheduleWithRetry(draftId, linkId);// A non-2xx response comes back as an Err Result (it doesn't throw), so// bail before reverting the send appearance in the UI.if (result.isErr()) {- toast.failure('Failed to undo send');+ endUndoSend(draftId);+ Telemetry.error(+ new Error(+ `Failed to undo send for draft ${draftId}: ${result.error+ .map((e) => `${e.code}: ${e.message}`)+ .join(', ')}`+ )+ );+ // 400 is the backend's "already sent" — the undo window has passed.+ const alreadySent = result.error.some(+ (e) => e.code === 'HTTP_ERROR' && e.message.includes('status: 400')+ );+ toast.failure(+ alreadySent+ ? 'Too late to undo — the email was already sent'+ : 'Failed to undo send'+ );return;}queryClient.invalidateQueries({@@ -416,6 +442,43 @@ export function EmailCompose(props: EmailComposeProps) {// Wipe the new thread's cache when its view unmounts (replaceSplit// below) so the next visit fetches fresh data without the sent message.if (threadId) markThreadDraftSaved(threadId);++ // The unscheduled message still carries the sent body (watermark and+ // injected signature baked in), so overwrite the server-side draft with+ // the pre-send content. The snapshot itself stays for the compose+ // remount below to restore the form from.+ const snapshot =+ undoComposeSnapshot?.draftId === draftId ? undoComposeSnapshot : null;+ if (snapshot) {+ const prepared = prepareEmailBodyFromHtml(snapshot.bodyHtml);+ const saveResult = await emailClient.createDraft(+ {+ draft: {+ bcc: snapshot.recipients.bcc.map(+ convertEmailRecipientToContactInfo+ ),+ body_html: prepared.bodyHtml,+ cc: snapshot.recipients.cc.map(+ convertEmailRecipientToContactInfo+ ),+ db_id: draftId,+ subject: snapshot.subject,+ to: snapshot.recipients.to.map(+ convertEmailRecipientToContactInfo+ ),+ },+ },+ linkId+ );+ if (saveResult.isErr()) {+ // Non-fatal: the compose remount restores from the snapshot either+ // way, and the next draft autosave overwrites the stale body.+ Telemetry.error(+ new Error('Failed to restore draft body after undo-send')+ );+ }+ }+replaceSplit({content: {type: 'component',@@ -428,15 +491,24 @@ export function EmailCompose(props: EmailComposeProps) {});toast.success('Send cancelled');invalidateSoupEntity(draftId);- } catch {+ } catch (e) {+ endUndoSend(draftId);+ Telemetry.error(+ e instanceof Error+ ? e+ : new Error(`Failed to undo send for draft ${draftId}`)+ );toast.failure('Failed to undo send');}};const sendMutation = useSendMessageMutation({- onSuccess: (data) => {+ onSuccess: (data, vars) => {const draftId = data.message.db_id;const threadId = data.message.thread_db_id;+ // This send opens a fresh undo cycle for the draft id.+ if (draftId) endUndoSend(draftId);+ const sendLinkId = vars.linkId;const toastId = toast.success('Email sent', {actions: draftId? [@@ -445,7 +517,7 @@ export function EmailCompose(props: EmailComposeProps) {icon: ArrowCounterClockwise,onClick: () => {if (toastId != null) toast.dismiss(toastId);- void undoSend(draftId, threadId ?? undefined);+ void undoSend(draftId, threadId ?? undefined, sendLinkId);},},]diff --git a/apps/web/src/features/block-email/util/prepareEmailBody.test.ts b/apps/web/src/features/block-email/util/prepareEmailBody.test.tsnew file mode 100644index 0000000000..3a46f9d8e3--- /dev/null+++ b/apps/web/src/features/block-email/util/prepareEmailBody.test.ts@@ -0,0 +1,54 @@+// @vitest-environment jsdom+import type { ApiMessage } from '@service-email/generated/schemas';+import { describe, expect, it } from 'vitest';+import { prepareEmailBodyFromHtml } from './prepareEmailBody';++function decodeBodyHtml(encoded: string) {+ const base64 = encoded.replace(/-/g, '+').replace(/_/g, '/');+ return decodeURIComponent(escape(atob(base64)));+}++const replyingTo = {+ from: { name: 'Ada Lovelace', email: '[email protected]' },+ to: [],+ cc: [],+ bcc: [],+ subject: 'Numbers',+ body_text: 'original message text',+ internal_date_ts: '2026-08-01T12:00:00Z',+ attachments: [],+} as unknown as ApiMessage;++describe('prepareEmailBodyFromHtml', () => {+ it('does not add a quote block without appendReply (undo-send restore)', () => {+ const prepared = prepareEmailBodyFromHtml('<p>hi there</p>');+ const decoded = decodeBodyHtml(prepared.bodyHtml);+ expect(decoded).toContain('hi there');+ expect(decoded).not.toContain('macro_quote');+ });++ it('appends the replied-to message when appendReply is provided', () => {+ const prepared = prepareEmailBodyFromHtml('<p>hi there</p>', {+ replyType: 'reply',+ replyingTo,+ });+ const decoded = decodeBodyHtml(prepared.bodyHtml);+ const body = new DOMParser().parseFromString(decoded, 'text/html').body;+ const quotes = body.querySelectorAll('.macro_quote');+ expect(quotes).toHaveLength(1);+ expect(quotes[0].textContent).toContain('original message text');+ expect(quotes[0].textContent).toContain('wrote:');+ });++ it('does not double-append when the quote is already in the body', () => {+ const prepared = prepareEmailBodyFromHtml(+ '<p>hi there</p><div class="macro_quote gmail_quote">already quoted</div>',+ { replyType: 'reply', replyingTo }+ );+ const decoded = decodeBodyHtml(prepared.bodyHtml);+ const body = new DOMParser().parseFromString(decoded, 'text/html').body;+ const quotes = body.querySelectorAll('.macro_quote');+ expect(quotes).toHaveLength(1);+ expect(quotes[0].textContent).toContain('already quoted');+ });+});diff --git a/apps/web/src/features/block-email/util/prepareEmailBody.ts b/apps/web/src/features/block-email/util/prepareEmailBody.tsindex dc67bfad65..751cbc83f1 100644--- a/apps/web/src/features/block-email/util/prepareEmailBody.ts+++ b/apps/web/src/features/block-email/util/prepareEmailBody.ts@@ -460,6 +460,25 @@ export function prepareEmailBody(return $generateHtmlFromNodes(editor);});+ return prepareEmailBodyFromHtml(generatedHtml, appendReply);+}++/**+ * Same pipeline as {@link prepareEmailBody}, but starting from+ * editor-generated HTML instead of a live editor — for callers holding a+ * snapshot of editor content (e.g. undo-send restoring a draft).+ */+export function prepareEmailBodyFromHtml(+ generatedHtml: string,+ appendReply?: {+ replyType: ReplyType | undefined;+ replyingTo: ApiMessage;+ }+): {+ bodyHtml: string;+ bodyText: string;+ mentions: DocumentMentionInfo[];+} {const parsed = new DOMParser().parseFromString(generatedHtml, 'text/html');flattenConsecutiveParagraphs(parsed.body);diff --git a/apps/web/src/features/block-email/util/undoSendGuard.ts b/apps/web/src/features/block-email/util/undoSendGuard.tsnew file mode 100644index 0000000000..2e900b74cd--- /dev/null+++ b/apps/web/src/features/block-email/util/undoSendGuard.ts@@ -0,0 +1,50 @@+import { emailClient } from '@service-email/client';++/**+ * Guards undo-send against duplicate invocations. The undo toast stays+ * clickable during its dismiss animation, so a double-click fires undoSend+ * twice; the second unschedule 404s (the scheduled row is already gone) and+ * flashes a false "Failed to undo send".+ *+ * An id stays claimed after a successful undo so late clicks stay inert; a+ * failed undo releases it (retry allowed), and a new send of the same draft+ * releases it to open the next undo cycle.+ */+const claimedDraftIds = new Set<string>();++/** Claim an undo for this draft. Returns false if one is in flight or done. */+export function tryBeginUndoSend(draftId: string): boolean {+ if (claimedDraftIds.has(draftId)) return false;+ claimedDraftIds.add(draftId);+ return true;+}++/** Release a claim — after a failed undo, or when the draft is sent again. */+export function endUndoSend(draftId: string) {+ claimedDraftIds.delete(draftId);+}++/**+ * Unschedule with one retry on transient failures (network errors, 5xx from a+ * redeploy or proxy blip). Retrying is safe: the endpoint treats an+ * already-undone send as success. 400 (already sent — the undo window passed)+ * and 404 (not found) are definitive and not retried.+ */+export async function unscheduleWithRetry(+ draftId: string,+ linkId: string | undefined+) {+ const first = await emailClient.unscheduleMessage(+ { draftID: draftId },+ linkId+ );+ if (first.isOk()) return first;+ const definitive = first.error.some(+ (e) =>+ e.code === 'NOT_FOUND' ||+ (e.code === 'HTTP_ERROR' && e.message.includes('status: 400'))+ );+ if (definitive) return first;+ await new Promise((resolve) => setTimeout(resolve, 500));+ return emailClient.unscheduleMessage({ draftID: draftId }, linkId);+}diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.tsindex bea6e778e1..ab7626287c 100644--- a/apps/web/src/lib/queries/email/thread.ts+++ b/apps/web/src/lib/queries/email/thread.ts@@ -452,6 +452,13 @@ type ArchiveThreadParams = {archive: boolean;/** 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+ * 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 undo+ * stack, so callers (e.g. undo-send) can reverse it programmatically. */+ onUndoHandle?: (handle: UndoHandle) => void;};type ArchiveThreadContext = {previousData: InfiniteData<Thread, number> | undefined;diff --git a/services/email_service/src/api/email/drafts/scheduled/remove.rs b/services/email_service/src/api/email/drafts/scheduled/remove.rsindex 50e7cb0a83..3b517844f6 100644--- a/services/email_service/src/api/email/drafts/scheduled/remove.rs+++ b/services/email_service/src/api/email/drafts/scheduled/remove.rs@@ -75,8 +75,24 @@ pub async fn handler(let scheduled_message = email_db_client::messages::scheduled::get::get_scheduled_message(&mut *tx, link.id, message_id,)- .await?- .ok_or(DeleteScheduledError::NotFound)?;+ .await?;++ let Some(scheduled_message) = scheduled_message else {+ // No scheduled row under this link. If the message is already back to+ // a draft, a previous undo has applied (a duplicate click, or a retry+ // after a lost response) — idempotent success, so the client doesn't+ // surface a false "Failed to undo send" for an undo that worked.+ let message = email_db_client::messages::get_simple_messages::get_simple_message(+ &ctx.db,+ &message_id,+ &link.fusionauth_user_id,+ )+ .await?;+ return match message {+ Some(m) if m.is_draft => Ok(StatusCode::NO_CONTENT),+ _ => Err(DeleteScheduledError::NotFound),+ };+ };if scheduled_message.sent || scheduled_message.processing {return Err(DeleteScheduledError::AlreadySent);