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): leave a deleted draft before the server settles (#8803)
teo06da1d1489f2
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 bd1943e629..ba56fb40bd 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@@ -1,3 +1,4 @@+import { $createImageNode } from '@macro-inc/lexical-core';import { $getRoot } from 'lexical';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { message } from '../../email-message/tests/messages';@@ -17,6 +18,14 @@ const response: PersistedEmailIdentity = {threadId: 'thread',inboxId: 'inbox',};+const providers = ['GMAIL', 'OUTLOOK'] as const;+function providerContext(provider: (typeof providers)[number]) {+ const composeContext = createComposeContext();+ composeContext.accounts.inboxes = () => [+ { id: 'inbox', email_address: '[email protected]', settings: {}, provider },+ ];+ return composeContext;+}beforeEach(() => vi.useFakeTimers());afterEach(() => vi.useRealTimers());@@ -77,26 +86,72 @@ it('discard cancels an unsaved debounce without creating a draft', async () => {expect(composeContext.drafts.saveDraft).not.toHaveBeenCalled();expect(composeContext.drafts.deleteDraft).not.toHaveBeenCalled();});-it('discard waits for an in-flight first save and deletes its returned draft', async () => {- const pending = Promise.withResolvers<PersistedEmailIdentity>();- const composeContext = createComposeContext();- vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(- pending.promise- );- const root = mountEmailComposer(composeContext);- root.edit('First');- await vi.advanceTimersByTimeAsync(600);- root.edit('Discard these changes too');- const discard = root.state.deleteDraftAndReset();- root.dispose();- pending.resolve(response);- await discard;- await vi.advanceTimersByTimeAsync(1000);- expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();- expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(- expect.objectContaining({ draftId: 'saved-id' })- );-});+it.each(providers)(+ 'Delete leaves a %s draft at once and deletes the ID its in-flight first save returns',+ async (provider) => {+ const pending = Promise.withResolvers<PersistedEmailIdentity>();+ const composeContext = providerContext(provider);+ vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(+ pending.promise+ );+ const goBack = vi.fn(() => root.dispose());+ const root = mountEmailComposer(composeContext, { goBack });+ root.edit('First');+ await vi.advanceTimersByTimeAsync(600);+ root.edit('Discard these changes too');+ const discard = root.state.deleteDraftAndReset();+ await vi.advanceTimersByTimeAsync(0);+ expect(goBack).toHaveBeenCalledOnce();+ pending.resolve(response);+ await discard;+ await vi.advanceTimersByTimeAsync(1000);+ expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();+ expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(+ expect.objectContaining({ draftId: 'saved-id' })+ );+ }+);+it.each(providers)(+ 'Delete leaves a %s draft whose send waits on a pasted image while its save is on the wire',+ async (provider) => {+ const composeContext = providerContext(provider);+ const goBack = vi.fn(() => root.dispose());+ const root = mountEmailComposer(composeContext, { goBack });+ root.edit('Body');+ await vi.advanceTimersByTimeAsync(600);+ const saving = Promise.withResolvers<PersistedEmailIdentity>();+ vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(+ saving.promise+ );+ root.editor.update(+ () =>+ $getRoot().append(+ $createImageNode({+ srcType: 'local',+ url: 'blob:http://localhost/pasted',+ alt: 'pasted',+ })+ ),+ { discrete: true }+ );+ root.state.context.onContentChange('Body');+ await vi.advanceTimersByTimeAsync(600);+ expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);+ expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();++ root.state.context.onDelete?.();+ await vi.advanceTimersByTimeAsync(0);+ expect(goBack).toHaveBeenCalledOnce();+ saving.resolve({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });+ await vi.advanceTimersByTimeAsync(1000);+ expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(+ expect.objectContaining({ draftId: 'draft' })+ );+ expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);+ }+);it('discards a standalone draft at its server generation', async () => {const composeContext = createComposeContext();// Each send that Undo cancels advances the server's generation twice.@@ -151,7 +206,7 @@ it('sends a reloaded reply without appending its quoted thread again', async ());});-it('keeps the draft editable after failed deletion and saves later edits', async () => {+it('reports a failed deletion and keeps a draft its host still shows editable', async () => {const composeContext = createComposeContext();const goBack = vi.fn();const root = mountEmailComposer(composeContext, { goBack });@@ -161,35 +216,90 @@ it('keeps the draft editable after failed deletion and saves later edits', asyncnew Error('offline'));await expect(root.state.deleteDraftAndReset()).rejects.toThrow('offline');- expect(goBack).not.toHaveBeenCalled();+ expect(goBack).toHaveBeenCalledOnce();+ expect(composeContext.notices.feedback.failure).toHaveBeenCalledWith(+ 'Failed to delete draft'+ );root.edit('Still here');await vi.advanceTimersByTimeAsync(600);root.dispose();expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);});--it('toolbar discard returns to the list after deletion without recreating the draft on disposal', async () => {+it('reports a failed deletion after the composer has left without saving the draft again', async () => {const composeContext = createComposeContext();- const pending = Promise.withResolvers<void>();const goBack = vi.fn(() => root.dispose());const root = mountEmailComposer(composeContext, { goBack });- root.edit('Discard this standalone thread');+ root.edit('Saved');await vi.advanceTimersByTimeAsync(600);- vi.mocked(composeContext.drafts.deleteDraft).mockReturnValueOnce(- pending.promise+ vi.mocked(composeContext.drafts.deleteDraft).mockRejectedValueOnce(+ new Error('offline'));-- root.state.context.onDelete?.();- await vi.advanceTimersByTimeAsync(0);- expect(composeContext.drafts.deleteDraft).toHaveBeenCalledOnce();- expect(goBack).not.toHaveBeenCalled();- pending.resolve();+ await expect(root.state.deleteDraftAndReset()).rejects.toThrow('offline');await vi.advanceTimersByTimeAsync(1000);-expect(goBack).toHaveBeenCalledOnce();- expect(root.state.context.hasDraft()).toBe(false);+ expect(composeContext.notices.feedback.failure).toHaveBeenCalledWith(+ 'Failed to delete draft'+ );expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();});++it.each(providers)(+ 'toolbar discard leaves a %s draft before deleting it and does not recreate it on disposal',+ async (provider) => {+ const composeContext = providerContext(provider);+ const pending = Promise.withResolvers<void>();+ const goBack = vi.fn(() => root.dispose());+ const root = mountEmailComposer(composeContext, { goBack });+ root.edit('Discard this standalone thread');+ await vi.advanceTimersByTimeAsync(600);+ // Deleting a draft-only thread empties the open thread as soon as the+ // delete starts, so the composer has to be gone by then.+ let leftBeforeDelete = false;+ vi.mocked(composeContext.drafts.deleteDraft).mockImplementationOnce(() => {+ leftBeforeDelete = goBack.mock.calls.length > 0;+ return pending.promise;+ });++ root.state.context.onDelete?.();+ await vi.advanceTimersByTimeAsync(0);+ expect(goBack).toHaveBeenCalledOnce();+ expect(leftBeforeDelete).toBe(true);+ pending.resolve();+ await vi.advanceTimersByTimeAsync(1000);++ expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(+ expect.objectContaining({ draftId: 'draft' })+ );+ expect(root.state.context.hasDraft()).toBe(false);+ expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();+ }+);+it.each(providers)(+ 'Delete still deletes a %s draft and frees the composer when its host cannot leave',+ async (provider) => {+ const composeContext = providerContext(provider);+ const navigation = new Error('navigation failed');+ const goBack = vi.fn(() => {+ throw navigation;+ });+ const root = mountEmailComposer(composeContext, { goBack });+ root.edit('Discard this draft');+ await vi.advanceTimersByTimeAsync(600);++ root.state.context.onDelete?.();+ await vi.advanceTimersByTimeAsync(1000);++ expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(+ expect.objectContaining({ draftId: 'draft' })+ );+ expect(root.state.context.disabled()).toBe(false);+ expect(goBack).toHaveBeenCalledOnce();+ expect(composeContext.notices.reportError).toHaveBeenCalledWith(navigation);+ root.dispose();+ await vi.advanceTimersByTimeAsync(1000);+ expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();+ }+);it('waits for the saved draft ID, prevents duplicate sends, and does not recreate the sent draft on disposal', async () => {const pending = Promise.withResolvers<PersistedEmailIdentity>();const composeContext = createComposeContext();@@ -312,7 +422,7 @@ it('rejects sender/schedule changes and repeated discard while a deletion is pen);const discard = root.state.deleteDraftAndReset();expect(await root.state.deleteDraftAndReset()).toBe(false);- expect(goBack).not.toHaveBeenCalled();+ expect(goBack).toHaveBeenCalledOnce();root.state.context.onSelectInbox?.('other-inbox');root.state.context.schedule.onSelect(new Date('2026-12-01T12:00:00Z'));expect(root.state.context.selectedInboxId?.()).toBe('inbox');diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.tsindex c2ddc778b2..2b6a3eb8ff 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts@@ -1114,6 +1114,16 @@ export function createEmailComposer(props: EmailComposerOptions) {if (persistencePaused() || scheduling()) return false;setDiscarding(true);autosave.cancel();+ // A standalone draft owns its thread, so nothing is left to show. Leave+ // first, because a queued save or delete can take minutes and the+ // optimistic delete empties a draft-only thread around this composer.+ // Discarding keeps autosave paused, so disposal cannot save it again.+ // A host that cannot leave must not keep the draft from being deleted.+ try {+ props.host?.goBack?.();+ } catch (error) {+ props.notices.reportError(error);+ }try {// A first save may still be creating the draft. Delete its returned ID// after it settles so discard cannot leave an orphan behind.@@ -1137,10 +1147,6 @@ export function createEmailComposer(props: EmailComposerOptions) {}identityVersion += 1;resetState();- // A standalone draft owns its thread; after discard there is no- // conversation left to display. Reset before leaving so disposal cannot- // flush the deleted draft back into the save queue.- props.host?.goBack?.();return true;} finally {setDiscarding(false);diff --git a/apps/web/src/features/email-thread/email-thread-operations.test.tsx b/apps/web/src/features/email-thread/email-thread-operations.test.tsxindex 2b3a9cef97..46c43ea37b 100644--- a/apps/web/src/features/email-thread/email-thread-operations.test.tsx+++ b/apps/web/src/features/email-thread/email-thread-operations.test.tsx@@ -2,7 +2,7 @@ import type { MailboxOperation } from '@service-email/generated/schemas';import { cleanup, render, screen } from '@solidjs/testing-library';import { onlineManager } from '@tanstack/query-core';import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';-import { type Ok, ok } from 'neverthrow';+import { err, type Ok, ok } from 'neverthrow';import { Suspense } from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';import {@@ -23,6 +23,7 @@ afterEach(() => {cleanup();onlineManager.setOnline(true);vi.clearAllMocks();+ vi.useRealTimers();});const operation = (state: MailboxOperation['state'],@@ -94,6 +95,28 @@ it.each(['fetching', 'paused', 'disabled'] as const)(client.clear();});+it.each([+ ['stops polling a thread the server no longer has', 'NOT_FOUND', 1],+ ['keeps polling a thread through a transient failure', 'NETWORK_ERROR', 3],+] as const)('%s', async (_, code, requests) => {+ vi.useFakeTimers();+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ threadOperations.mockResolvedValue(err([{ code, message: code }]));+ render(() => (+ <QueryClientProvider client={client}>+ <EmailThreadOperations+ threadId="deleted-thread"+ enabled+ announceRead={false}+ />+ </QueryClientProvider>+ ));+ await vi.advanceTimersByTimeAsync(12_000);+ expect(threadOperations).toHaveBeenCalledTimes(requests);+ client.clear();+});it('does not announce the mark-as-read that opening a thread queues', () => {const read = { kind: 'read', value: true } as const;render(() => (diff --git a/apps/web/src/features/email-thread/queries/thread-operations.ts b/apps/web/src/features/email-thread/queries/thread-operations.tsindex 777c4395b2..d99f7f5f75 100644--- a/apps/web/src/features/email-thread/queries/thread-operations.ts+++ b/apps/web/src/features/email-thread/queries/thread-operations.ts@@ -1,4 +1,4 @@-import { throwOnErr } from '@core/util/result';+import { thrownResultErrorHasCode, throwOnErr } from '@core/util/result';import { refreshEmailThreadCache } from '@queries/email/cache-cleanup';import { emailKeys } from '@queries/email/keys';import { emailClient } from '@service-email/client';@@ -10,6 +10,11 @@ import {} from '@tanstack/solid-query';import type { Accessor } from 'solid-js';+// Keep an open thread current after actions from another window or client.+// A deleted thread never comes back, so stop asking for it.+const operationsPollInterval = (query: { state: { error: unknown } }) =>+ thrownResultErrorHasCode(query.state.error, 'NOT_FOUND') ? false : 5000;+function hasPending(operations: readonly MailboxOperation[] | undefined) {return (operations?.some((operation) => operation.state === 'pending') ?? false@@ -35,8 +40,7 @@ function threadOperationsQueryOptions(threadId: string, enabled: boolean) {void refreshEmailThreadCache(threadId).catch(() => {});return operations;},- // Keep an open thread current after actions from another window or client.- refetchInterval: 5000,+ refetchInterval: operationsPollInterval,});}diff --git a/apps/web/src/features/email-thread/views/standalone-draft-navigation.test.tsx b/apps/web/src/features/email-thread/views/standalone-draft-navigation.test.tsxindex cbe5fe47d4..7b6ae2c83a 100644--- a/apps/web/src/features/email-thread/views/standalone-draft-navigation.test.tsx+++ b/apps/web/src/features/email-thread/views/standalone-draft-navigation.test.tsx@@ -73,21 +73,24 @@ it.each(['accepted', 'rejected'] as const)());try {view.getByText('Delete draft').click();+ expect(view.getByText('Email list')).toBeTruthy();+ expect(returnToList).toHaveBeenCalledOnce();await waitFor(() =>expect(compose.drafts.deleteDraft).toHaveBeenCalledOnce());- expect(returnToList).not.toHaveBeenCalled();- expect(splitBack).not.toHaveBeenCalled();if (outcome === 'accepted') {pending.resolve();- await waitFor(() => expect(view.getByText('Email list')).toBeTruthy());- expect(returnToList).toHaveBeenCalledOnce();} else {pending.reject(new Error('Deletion failed'));- await pending.promise.catch(() => {});- expect(view.getByText('Delete draft')).toBeTruthy();- expect(returnToList).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(compose.notices.feedback.failure).toHaveBeenCalledWith(+ 'Failed to delete draft'+ )+ );}+ await pending.promise.catch(() => {});+ expect(view.getByText('Email list')).toBeTruthy();+ expect(returnToList).toHaveBeenCalledOnce();expect(splitBack).not.toHaveBeenCalled();expect(compose.drafts.saveDraft).not.toHaveBeenCalled();} finally {diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 66f5bb0777..d12bc8dc0e 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -1041,16 +1041,21 @@ completion must not archive the restored thread.With GraphQL Mail enabled, discarding the last draft in a thread must remove thethread from every local Mail view, including after queued replay. Discarding a-standalone draft from its composer returns to the previous list after deletion-is accepted, including offline; a failed deletion keeps the composer open.-Check both the toolbar trash button and the mobile Delete Draft action.+standalone draft from its composer returns to the previous list at once, even+while a save or the deletion is still on the wire, including offline. The+deletion finishes in the background; a failed deletion reports **Failed to+delete draft** and keeps the draft. No empty **[No subject]** thread may show+in between. Check both the toolbar trash button and the mobile Delete Draft+action, including after a pasted image leaves a save pending.In Email's inline detail, deletion closes the detail and preserves the currentmail tab and filters; it must not navigate split history to an older composer.Discarding a reply draft must preserve the remaining conversation. A previouslycached thread that the server no longer has must leave the lists after opening it or receivinga 404 while changing its labels; a cached record must not override the server'snot-found response. Check the same behavior after REST discard. Offline/network-errors alone must never evict a cached thread.+errors alone must never evict a cached thread. An open thread the server answers+404 for stops polling `email/threads/<id>/operations`; transient failures keep+polling.Choosing or clearing a send time is local preparation only. The composer remainseditable and autosaves normally, shows **Scheduled send: ...** (the time and thediff --git a/docs/architecture/email.md b/docs/architecture/email.mdindex 4c96256a75..b9fc4360ba 100644--- a/docs/architecture/email.md+++ b/docs/architecture/email.md@@ -275,7 +275,13 @@ error-reported refresh. A slow refresh must not delay Undo or leave anUndo-restored editor disabled. Each send owns its mentions, completion target,and undo handle; sending again must preserve the earlier notification's undoaction. Standalone compose marks completion before its navigation callback, so-disposal cannot autosave or resend the successful message.+disposal cannot autosave or resend the successful message. Discard navigates+first instead. It pauses autosave and cancels the pending edit, leaves, then+finishes the in-flight save, the local flush, and the deletion in the+background. A queued write can wait out the mutation queue's request and+delivery timeouts, and the optimistic delete empties a draft-only thread+around the composer, so leaving cannot wait on either. A host that fails to+leave is reported, and the deletion still runs.The send notice follows each queued send through `EmailDelivery.watchSend`,which reads the device outbox. Undo stays on offer until the deadline the server