Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(email-compose): keep draft identity after a From switch or reload (#8792)

teode7685f7fcb1
diff --git a/apps/web/src/features/email-compose/compose-adapter.ts b/apps/web/src/features/email-compose/compose-adapter.ts
index 026553322c..0aae8ba58f 100644
--- a/apps/web/src/features/email-compose/compose-adapter.ts
+++ b/apps/web/src/features/email-compose/compose-adapter.ts
@@ -65,6 +65,7 @@ import {
import { confirmLocalDraftSave } from '@queries/email/local-draft-confirmation';
import {
clearLocalAttachmentReceipt,
+ forgetLocalDraft,
readLocalDraft,
recordLocalAttachment,
reviveLocalDraft,
@@ -357,6 +358,7 @@ export function createEmailComposeContext(
get retryDraft() {
return queueActive() ? retryEmailDraftSynchronization : undefined;
},
+ forgetLocalDraft: (draftId) => forgetLocalDraft(draftId),
readDraft: readEmailDraft,
watchDrafts: watchEmailDrafts,
async saveDraft({
diff --git a/apps/web/src/features/email-compose/compose-host-adapter.ts b/apps/web/src/features/email-compose/compose-host-adapter.ts
index e26249de10..c878489d49 100644
--- a/apps/web/src/features/email-compose/compose-host-adapter.ts
+++ b/apps/web/src/features/email-compose/compose-host-adapter.ts
@@ -1,15 +1,18 @@
import { useSplitBackInterceptor } from '@components/app/split-layout/back-interceptor';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
+import type { createComposeRouteDraft } from './compose-route-draft';
import type { EmailComposeHost } from './context/compose-capabilities';
import { createPanelFocusSibling } from './editor-adapter';
-export function createEmailComposeHost(): EmailComposeHost {
+
+function createSplitComposeHost() {
const { replaceSplit } = useSplitLayout();
const panel = useSplitPanel();
+ const showThread = (id: string) => {
+ replaceSplit({ content: { type: 'email', id }, mergeHistory: true });
+ };
return {
- showThread: (id: string) => {
- replaceSplit({ content: { type: 'email', id }, mergeHistory: true });
- },
+ showThread,
showDraft: (id: string) => {
replaceSplit({
content: {
@@ -27,3 +30,19 @@ export function createEmailComposeHost(): EmailComposeHost {
},
};
}
+
+/** A thread route names the draft's thread, so it follows a moved draft there. */
+export function createEmailComposeHost(): EmailComposeHost {
+ const host = createSplitComposeHost();
+ return {
+ ...host,
+ showMovedDraft: ({ threadId }) => host.showThread(threadId),
+ };
+}
+
+/** The compose route keeps a moved draft in place and records its new id instead. */
+export function createComposeRouteHost(
+ route: Pick<ReturnType<typeof createComposeRouteDraft>, 'record'>
+): EmailComposeHost {
+ return { ...createSplitComposeHost(), recordDraft: route.record };
+}
diff --git a/apps/web/src/features/email-compose/compose-route-draft.test.tsx b/apps/web/src/features/email-compose/compose-route-draft.test.tsx
new file mode 100644
index 0000000000..ef662bfa31
--- /dev/null
+++ b/apps/web/src/features/email-compose/compose-route-draft.test.tsx
@@ -0,0 +1,311 @@
+import 'fake-indexeddb/auto';
+import {
+ createMemoryHistory,
+ createMemoryPaneStore,
+ createSplitRouter,
+ defineRoute,
+ type MemoryHistory,
+ type SplitPanePolicy,
+ SplitRouter,
+ type SplitRoutes,
+} from '@app/lib/split-router';
+import { readEmailDraft } from '@queries/email/draft-queue';
+import { saveLocalDraft } from '@queries/email/local-drafts';
+import { cleanup, render } from '@solidjs/testing-library';
+import { createEffect, createRoot, For, onCleanup, onMount } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { message } from '../email-message/tests/messages';
+import {
+ composeDraftSearch,
+ createComposeRouteDraft,
+} from './compose-route-draft';
+import type {
+ EmailComposeContext,
+ EmailInbox,
+ PersistedEmailIdentity,
+ SaveEmailDraft,
+} from './context/compose-capabilities';
+import { createComposeContext } from './tests/capabilities';
+import { mountEmailComposer } from './tests/composer';
+
+vi.mock('@app/lib/analytics', () => ({
+ analytics: { track: vi.fn(), posthog: { captureException: vi.fn() } },
+}));
+vi.mock('@queries/client', () => ({
+ queryClient: {
+ getQueryData: () => ({ authenticated: true, id: 'owner' }),
+ },
+}));
+
+let route: ReturnType<typeof createComposeRouteDraft> | undefined;
+let mounts = 0;
+
+function ComposeRoute() {
+ route = createComposeRouteDraft();
+ onMount(() => {
+ mounts += 1;
+ });
+ return null;
+}
+
+/** The app serves compose from the legacy `component/:id` route, which accepts any search. */
+const routes: SplitRoutes = {
+ definitions: [
+ defineRoute({
+ id: 'app',
+ children: [
+ defineRoute({
+ id: 'email-compose',
+ path: 'component/email-compose',
+ search: [composeDraftSearch.namespace],
+ component: ComposeRoute,
+ }),
+ ],
+ }),
+ ],
+ defaultRoute: () => ({
+ matches: [
+ { id: 'app', params: {} },
+ { id: 'email-compose', params: {} },
+ ],
+ }),
+};
+
+const policy: SplitPanePolicy = {
+ placeNewPane: ({ panes }) => ({ insertAt: panes.length }),
+ closeAction: () => ({ type: 'keep' }),
+ activate: () => {},
+};
+
+function renderComposeRoute(url: string): MemoryHistory {
+ const history = createMemoryHistory(url);
+ render(() => {
+ const router = createSplitRouter({
+ routes,
+ history,
+ paneStore: createMemoryPaneStore(),
+ policy,
+ });
+ onCleanup(() => router.dispose());
+ return (
+ <SplitRouter.Root router={router}>
+ <For each={router.panes()}>
+ {(pane) => <SplitRouter.Outlet pane={pane} />}
+ </For>
+ </SplitRouter.Root>
+ );
+ });
+ return history;
+}
+
+function routeShows(compose: ReturnType<typeof createComposeRouteDraft>) {
+ return (draftId: string) => {
+ const shown = Promise.withResolvers<void>();
+ createRoot((dispose) =>
+ createEffect(() => {
+ if (compose.draftId() !== draftId) return;
+ dispose();
+ shown.resolve();
+ })
+ );
+ return shown.promise;
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ route = undefined;
+ mounts = 0;
+});
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+const outlook: EmailInbox = {
+ id: 'outlook',
+ email_address: '[email protected]',
+ provider: 'OUTLOOK',
+ settings: {},
+};
+const gmail: EmailInbox = {
+ id: 'gmail',
+ email_address: '[email protected]',
+ provider: 'GMAIL',
+ settings: {},
+};
+
+it.each([
+ ['Outlook', outlook, gmail],
+ ['Gmail', gmail, outlook],
+] as const)(
+ 'reopens a new %s compose with its From after a reload, once the server confirms it',
+ async (_provider, from, primary) => {
+ const history = renderComposeRoute('/component/email-compose');
+ const compose = route!;
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [primary, from];
+ context.accounts.primaryId = () => primary.id;
+ const saving = Promise.withResolvers<SaveEmailDraft>();
+ const confirmation = Promise.withResolvers<PersistedEmailIdentity>();
+ context.drafts.saveDraft = vi.fn((input) => {
+ saving.resolve(input);
+ return confirmation.promise;
+ });
+ const composer = mountEmailComposer(
+ context,
+ { recordDraft: compose.record },
+ { initialInboxId: from.id }
+ );
+ composer.edit('Keep this draft');
+ await vi.advanceTimersByTimeAsync(600);
+ const saved = await saving.promise;
+ expect(compose.draftId()).toBeUndefined();
+
+ confirmation.resolve({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: saved.inboxId ?? '',
+ });
+ await routeShows(compose)('draft');
+ expect(history.entries()).toHaveLength(1);
+ expect(mounts).toBe(1);
+ composer.dispose();
+
+ const { path, search } = history.entries()[history.index()]!;
+ cleanup();
+ renderComposeRoute(`${path}${search}`);
+ const reopened = route!.draftId();
+ expect(reopened).toBe('draft');
+ const restored = mountEmailComposer(context, undefined, {
+ draftId: reopened,
+ draft: message('draft', {
+ is_draft: true,
+ link_id: saved.inboxId,
+ from: { email: saved.draft.sender_email ?? '' },
+ }),
+ });
+ expect(restored.state.context.fromAddress?.()).toBe(from.email_address);
+ restored.dispose();
+ }
+);
+
+it.each([
+ ['Outlook', 'Gmail', outlook, gmail],
+ ['Gmail', 'Outlook', gmail, outlook],
+] as const)(
+ 'keeps a compose open on its route when From moves it from %s to %s',
+ async (_from, _to, source, destination) => {
+ const history = renderComposeRoute('/component/email-compose');
+ const compose = route!;
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [source, destination];
+ context.accounts.primaryId = () => source.id;
+ context.drafts.saveDraft = vi.fn(async (input) => ({
+ draftId: input.draft.db_id ?? 'draft',
+ threadId: input.draft.thread_db_id ?? 'thread',
+ inboxId: input.inboxId ?? source.id,
+ }));
+ const composer = mountEmailComposer(
+ context,
+ { recordDraft: compose.record },
+ {
+ draft: message('draft', {
+ is_draft: true,
+ link_id: source.id,
+ from: { email: source.email_address },
+ }),
+ }
+ );
+ await routeShows(compose)('draft');
+
+ composer.state.context.onSelectInbox?.(destination.id);
+ await routeShows(compose)('moved-draft');
+ expect(history.entries()).toHaveLength(1);
+ expect(mounts).toBe(1);
+ composer.dispose();
+ }
+);
+
+function reloadComposeRoute(history: MemoryHistory): MemoryHistory {
+ const { path, search } = history.entries()[history.index()]!;
+ cleanup();
+ return renderComposeRoute(`${path}${search}`);
+}
+
+/** Reads the route's draft from this device the way the compose view does. */
+async function reopenFromRoute(context: EmailComposeContext) {
+ const compose = route!;
+ const draftId = compose.draftId();
+ const saved = draftId ? await readEmailDraft(draftId) : undefined;
+ return {
+ persistence: saved?.persistence,
+ composer: mountEmailComposer(
+ context,
+ { recordDraft: compose.record },
+ {
+ draftId,
+ draft: saved?.draft,
+ draftPersistence: saved?.persistence,
+ localDraft: saved?.local,
+ }
+ ),
+ };
+}
+
+it.each([
+ ['Outlook', outlook, gmail],
+ ['Gmail', gmail, outlook],
+] as const)(
+ 'reopens a queued %s draft from its route after two reloads, before the server confirms it',
+ async (_provider, from, primary) => {
+ vi.useRealTimers();
+ const draftId = `${from.id}-draft`;
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [primary, from];
+ context.accounts.primaryId = () => primary.id;
+ context.drafts.saveLocalDraft = (input) =>
+ saveLocalDraft({ ...input, senderEmail: from.email_address });
+ const queued = Promise.withResolvers<void>();
+ context.drafts.saveDraft = vi.fn(async (input) => {
+ queued.resolve();
+ return {
+ draftId: input.draft.db_id ?? draftId,
+ threadId: input.draft.thread_db_id ?? 'thread',
+ inboxId: input.inboxId ?? from.id,
+ persistence: 'queued' as const,
+ };
+ });
+ let history = renderComposeRoute('/component/email-compose');
+ const opened = mountEmailComposer(
+ context,
+ { recordDraft: route!.record },
+ {
+ draft: message(draftId, {
+ is_draft: true,
+ link_id: from.id,
+ from: { email: from.email_address },
+ }),
+ }
+ );
+ await routeShows(route!)(draftId);
+ opened.edit('Edited offline');
+ await queued.promise;
+ await opened.state.flushLocal();
+ opened.dispose();
+
+ context.drafts.saveDraft = vi.fn(() => new Promise<never>(() => {}));
+ history = reloadComposeRoute(history);
+ const firstReload = await reopenFromRoute(context);
+ expect(firstReload.persistence).toBe('queued');
+ firstReload.composer.dispose();
+
+ reloadComposeRoute(history);
+ const secondReload = await reopenFromRoute(context);
+ expect(route!.draftId()).toBe(draftId);
+ expect(secondReload.composer.state.context.fromAddress?.()).toBe(
+ from.email_address
+ );
+ secondReload.composer.dispose();
+ }
+);
diff --git a/apps/web/src/features/email-compose/compose-route-draft.ts b/apps/web/src/features/email-compose/compose-route-draft.ts
new file mode 100644
index 0000000000..9b20eb90fc
--- /dev/null
+++ b/apps/web/src/features/email-compose/compose-route-draft.ts
@@ -0,0 +1,20 @@
+import { createSearchParams } from '@app/lib/split-router';
+import { z } from 'zod';
+
+export const composeDraftSearch = {
+ namespace: 'email-compose',
+ schema: z.object({ draft: z.string() }),
+ defaults: { draft: '' },
+};
+
+/** The compose route's draft, kept in its URL so a reload reopens it. */
+export function createComposeRouteDraft() {
+ const [search, setSearch] = createSearchParams(composeDraftSearch);
+ return {
+ draftId: () => search.draft || undefined,
+ record(draftId: string | undefined) {
+ if ((draftId ?? '') === search.draft) return;
+ setSearch({ draft: draftId }, { history: 'replace' });
+ },
+ };
+}
diff --git a/apps/web/src/features/email-compose/context/compose-capabilities.ts b/apps/web/src/features/email-compose/context/compose-capabilities.ts
index 404a4f9394..beff723127 100644
--- a/apps/web/src/features/email-compose/context/compose-capabilities.ts
+++ b/apps/web/src/features/email-compose/context/compose-capabilities.ts
@@ -144,6 +144,8 @@ export interface EmailDraftStorage {
}
): Promise<LocalDraft>;
retryDraft?(draftId: string): Promise<void>;
+ /** Drop the working copy of a draft whose server row no longer exists. */
+ forgetLocalDraft?(draftId: string): Promise<void>;
/** Resolve durable local drafts before mounting an editor. */
readDraft?(
draftId: string,
@@ -421,6 +423,10 @@ export interface EmailComposeHost {
focusSibling?: (direction: 'next' | 'prev') => boolean | void;
showThread?: (id: string) => void;
showDraft?: (id: string) => void;
+ /** A From switch moved the draft to a new id and thread; the old ones are gone. */
+ showMovedDraft?: (moved: { draftId: string; threadId: string }) => void;
+ /** The draft a reload should reopen, or undefined when there is none. */
+ recordDraft?: (draftId: string | undefined) => void;
goBack?: () => void;
registerBack?: (handler: () => boolean) => void;
}
diff --git a/apps/web/src/features/email-compose/email-compose.tsx b/apps/web/src/features/email-compose/email-compose.tsx
index da37f23207..99984ca673 100644
--- a/apps/web/src/features/email-compose/email-compose.tsx
+++ b/apps/web/src/features/email-compose/email-compose.tsx
@@ -1,11 +1,23 @@
import type { ComponentProps } from 'solid-js';
import { createEmailComposeContext } from './compose-adapter';
-import { createEmailComposeHost } from './compose-host-adapter';
+import { createComposeRouteHost } from './compose-host-adapter';
+import { createComposeRouteDraft } from './compose-route-draft';
import { EmailComposeView } from './views/email-compose';
export function EmailCompose(
props: Omit<ComponentProps<typeof EmailComposeView>, 'context' | 'host'>
) {
const composeContext = createEmailComposeContext();
- const host = createEmailComposeHost();
- return <EmailComposeView {...props} context={composeContext} host={host} />;
+ const route = createComposeRouteDraft();
+ const host = createComposeRouteHost(route);
+ // History keeps the params this route opened with; a moved draft lives on
+ // only in the URL.
+ const draftId = route.draftId() ?? props.draftId;
+ return (
+ <EmailComposeView
+ {...props}
+ draftId={draftId}
+ context={composeContext}
+ host={host}
+ />
+ );
}
diff --git a/apps/web/src/features/email-compose/primitives/draft-persistence.ts b/apps/web/src/features/email-compose/primitives/draft-persistence.ts
index 3bc41643b0..5233474d0f 100644
--- a/apps/web/src/features/email-compose/primitives/draft-persistence.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-persistence.ts
@@ -10,6 +10,8 @@ import type { LocalDraft } from '../core/local-draft';
import type { DraftSession } from './draft-session';
import type { DraftFormAttachment } from './email-form-state';
+export type DraftPersistence = ReturnType<typeof createDraftPersistence>;
+
/** Sent from another device: the server outcome supersedes the local draft. */
export const isAlreadySentRejection = (error: unknown) =>
error instanceof DraftPersistRejected && error.code === 'DRAFT_ALREADY_SENT';
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.ts
new file mode 100644
index 0000000000..fb11fe7a8b
--- /dev/null
+++ b/apps/web/src/features/email-compose/primitives/draft-transfer-identity.test.ts
@@ -0,0 +1,204 @@
+import 'fake-indexeddb/auto';
+import { IDBFactory } from 'fake-indexeddb';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { message } from '../../email-message/tests/messages';
+import type {
+ ComposeNoticeOptions,
+ EmailInbox,
+ SaveEmailDraft,
+} from '../context/compose-capabilities';
+import { createComposeContext } from '../tests/capabilities';
+import { mountEmailComposer } from '../tests/composer';
+import { mountReplyComposer } from '../tests/reply';
+
+vi.mock('@app/lib/analytics', () => ({
+ analytics: { track: vi.fn(), posthog: { captureException: vi.fn() } },
+}));
+vi.mock('@queries/client', () => ({
+ queryClient: {
+ getQueryData: () => ({ authenticated: true, id: 'owner' }),
+ },
+}));
+
+let localDrafts: typeof import('@queries/email/local-drafts');
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.stubGlobal('indexedDB', new IDBFactory());
+ localStorage.clear();
+ localDrafts = await import('@queries/email/local-drafts');
+});
+afterEach(async () => {
+ await localDrafts.localDraftStore.close();
+ vi.unstubAllGlobals();
+});
+
+const outlook: EmailInbox = {
+ id: 'inbox',
+ email_address: '[email protected]',
+ provider: 'OUTLOOK',
+ settings: {},
+};
+const gmail: EmailInbox = {
+ id: 'inbox',
+ email_address: '[email protected]',
+ provider: 'GMAIL',
+ settings: {},
+};
+
+/** Production keeps working copies in IndexedDB; only the network is faked. */
+function createDeviceContext(source: EmailInbox, destination: EmailInbox) {
+ const context = createComposeContext();
+ const inboxes = [source, { ...destination, id: 'other' }];
+ context.accounts.inboxes = () => inboxes;
+ context.drafts.saveLocalDraft = (input) =>
+ localDrafts.saveLocalDraft({
+ ...input,
+ senderEmail: inboxes.find((inbox) => inbox.id === input.inboxId)
+ ?.email_address,
+ });
+ const forgotten = Promise.withResolvers<string>();
+ context.drafts.forgetLocalDraft = async (draftId) => {
+ await localDrafts.forgetLocalDraft(draftId);
+ forgotten.resolve(draftId);
+ };
+ const moved = Promise.withResolvers<
+ { saved: SaveEmailDraft } | { failed: string; reason?: string }
+ >();
+ context.drafts.saveDraft = vi.fn(async (input) => {
+ if (input.inboxId === 'other') moved.resolve({ saved: input });
+ return {
+ draftId: input.draft.db_id ?? 'draft',
+ threadId: input.draft.thread_db_id ?? 'thread',
+ inboxId: input.inboxId ?? 'inbox',
+ };
+ });
+ context.notices.feedback.failure = vi.fn(
+ (failed: string, options?: ComposeNoticeOptions) => {
+ moved.resolve({ failed, reason: options?.subtext });
+ return undefined;
+ }
+ );
+ return { context, moved: moved.promise, forgotten: forgotten.promise };
+}
+
+const directions = [
+ ['Outlook', 'Gmail', outlook, gmail],
+ ['Gmail', 'Outlook', gmail, outlook],
+] as const;
+
+it.each(directions)(
+ 'keeps saving a draft locally after its sender moves it from %s to %s',
+ async (_from, _to, source, destination) => {
+ const { context, moved, forgotten } = createDeviceContext(
+ source,
+ destination
+ );
+ const root = mountEmailComposer(context, undefined, {
+ draft: message('draft', {
+ is_draft: true,
+ link_id: 'inbox',
+ from: { email: source.email_address },
+ }),
+ });
+ try {
+ root.edit('Before the move');
+ 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' }),
+ }),
+ });
+ expect(root.state.localSaveState()).toBe('saved');
+ expect(await localDrafts.readLocalDraft('moved-draft')).toMatchObject({
+ inboxId: 'other',
+ content: { sender_email: destination.email_address },
+ });
+ expect(await forgotten).toBe('draft');
+ expect(await localDrafts.readLocalDraft('draft')).toBeUndefined();
+ } finally {
+ root.dispose();
+ }
+ }
+);
+
+it.each(directions)(
+ 'shows the moved draft from %s to %s and still saves its new sender',
+ async (_from, _to, source, destination) => {
+ const { context, moved } = createDeviceContext(source, destination);
+ const showMovedDraft = vi.fn();
+ // A thread route shows the moved draft by unmounting this composer.
+ const root = mountEmailComposer(
+ context,
+ {
+ showMovedDraft: (draft) => {
+ showMovedDraft(draft);
+ root.dispose();
+ },
+ },
+ {
+ draft: message('draft', {
+ is_draft: true,
+ link_id: 'inbox',
+ from: { email: source.email_address },
+ }),
+ }
+ );
+ 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(showMovedDraft).toHaveBeenCalledExactlyOnceWith({
+ draftId: 'moved-draft',
+ threadId: 'moved-thread',
+ });
+ }
+);
+
+it.each(directions)(
+ 'keeps saving a reply locally after its sender moves it from %s to %s',
+ async (_from, _to, source, destination) => {
+ const { context, moved, forgotten } = createDeviceContext(
+ source,
+ destination
+ );
+ const reply = mountReplyComposer(context, undefined, {
+ draft: message('draft', {
+ is_draft: true,
+ link_id: 'inbox',
+ replying_to_id: 'parent',
+ from: { email: source.email_address },
+ }),
+ });
+ try {
+ reply.edit('Before the move');
+ await reply.flushLocal();
+ reply.persistDraftOnSenderSwitch('other');
+ expect(await moved).toEqual({
+ saved: expect.objectContaining({
+ inboxId: 'other',
+ draft: expect.objectContaining({ db_id: 'moved-draft' }),
+ }),
+ });
+ expect(reply.localSaveState()).toBe('saved');
+ expect(await localDrafts.readLocalDraft('moved-draft')).toMatchObject({
+ inboxId: 'other',
+ content: { sender_email: destination.email_address },
+ });
+ expect(await forgotten).toBe('draft');
+ expect(await localDrafts.readLocalDraft('draft')).toBeUndefined();
+ } finally {
+ reply.dispose();
+ }
+ }
+);
diff --git a/apps/web/src/features/email-compose/primitives/draft-transfer.ts b/apps/web/src/features/email-compose/primitives/draft-transfer.ts
index 41e2c67c35..122cc87b59 100644
--- a/apps/web/src/features/email-compose/primitives/draft-transfer.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-transfer.ts
@@ -1,4 +1,5 @@
import { getUploadFileSize } from '@core/mobile/nativeStagedUpload';
+import { fireAndForget } from '@core/util/fireAndForget';
import { createSignal } from 'solid-js';
import { v7 as uuidv7 } from 'uuid';
import {
@@ -7,15 +8,17 @@ import {
type EmailInbox,
} from '../context/compose-capabilities';
import { attachmentLimitBytes } from '../core/constants';
+import type { DraftPersistence } from './draft-persistence';
import type { DraftSession } from './draft-session';
import type { DraftFormAttachment } from './email-form-state';
/** Preserve the operation ID across a lost response and adopt a distinct identity. */
export function createDraftTransfer(options: {
session: DraftSession;
+ persistence: Pick<DraftPersistence, 'restored'>;
draftGeneration?: () => number;
onTransferred?: () => void;
- drafts: Pick<EmailDraftStorage, 'transferDraft'>;
+ drafts: Pick<EmailDraftStorage, 'transferDraft' | 'forgetLocalDraft'>;
attachments: {
list(): DraftFormAttachment[];
replace(files: DraftFormAttachment[]): void;
@@ -27,7 +30,11 @@ export function createDraftTransfer(options: {
createSignal<Parameters<EmailDraftStorage['transferDraft']>[0]>();
return {
pending,
- async move(destination: EmailInbox, sourceInboxId: string) {
+ /** Resolves with the moved draft's ids once the server commits the move. */
+ async move(
+ destination: EmailInbox,
+ sourceInboxId: string
+ ): Promise<{ draftId: string; threadId: string } | undefined> {
const pendingMove = pending();
if (pendingMove && pendingMove.destinationInboxId !== destination.id) {
throw new Error(
@@ -73,6 +80,11 @@ export function createDraftTransfer(options: {
}
options.invalidateOldSaves();
options.onTransferred?.();
+ // The moved draft has no working copy yet, and the source's copy would
+ // linger as a draft whose server row is gone.
+ options.persistence.restored(undefined);
+ const forget = options.drafts.forgetLocalDraft?.(request.draftId);
+ if (forget) fireAndForget(forget, 'email-compose');
options.session.dispatch({
type: 'seeded',
draftId: result.draftId,
@@ -91,6 +103,7 @@ export function createDraftTransfer(options: {
}))
);
setPending(undefined);
+ return { draftId: result.draftId, threadId: result.threadId };
},
};
}
diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.ts
index 0572628bac..ff527d69a3 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts
@@ -246,6 +246,17 @@ export function createEmailComposer(props: EmailComposerOptions) {
const currentDraftId = session.draftId;
const [sentDraftId, setSentDraftId] = createSignal<string>();
const currentThreadId = session.threadId;
+ // A reload reopens the draft this composer opened, which this device can
+ // read even while its save is queued. A draft the composer creates or moves
+ // to is recorded only once the server confirms it.
+ const confirmedDraftId = createMemo<string | undefined>((previous) => {
+ const identity = session.identity();
+ if (identity.kind === 'none') return undefined;
+ return session.serverConfirmed() ? identity.draftId : previous;
+ }, initialDraftId);
+ createEffect(
+ on(confirmedDraftId, (draftId) => props.host?.recordDraft?.(draftId))
+ );
const sendLocked = () =>
props.delivery.sendLocked?.(currentDraftId() ?? sentDraftId()) ?? false;
observeDraftIdentity(
@@ -1276,6 +1287,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
draftGeneration,
onTransferred: () => setDraftGeneration(0),
session,
+ persistence,
drafts: props.drafts,
attachments: form.attachments,
save: () => autosave.save(),
@@ -1310,13 +1322,18 @@ export function createEmailComposer(props: EmailComposerOptions) {
);
}
autosave.cancel();
- if (sourceInboxId && sourceInboxId !== inboxId) {
- await draftTransfer?.move(destination, sourceInboxId);
- }
+ const moved =
+ sourceInboxId && sourceInboxId !== inboxId
+ ? await draftTransfer?.move(destination, sourceInboxId)
+ : undefined;
form.setSelectedInbox(inboxId, senderEmail);
editVersion += 1;
setDraftDirty(true);
- await autosave.save();
+ // 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);
+ await saved;
} catch (error) {
props.notices.reportError(error);
props.notices.feedback.failure(
diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.ts
index 9d253a5690..48b9178a0a 100644
--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts
@@ -845,6 +845,7 @@ export function createReplyComposer(
draftGeneration,
onTransferred: () => setDraftGeneration(0),
session,
+ persistence,
drafts: props.drafts,
attachments: form.attachments,
save: () => executeSaveDraft(),
diff --git a/apps/web/src/features/email-compose/tests/composer.ts b/apps/web/src/features/email-compose/tests/composer.ts
index f8dac480f1..3c51039678 100644
--- a/apps/web/src/features/email-compose/tests/composer.ts
+++ b/apps/web/src/features/email-compose/tests/composer.ts
@@ -17,6 +17,8 @@ export function mountEmailComposer(
EmailComposerOptions,
| 'draft'
| 'draftId'
+ | 'draftPersistence'
+ | 'localDraft'
| 'initialInboxId'
| 'initialSubject'
| 'initialBodyText'
diff --git a/apps/web/src/lib/queries/email/draft.ts b/apps/web/src/lib/queries/email/draft.ts
index b410b4d410..2c99f32cda 100644
--- a/apps/web/src/lib/queries/email/draft.ts
+++ b/apps/web/src/lib/queries/email/draft.ts
@@ -1,4 +1,5 @@
import { DraftTransferAborted } from '@app/features/email-compose/context/compose-capabilities';
+import { fireAndForget } from '@core/util/fireAndForget';
import { throwOnErr } from '@core/util/result';
import { Telemetry } from '@macro-inc/observability';
import { invalidateAllSoup, refetchSoupEntity } from '@queries/soup/cache';
@@ -6,6 +7,7 @@ import { emailClient } from '@service-email/client';
import type {
ApiDraftInput,
CreateDraftResponse,
+ TransferDraftResponse,
} from '@service-email/generated/schemas';
import { getGraphqlCacheHost } from '@service-storage/graphql-soup';
import { useMutation } from '@tanstack/solid-query';
@@ -165,22 +167,24 @@ export async function transferEmailDraft(input: {
result = recovery.committed;
}
// Cache refresh errors must not turn a committed move into a failed write.
- try {
- await getGraphqlCacheHost()?.deleteRecords([
- `GraphqlSoupEmailMessage:${result.source_id}`,
- ]);
- await Promise.all([
- refreshEmailThreadCache(result.source_thread_id),
- refreshEmailThreadCache(result.thread_id),
- ]);
- for (const threadId of [result.source_thread_id, result.thread_id]) {
- await queryClient.invalidateQueries({
- queryKey: emailKeys.threadMessages(threadId).queryKey,
- });
- }
- invalidateAllSoup();
- } catch (error) {
- Telemetry.error(error);
- }
+ // The caller shows the moved draft first. Evicting the source thread
+ // replaces a route that still shows it with the not-found page.
+ fireAndForget(refreshTransferredThreads(result), 'email-draft-transfer');
return result;
}
+
+async function refreshTransferredThreads(result: TransferDraftResponse) {
+ await getGraphqlCacheHost()?.deleteRecords([
+ `GraphqlSoupEmailMessage:${result.source_id}`,
+ ]);
+ await Promise.all([
+ refreshEmailThreadCache(result.source_thread_id),
+ refreshEmailThreadCache(result.thread_id),
+ ]);
+ for (const threadId of [result.source_thread_id, result.thread_id]) {
+ await queryClient.invalidateQueries({
+ queryKey: emailKeys.threadMessages(threadId).queryKey,
+ });
+ }
+ invalidateAllSoup();
+}
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index 6920301907..93824c4d06 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -97,6 +97,13 @@ provider copy before choosing an explicit resend; a resend in flight shows as
the send button's pending state. Switching the sender
inbox copies the draft and attachments into the destination; wait for completion
before sending. If the copy is interrupted, use retry or keep the original.
+A draft opened from Drafts then shows its thread in the destination inbox,
+never the not-found page; a draft in compose stays open there. Keep editing
+after the switch and check that no "This draft changed while saving" notice
+appears. Once a new compose's first save is confirmed, the URL carries its
+draft (`s0.email-compose.draft` for the first pane): reloading reopens it with
+its From, including after a From switch. The draft stays in the URL across
+further reloads, even while an offline edit is still queued.
Opening an attachment opens it in a split from its Drive copy, except a
calendar file: it opens its event (see the calendar invitations section of the
diff --git a/docs/architecture/email.md b/docs/architecture/email.md
index 30d87a627c..47dfa24df5 100644
--- a/docs/architecture/email.md
+++ b/docs/architecture/email.md
@@ -100,7 +100,7 @@ test exercises this ordering.
| `EmailRenderingContextValue` | Theme values, explicit image policy, link preparation, and image resolution with an abortable resource lifetime |
| `EmailFormContextInputs` | Viewer address and available inbox identities for recipient selection |
| `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; inputs use domain inbox IDs and completion intent |
+| `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 |
| `EmailComposeFeedback` | User notices and error reporting |
@@ -109,7 +109,7 @@ test exercises this ordering.
| `EmailEditorFiles` | View-owned editor file upload and sharing integration |
| `EmailComposeContext` | Compose capabilities supplied to views, which pass the narrow inputs each controller needs |
| `PersistedEmailIdentity` | Successful save/send result: draft, thread, and inbox identity without a transport envelope |
-| `EmailComposeHost` | Optional navigation, back handling, and focus movement supplied by the host |
+| `EmailComposeHost` | Optional navigation, a moved draft's destination, the route's draft, back handling, and focus movement supplied by the host |
Core types are owned by the features. Generated email service schemas and concrete
query results stop at adapters. `email-thread/queries/thread-source.ts` uses
@@ -287,6 +287,14 @@ inbox ID is not a precomputed header: primary-inbox omission belongs to the adap
Existing message/thread model fields retain their established snake_case spelling;
this cleanup does not rename generated schemas or persisted URLs. In particular,
the host still reads/writes the existing `draftID` compose route parameter.
+Those parameters live only in memory, so the compose route also records the
+composer's draft in its `email-compose.draft` pane search, replacing the
+current history entry, and reopens that draft ahead of `draftID`
+(`compose-route-draft.ts`). It records the draft the composer opened right
+away, since this device can read it while a save is queued, and records a draft
+the composer creates or moves to only once the server confirms it. A From switch that moves a draft keeps
+the compose route in place, while a thread route follows the moved draft to
+its new thread (`compose-host-adapter.ts`).
`EmailThreadStateProvider` and `useEmailThreadState` name mounted thread state.
`ThreadReplyInput` names the thread-owned reply entry point, while