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 edits through lag, offline and cold starts (#8804)

teo123fea2db317
diff --git a/apps/web/package.json b/apps/web/package.json
index 9cff92f7f0..674a0c088a 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -188,6 +188,9 @@
"@graphql-codegen/cli": "^7.1.3",
"@graphql-codegen/typed-document-node": "^7.0.3",
"@graphql-codegen/typescript-operations": "^6.0.5",
+ "@opentelemetry/api": "^1.9.1",
+ "@opentelemetry/core": "^2.9.0",
+ "@opentelemetry/sdk-trace-base": "^2.9.0",
"@playwright/test": "^1.55.1",
"@solidjs/meta": "^0.29.4",
"@solidjs/testing-library": "^0.8.10",
diff --git a/apps/web/src/features/email-compose/components/draft-sync-status.tsx b/apps/web/src/features/email-compose/components/draft-sync-status.tsx
index efa75974f2..6c0f558799 100644
--- a/apps/web/src/features/email-compose/components/draft-sync-status.tsx
+++ b/apps/web/src/features/email-compose/components/draft-sync-status.tsx
@@ -3,7 +3,7 @@ import { Show } from 'solid-js';
import { match } from 'ts-pattern';
import type { DraftSyncViewState } from '../core/local-draft';
-/** In-composer banner for draft failures; saving itself stays silent. */
+/** In-composer banner for draft failures and offline edits; saving itself stays silent. */
export function DraftSyncStatus(props: {
state?: DraftSyncViewState;
busy: boolean;
@@ -17,7 +17,7 @@ export function DraftSyncStatus(props: {
{(state) => (
<div
class="flex flex-wrap items-center gap-2 border-b border-edge-muted p-3 text-sm"
- role="alert"
+ role={state().failed ? 'alert' : 'status'}
>
<div class="min-w-0 flex-1">
<p>{state().message}</p>
diff --git a/apps/web/src/features/email-compose/compose-adapter.ts b/apps/web/src/features/email-compose/compose-adapter.ts
index 73095a6a86..474d61dc49 100644
--- a/apps/web/src/features/email-compose/compose-adapter.ts
+++ b/apps/web/src/features/email-compose/compose-adapter.ts
@@ -152,7 +152,7 @@ export function createEmailComposeContext(
options.threadTransport?.() ??
(graphqlSoupFlag().enabled ? 'graphql' : 'rest')
);
- const sends = useQueuedEmailSends(() => true);
+ const sends = useQueuedEmailSends();
// Attach handlers run as event handlers, which have no Solid owner of
// their own; the dialog needs the surface's.
const dialogOwner = getOwner();
@@ -601,7 +601,7 @@ export function createEmailComposeContext(
!inbox.settings.signature_on_replies_forwards)
? ''
: (inbox.settings.signature ?? '');
- return await sendEmailQueued({
+ const queued = await sendEmailQueued({
signatureHtml,
expectedLocalVersion: input.expectedLocalVersion,
draft: {
@@ -627,6 +627,10 @@ export function createEmailComposeContext(
restoreBodyText: input.restoreBodyText,
restoreBodyMacro: input.restoreBodyMacro,
});
+ // The thread shown after Send renders from this snapshot on mount; it
+ // must already hold the send, or the thread shows the draft instead.
+ await sends.refresh();
+ return queued;
},
async unschedule({ draftId, threadId, inboxId, draftGeneration }) {
const local = sends
diff --git a/apps/web/src/features/email-compose/primitives/compose-view-state.ts b/apps/web/src/features/email-compose/primitives/compose-view-state.ts
index e43f9bdc76..ef7b9a668c 100644
--- a/apps/web/src/features/email-compose/primitives/compose-view-state.ts
+++ b/apps/web/src/features/email-compose/primitives/compose-view-state.ts
@@ -85,6 +85,7 @@ export interface ComposeState {
// From-inbox selection: the inboxes the user can send from, the active one,
// and a setter to change it.
fromInboxes?: Accessor<FromInboxOption[]>;
+ inboxesLoading?: Accessor<boolean>;
selectedInboxId?: Accessor<string | undefined>;
onSelectInbox?: (inboxId: string, senderEmail?: string) => void;
hasPaidAccess: Accessor<boolean>;
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 5233474d0f..6fdd38a53d 100644
--- a/apps/web/src/features/email-compose/primitives/draft-persistence.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-persistence.ts
@@ -67,6 +67,7 @@ export function createDraftPersistence(options: {
const { session } = options;
let localRevision = options.localDraft?.revision;
let localGeneration = options.localDraft?.generation;
+ let removal: Promise<void> = Promise.resolve();
const mint = (draft: EmailDraft) => {
if (session.draftId()) return;
localRevision = undefined;
@@ -105,6 +106,9 @@ export function createDraftPersistence(options: {
attachments: readonly DraftFormAttachment[];
}) {
if (!options.drafts.saveLocalDraft) return;
+ // The copy being deleted refuses edits. Address the draft the delete
+ // leaves: a fresh one, or the same one when the delete failed.
+ await removal;
// Preserve an emptied working copy too; a failed delete must not restore
// the earlier body on reload. An untouched composer has no identity.
if (!input.draft && !session.draftId()) return;
@@ -158,23 +162,29 @@ export function createDraftPersistence(options: {
},
/** The draft has no content left: delete its row and drop its identity. */
async remove(input: { inboxId?: string; completingThread?: boolean }) {
- const draftId = session.draftId();
- const epoch = session.epoch();
- if (draftId) {
- try {
- await options.drafts.deleteDraft({
- draftId,
- draftGeneration: options.draftGeneration?.() ?? 0,
- threadId: session.threadId(),
- ...input,
- });
- } catch (error) {
- recordRejection(error, epoch);
- throw error;
+ const removed = Promise.withResolvers<void>();
+ removal = removed.promise;
+ try {
+ const draftId = session.draftId();
+ const epoch = session.epoch();
+ if (draftId) {
+ try {
+ await options.drafts.deleteDraft({
+ draftId,
+ draftGeneration: options.draftGeneration?.() ?? 0,
+ threadId: session.threadId(),
+ ...input,
+ });
+ } catch (error) {
+ recordRejection(error, epoch);
+ throw error;
+ }
}
+ if (session.isStale(epoch)) return;
+ session.dispatch({ type: 'emptied' });
+ } finally {
+ removed.resolve();
}
- if (session.isStale(epoch)) return;
- session.dispatch({ type: 'emptied' });
},
/**
diff --git a/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts b/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts
index b525bd88ed..895d6db11c 100644
--- a/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-sync-status.test.ts
@@ -37,6 +37,7 @@ it('offers retry discard when a crash interrupted deletion before admission', as
disposers.push(dispose);
return createDraftSyncStatus({
drafts: context.drafts,
+ connectivity: context.connectivity,
draftId: () => 'draft',
localSaveState: () => 'saved',
retry: vi.fn(),
@@ -62,6 +63,7 @@ it('shows a failed status read without throwing into the composer error boundary
disposers.push(dispose);
return createDraftSyncStatus({
drafts: context.drafts,
+ connectivity: context.connectivity,
draftId: () => 'draft',
localSaveState: () => 'saved',
retry: vi.fn(),
@@ -96,6 +98,7 @@ it('stays silent once a failed save recovers', async () => {
disposers.push(dispose);
return createDraftSyncStatus({
drafts: context.drafts,
+ connectivity: context.connectivity,
draftId: () => 'draft',
localSaveState: disk,
retry,
@@ -125,6 +128,7 @@ it('offers retry for server failures while newer edits remain saved locally', as
disposers.push(dispose);
return createDraftSyncStatus({
drafts: context.drafts,
+ connectivity: context.connectivity,
draftId: () => 'draft',
localSaveState: () => 'saving',
retry: vi.fn(),
@@ -151,6 +155,7 @@ it('keeps local edits visible with an actionable synchronization status during r
disposers.push(dispose);
return createDraftSyncStatus({
drafts: context.drafts,
+ connectivity: context.connectivity,
draftId: () => 'draft',
localSaveState: () => 'saved',
retry: vi.fn(),
diff --git a/apps/web/src/features/email-compose/primitives/draft-sync-status.ts b/apps/web/src/features/email-compose/primitives/draft-sync-status.ts
index 1d8a219142..8c4380fa75 100644
--- a/apps/web/src/features/email-compose/primitives/draft-sync-status.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-sync-status.ts
@@ -8,12 +8,16 @@ import {
onCleanup,
} from 'solid-js';
import { match } from 'ts-pattern';
-import type { EmailDraftStorage } from '../context/compose-capabilities';
+import type {
+ EmailConnectivity,
+ EmailDraftStorage,
+} from '../context/compose-capabilities';
import type { DraftSyncViewState } from '../core/local-draft';
/** Recovery reads only metadata; file blobs are restored once when opening a draft. */
export function createDraftSyncStatus(options: {
drafts: EmailDraftStorage;
+ connectivity: EmailConnectivity;
draftId: Accessor<string | undefined>;
localSaveState: Accessor<'saving' | 'saved' | 'failed'>;
retry(): Promise<unknown>;
@@ -40,6 +44,18 @@ export function createDraftSyncStatus(options: {
(local()?.status === 'deleting' &&
(!local()?.queuedAttemptId ||
local()?.queuedAttemptId !== local()?.latestAttemptId));
+ // Saving is silent online. Offline, edits wait on this device.
+ const offlineState = (): DraftSyncViewState | undefined => {
+ const draft = local();
+ if (!draft || draft.acknowledgedRevision >= draft.revision) return;
+ if (!options.connectivity.looksOffline()) return;
+ return {
+ message: 'Saved on this device; waiting to sync',
+ detail: 'Changes stay on this device until you are back online.',
+ failed: false,
+ canKeepEditing: false,
+ };
+ };
const state = createMemo<DraftSyncViewState | undefined>(() => {
if (!options.drafts.saveLocalDraft || !options.draftId()) return;
const disk = options.localSaveState();
@@ -79,8 +95,7 @@ export function createDraftSyncStatus(options: {
canKeepEditing: false,
};
}
- // Saving is silent; only failures that need the user surface here.
- if (!failed) return;
+ if (!failed) return offlineState();
return {
message:
disk === 'failed'
diff --git a/apps/web/src/features/email-compose/primitives/draft-transfer.test.ts b/apps/web/src/features/email-compose/primitives/draft-transfer.test.ts
new file mode 100644
index 0000000000..d3a2a68727
--- /dev/null
+++ b/apps/web/src/features/email-compose/primitives/draft-transfer.test.ts
@@ -0,0 +1,125 @@
+import { ZoneContextManager } from '@macro-inc/observability/zone';
+import { context, propagation, trace } from '@opentelemetry/api';
+import { W3CTraceContextPropagator } from '@opentelemetry/core';
+import {
+ BasicTracerProvider,
+ type ReadableSpan,
+} from '@opentelemetry/sdk-trace-base';
+import { transferEmailDraft } from '@queries/email/draft';
+import { afterEach, expect, it, vi } from 'vitest';
+import type { EmailInbox } from '../context/compose-capabilities';
+import { createDraftSession } from './draft-session';
+import { createDraftTransfer } from './draft-transfer';
+
+const finished: ReadableSpan[] = [];
+let open = 0;
+let settled: (() => void) | undefined;
+context.setGlobalContextManager(new ZoneContextManager().enable());
+propagation.setGlobalPropagator(new W3CTraceContextPropagator());
+trace.setGlobalTracerProvider(
+ new BasicTracerProvider({
+ spanProcessors: [
+ {
+ onStart: () => {
+ open += 1;
+ },
+ onEnd: (span) => {
+ finished.push(span);
+ open -= 1;
+ if (open === 0) settled?.();
+ },
+ forceFlush: () => Promise.resolve(),
+ shutdown: () => Promise.resolve(),
+ },
+ ],
+ })
+);
+
+function spansSettled() {
+ return open === 0
+ ? Promise.resolve()
+ : new Promise<void>((resolve) => {
+ settled = resolve;
+ });
+}
+
+const outlook: EmailInbox = {
+ id: 'outlook-inbox',
+ email_address: '[email protected]',
+ provider: 'OUTLOOK',
+ settings: {},
+};
+const movedDraft = {
+ message_id: 'draft-2',
+ thread_id: 'thread-2',
+ source_id: 'draft-1',
+ source_thread_id: 'thread-1',
+ attachments: [],
+};
+
+const fetch = vi.fn<typeof window.fetch>();
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function traceparentOf(pathSuffix: string) {
+ const call = fetch.mock.calls.find(([input]) =>
+ String(input).endsWith(pathSuffix)
+ );
+ const [, traceId, spanId] =
+ new Headers(call?.[1]?.headers).get('traceparent')?.split('-') ?? [];
+ return { traceId, spanId };
+}
+
+it('keeps the recover request and the detached cache refresh in the move’s trace', async () => {
+ vi.stubGlobal('fetch', fetch);
+ fetch
+ .mockRejectedValueOnce(new TypeError('Failed to fetch'))
+ .mockResolvedValueOnce(Response.json({ committed: movedDraft }));
+ const transfer = createDraftTransfer({
+ session: createDraftSession({
+ draftId: 'draft-1',
+ threadId: 'thread-1',
+ inboxId: 'gmail-inbox',
+ persistence: 'committed',
+ }),
+ persistence: { restored: vi.fn() },
+ drafts: {
+ async transferDraft(input) {
+ const result = await transferEmailDraft(input);
+ return {
+ draftId: result.message_id,
+ threadId: result.thread_id,
+ attachments: result.attachments,
+ };
+ },
+ },
+ attachments: { list: () => [], replace: vi.fn() },
+ save: vi.fn(async () => {}),
+ invalidateOldSaves: vi.fn(),
+ });
+
+ await expect(transfer.move(outlook, 'gmail-inbox')).resolves.toEqual({
+ draftId: 'draft-2',
+ threadId: 'thread-2',
+ });
+ await spansSettled();
+
+ const sent = traceparentOf('/drafts/draft-1/transfer');
+ expect(sent.traceId).toMatch(/^[\da-f]{32}$/);
+ expect(traceparentOf('/recover').traceId).toBe(sent.traceId);
+
+ const byId = new Map(
+ finished.map((span) => [span.spanContext().spanId, span])
+ );
+ const rootOf = (span: ReadableSpan | undefined): ReadableSpan | undefined =>
+ span?.parentSpanContext
+ ? rootOf(byId.get(span.parentSpanContext.spanId))
+ : span;
+ const rootIdOf = (span: ReadableSpan | undefined) =>
+ rootOf(span)?.spanContext().spanId;
+ expect(new Set(finished.map(rootIdOf))).toEqual(
+ new Set([rootIdOf(byId.get(sent.spanId ?? ''))])
+ );
+});
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 122cc87b59..6d338d93f2 100644
--- a/apps/web/src/features/email-compose/primitives/draft-transfer.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-transfer.ts
@@ -1,5 +1,6 @@
import { getUploadFileSize } from '@core/mobile/nativeStagedUpload';
import { fireAndForget } from '@core/util/fireAndForget';
+import { type Span, Telemetry } from '@macro-inc/observability';
import { createSignal } from 'solid-js';
import { v7 as uuidv7 } from 'uuid';
import {
@@ -12,6 +13,18 @@ import type { DraftPersistence } from './draft-persistence';
import type { DraftSession } from './draft-session';
import type { DraftFormAttachment } from './email-form-state';
+class DraftTransferRejected extends Error {
+ constructor(
+ readonly reason:
+ | 'pending_other_inbox'
+ | 'attachment_limit'
+ | 'unconfirmed_draft',
+ message: string
+ ) {
+ super(message);
+ }
+}
+
/** Preserve the operation ID across a lost response and adopt a distinct identity. */
export function createDraftTransfer(options: {
session: DraftSession;
@@ -28,82 +41,137 @@ export function createDraftTransfer(options: {
}) {
const [pending, setPending] =
createSignal<Parameters<EmailDraftStorage['transferDraft']>[0]>();
+ const transfer = async (
+ span: Span,
+ destination: EmailInbox,
+ sourceInboxId: string
+ ) => {
+ const pendingMove = pending();
+ if (pendingMove && pendingMove.destinationInboxId !== destination.id) {
+ throw new DraftTransferRejected(
+ 'pending_other_inbox',
+ 'Retry the previous inbox change before choosing another inbox.'
+ );
+ }
+ if (!pendingMove) {
+ const size = options.attachments
+ .list()
+ .reduce(
+ (sum, a) =>
+ sum + (a.type === 'local' ? getUploadFileSize(a.file) : a.fileSize),
+ 0
+ );
+ if (size > attachmentLimitBytes(destination.provider))
+ throw new DraftTransferRejected(
+ 'attachment_limit',
+ 'These attachments exceed the destination inbox’s size limit.'
+ );
+ await span.span('email.draft_transfer.save', async (save) => {
+ try {
+ await options.save();
+ } catch (error) {
+ save.error('Draft save failed');
+ throw error;
+ }
+ });
+ const draftId = options.session.draftId();
+ if (!draftId) return;
+ if (!options.session.serverConfirmed())
+ throw new DraftTransferRejected(
+ 'unconfirmed_draft',
+ 'Reconnect and let the draft finish saving before changing inboxes.'
+ );
+ setPending({
+ operationId: uuidv7(),
+ draftGeneration: options.draftGeneration?.(),
+ draftId,
+ sourceInboxId,
+ destinationInboxId: destination.id,
+ });
+ }
+ const request = pending();
+ if (!request) return;
+ span.setAttr('email.draft_transfer.draft_id', request.draftId);
+ span.setAttr('email.draft_transfer.operation_id', request.operationId);
+ let result;
+ try {
+ // Native awaits drop the active span, so the request joins this trace
+ // explicitly.
+ result = await span.run(() => options.drafts.transferDraft(request));
+ } catch (error) {
+ if (error instanceof DraftTransferAborted) setPending(undefined);
+ throw error;
+ }
+ 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,
+ threadId: result.threadId,
+ inboxId: destination.id,
+ });
+ options.attachments.replace(
+ result.attachments.map((a) => ({
+ type: 'remote',
+ attachmentId: a.id,
+ fileName: a.file_name,
+ contentType: a.content_type,
+ fileSize: a.size,
+ url: a.s3_key,
+ uploadPending: a.upload_pending,
+ }))
+ );
+ setPending(undefined);
+ return { draftId: result.draftId, threadId: result.threadId };
+ };
return {
pending,
/** Resolves with the moved draft's ids once the server commits the move. */
- async move(
+ move(
destination: EmailInbox,
sourceInboxId: string
): Promise<{ draftId: string; threadId: string } | undefined> {
- const pendingMove = pending();
- if (pendingMove && pendingMove.destinationInboxId !== destination.id) {
- throw new Error(
- 'Retry the previous inbox change before choosing another inbox.'
+ return Telemetry.span('email.draft_transfer', async (span) => {
+ span.setAttr('email.draft_transfer.source_inbox_id', sourceInboxId);
+ span.setAttr(
+ 'email.draft_transfer.destination_inbox_id',
+ destination.id
);
- }
- if (!pendingMove) {
- const size = options.attachments
- .list()
- .reduce(
- (sum, a) =>
- sum +
- (a.type === 'local' ? getUploadFileSize(a.file) : a.fileSize),
- 0
+ if (destination.provider)
+ span.setAttr(
+ 'email.draft_transfer.destination_provider',
+ destination.provider
);
- if (size > attachmentLimitBytes(destination.provider))
- throw new Error(
- 'These attachments exceed the destination inbox’s size limit.'
- );
- await options.save();
- const draftId = options.session.draftId();
- if (!draftId) return;
- if (!options.session.serverConfirmed())
- throw new Error(
- 'Reconnect and let the draft finish saving before changing inboxes.'
+ span.setAttr(
+ 'email.draft_transfer.attachment_count',
+ options.attachments.list().length
+ );
+ span.setAttr('email.draft_transfer.retry', pending() !== undefined);
+ try {
+ const moved = await transfer(span, destination, sourceInboxId);
+ span.setAttr(
+ 'email.draft_transfer.outcome',
+ moved ? 'moved' : 'skipped'
);
- setPending({
- operationId: uuidv7(),
- draftGeneration: options.draftGeneration?.(),
- draftId,
- sourceInboxId,
- destinationInboxId: destination.id,
- });
- }
- const request = pending();
- if (!request) return;
- let result;
- try {
- result = await options.drafts.transferDraft(request);
- } catch (error) {
- if (error instanceof DraftTransferAborted) setPending(undefined);
- throw error;
- }
- 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,
- threadId: result.threadId,
- inboxId: destination.id,
+ return moved;
+ } catch (error) {
+ if (error instanceof DraftTransferRejected) {
+ span.setAttr('email.draft_transfer.outcome', 'rejected');
+ span.setAttr('email.draft_transfer.rejection', error.reason);
+ } else {
+ const outcome =
+ error instanceof DraftTransferAborted ? 'aborted' : 'failed';
+ span.setAttr('email.draft_transfer.outcome', outcome);
+ span.error(`Draft transfer ${outcome}`);
+ }
+ throw error;
+ }
});
- options.attachments.replace(
- result.attachments.map((a) => ({
- type: 'remote',
- attachmentId: a.id,
- fileName: a.file_name,
- contentType: a.content_type,
- fileSize: a.size,
- url: a.s3_key,
- uploadPending: a.upload_pending,
- }))
- );
- 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 2b6a3eb8ff..b3f9bcab15 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts
@@ -1536,6 +1536,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
// Display
fromAddress: () => form.senderEmail() ?? link()?.email_address,
fromInboxes: () => fromInboxOptions(props.accounts.inboxes()),
+ inboxesLoading: props.accounts.loading,
selectedInboxId: () => link()?.id,
// Persist immediately on a sender switch so the draft moves to the new
// inbox even without a text edit.
diff --git a/apps/web/src/features/email-compose/primitives/emptied-draft-delete.test.ts b/apps/web/src/features/email-compose/primitives/emptied-draft-delete.test.ts
new file mode 100644
index 0000000000..5817002ab8
--- /dev/null
+++ b/apps/web/src/features/email-compose/primitives/emptied-draft-delete.test.ts
@@ -0,0 +1,419 @@
+import 'fake-indexeddb/auto';
+import { CombinedError, createClient, type Operation } from '@urql/core';
+import { IDBFactory } from 'fake-indexeddb';
+import { Kind } from 'graphql';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { filter, fromPromise, mergeMap, pipe } from 'wonka';
+import {
+ DraftPersistRejected,
+ type EmailInbox,
+ type SaveEmailDraft,
+} from '../context/compose-capabilities';
+import { decodeBase64Utf8 } from '../core/decode-base64';
+import type { EmailRecipient } from '../core/email-recipient';
+import { createComposeContext } from '../tests/capabilities';
+import { mountEmailComposer } from '../tests/composer';
+import { mountReplyComposer } from '../tests/reply';
+
+const network = vi.hoisted(() => ({
+ client: undefined as unknown,
+ uncertainDelete: false,
+ readRecordsByKeys: undefined as unknown as (
+ request: unknown
+ ) => Promise<unknown>,
+}));
+
+vi.mock('@app/lib/analytics', () => ({
+ analytics: { track: vi.fn(), posthog: { captureException: vi.fn() } },
+}));
+vi.mock('@queries/client', () => ({
+ queryClient: {
+ getQueryData: () => ({ authenticated: true, id: 'owner' }),
+ invalidateQueries: vi.fn(async () => {}),
+ },
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: vi.fn() },
+}));
+vi.mock('@core/constant/featureFlags', () => ({
+ enableGraphqlSoup: 'graphql-soup',
+ isFeatureEnabled: () => true,
+}));
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: { error: vi.fn() },
+}));
+vi.mock('@service-storage/graphql-soup', () => ({
+ assertEmailDraftQueueAvailable: () => {},
+ getGraphqlCacheHost: () => ({
+ readRecordsByKeys: (request: unknown) => network.readRecordsByKeys(request),
+ }),
+ getGraphqlSoupClient: () => network.client,
+ graphqlCacheEnabled: () => true,
+ graphqlCacheRecoveryState: () => undefined,
+ graphqlDraftQueueBlocked: () => false,
+ retryGraphqlCacheInitialization: async () => {},
+}));
+vi.mock('@queries/soup/cache', () => ({
+ invalidateAllSoup: vi.fn(),
+ invalidateSoupEntity: vi.fn(),
+ refetchSoupEntity: vi.fn(async () => {}),
+}));
+vi.mock('@queries/email/draft-cache', () => ({
+ markThreadDraftSaved: vi.fn(),
+}));
+vi.mock('@queries/email/thread', () => ({ fetchAndCacheThread: vi.fn() }));
+
+let localDrafts: typeof import('@queries/email/local-drafts');
+let draftQueue: typeof import('@queries/email/draft-queue');
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.stubGlobal('indexedDB', new IDBFactory());
+ localStorage.clear();
+ localDrafts = await import('@queries/email/local-drafts');
+ draftQueue = await import('@queries/email/draft-queue');
+});
+afterEach(async () => {
+ await localDrafts.localDraftStore.close();
+ vi.unstubAllGlobals();
+});
+
+const providers: [string, EmailInbox][] = [
+ [
+ 'Gmail',
+ {
+ id: 'inbox',
+ email_address: '[email protected]',
+ provider: 'GMAIL',
+ settings: {},
+ },
+ ],
+ [
+ 'Outlook',
+ {
+ id: 'inbox',
+ email_address: '[email protected]',
+ provider: 'OUTLOOK',
+ settings: {},
+ },
+ ],
+];
+
+const recipient = (email: string): EmailRecipient => ({
+ kind: 'custom',
+ id: `macro|${email}`,
+ data: { id: `macro|${email}`, email, invalid: false },
+});
+
+const operationName = (operation: Operation) =>
+ operation.query.definitions.find(
+ (definition) => definition.kind === Kind.OPERATION_DEFINITION
+ )?.name?.value;
+
+/**
+ * The durable draft queue against IndexedDB working copies. Only the
+ * GraphQL transport and the cache worker are fake: a delete waits for the
+ * test to answer it, then comes back queued, as a timed-out request does.
+ */
+function createQueueContext(inbox: EmailInbox) {
+ const deleteSent = Promise.withResolvers<void>();
+ const deleteAnswered = Promise.withResolvers<void>();
+ network.uncertainDelete = false;
+ network.readRecordsByKeys = async () => ({ revision: '1', records: [] });
+ network.client = createClient({
+ url: 'http://example.test/graphql',
+ exchanges: [
+ () => (operations$) =>
+ pipe(
+ operations$,
+ filter((operation) => operation.kind === 'mutation'),
+ mergeMap((operation) =>
+ fromPromise(
+ (async () => {
+ if (operationName(operation) === 'DeleteEmailDraft') {
+ if (network.uncertainDelete)
+ return {
+ operation,
+ stale: false,
+ hasNext: false,
+ error: new CombinedError({
+ networkError: new Error(
+ 'cache storage changed during enqueue'
+ ),
+ }),
+ };
+ deleteSent.resolve();
+ await deleteAnswered.promise;
+ }
+ return {
+ operation,
+ stale: false,
+ hasNext: false,
+ extensions: {
+ normalizedCacheMutationDisposition: {
+ kind: 'queued',
+ transactionId: crypto.randomUUID(),
+ },
+ },
+ };
+ })()
+ )
+ )
+ ),
+ ],
+ });
+
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [inbox];
+ context.drafts.saveLocalDraft = (input) =>
+ localDrafts.saveLocalDraft({
+ ...input,
+ senderEmail: inbox.email_address,
+ });
+ const saves: SaveEmailDraft[] = [];
+ context.drafts.saveDraft = vi.fn(async (input) => {
+ saves.push(input);
+ return {
+ draftId: input.clientHandles?.draftId ?? input.draft.db_id ?? '',
+ threadId: input.clientHandles?.threadId ?? input.draft.thread_db_id,
+ inboxId: input.inboxId ?? inbox.id,
+ persistence: 'queued' as const,
+ };
+ });
+ context.drafts.deleteDraft = vi.fn(async (input) => {
+ if (!input.threadId) throw new Error('A new draft has a thread handle');
+ const outcome = await draftQueue.deleteEmailDraftQueued({
+ draftId: input.draftId,
+ draftGeneration: input.draftGeneration,
+ threadId: input.threadId,
+ completingThread: input.completingThread,
+ });
+ if (outcome.kind === 'rejected')
+ throw new DraftPersistRejected(outcome.code);
+ });
+ return {
+ context,
+ saves,
+ deleteSent: deleteSent.promise,
+ answerDelete: () => deleteAnswered.resolve(),
+ };
+}
+
+const addressedTo = (save: SaveEmailDraft, email: string) =>
+ save.draft.to?.some((contact) => contact.email === email) ?? false;
+const saysIn = (save: SaveEmailDraft, text: string) =>
+ decodeBase64Utf8(save.draft.body_html ?? '').includes(text);
+
+async function waitForSave(
+ saves: SaveEmailDraft[],
+ matches: (save: SaveEmailDraft) => boolean
+) {
+ return await vi.waitFor(
+ () => {
+ const save = saves.find(matches);
+ expect(save).toBeDefined();
+ return save!;
+ },
+ { timeout: 3_000 }
+ );
+}
+
+/** Edits are kept on the device and no local-save failure was shown. */
+async function expectSavedLocally(
+ state: { localSaveState(): 'saving' | 'saved' | 'failed' },
+ failure: ReturnType<typeof vi.fn>
+) {
+ await vi.waitFor(() => expect(state.localSaveState()).toBe('saved'), {
+ timeout: 3_000,
+ });
+ expect(
+ failure.mock.calls.filter(
+ ([message]) => message === 'Draft could not be saved on this device'
+ )
+ ).toEqual([]);
+}
+
+/** A slow delete outlasts the composer's 500 ms autosave debounce. */
+const outlastAutosaveDebounce = () =>
+ new Promise((resolve) => setTimeout(resolve, 700));
+
+const timedOutCacheRead = async () => {
+ throw new Error('cache worker timeout: read-records-by-keys');
+};
+
+const unqueuedDeletes = providers.flatMap(([provider, inbox]) => [
+ [
+ provider,
+ 'its cache read timed out',
+ inbox,
+ () => {
+ network.readRecordsByKeys = timedOutCacheRead;
+ },
+ ] as const,
+ [
+ provider,
+ 'its enqueue outcome was uncertain',
+ inbox,
+ () => {
+ network.uncertainDelete = true;
+ },
+ ] as const,
+]);
+
+/** Type, then clear every field so the composer deletes the draft it saved. */
+async function emptySavedDraft(
+ root: ReturnType<typeof mountEmailComposer>,
+ saves: SaveEmailDraft[]
+) {
+ root.edit('First version', '');
+ const first = await waitForSave(saves, (save) =>
+ saysIn(save, 'First version')
+ );
+ root.edit('', '');
+ root.state.context.setRecipients('to', []);
+ return first.clientHandles!.draftId;
+}
+
+async function emptySavedReply(
+ reply: ReturnType<typeof mountReplyComposer>,
+ saves: SaveEmailDraft[]
+) {
+ reply.edit('First version');
+ const first = await waitForSave(saves, (save) =>
+ saysIn(save, 'First version')
+ );
+ reply.edit('');
+ return first.clientHandles!.draftId;
+}
+
+it.each(providers)(
+ 'keeps a recipient added on %s while the emptied draft is still being deleted',
+ async (_provider, inbox) => {
+ const { context, saves, deleteSent, answerDelete } =
+ createQueueContext(inbox);
+ const root = mountEmailComposer(context);
+ try {
+ const emptied = await emptySavedDraft(root, saves);
+ await deleteSent;
+ root.state.context.setRecipients('to', [recipient('[email protected]')]);
+ await outlastAutosaveDebounce();
+ answerDelete();
+
+ await expectSavedLocally(
+ root.state,
+ vi.mocked(context.notices.feedback.failure)
+ );
+ const saved = await waitForSave(saves, (save) =>
+ addressedTo(save, '[email protected]')
+ );
+ const draftId = saved.clientHandles!.draftId;
+ expect(draftId).not.toBe(emptied);
+ expect(await localDrafts.readLocalDraft(draftId)).toMatchObject({
+ content: {
+ to: [expect.objectContaining({ email: '[email protected]' })],
+ },
+ });
+ } finally {
+ root.dispose();
+ }
+ }
+);
+
+it.each(unqueuedDeletes)(
+ "keeps a recipient added on %s after the emptied draft's delete failed because %s",
+ async (_provider, _failure, inbox, failDelete) => {
+ const { context, saves } = createQueueContext(inbox);
+ failDelete();
+ const root = mountEmailComposer(context);
+ try {
+ const emptied = await emptySavedDraft(root, saves);
+ await vi.waitFor(() =>
+ expect(context.notices.feedback.failure).toHaveBeenCalledWith(
+ 'Failed to delete draft'
+ )
+ );
+ root.state.context.setRecipients('to', [recipient('[email protected]')]);
+
+ await expectSavedLocally(
+ root.state,
+ vi.mocked(context.notices.feedback.failure)
+ );
+ const saved = await waitForSave(saves, (save) =>
+ addressedTo(save, '[email protected]')
+ );
+ expect(saved.clientHandles?.draftId).toBe(emptied);
+ expect(await localDrafts.readLocalDraft(emptied)).toMatchObject({
+ content: {
+ to: [expect.objectContaining({ email: '[email protected]' })],
+ },
+ });
+ } finally {
+ root.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'keeps reply text typed on %s while the emptied reply is still being deleted',
+ async (_provider, inbox) => {
+ const { context, saves, deleteSent, answerDelete } =
+ createQueueContext(inbox);
+ const reply = mountReplyComposer(context);
+ try {
+ const emptied = await emptySavedReply(reply, saves);
+ await deleteSent;
+ reply.edit('Second version');
+ await outlastAutosaveDebounce();
+ answerDelete();
+
+ await expectSavedLocally(
+ reply,
+ vi.mocked(context.notices.feedback.failure)
+ );
+ const saved = await waitForSave(saves, (save) =>
+ saysIn(save, 'Second version')
+ );
+ const draftId = saved.clientHandles!.draftId;
+ expect(draftId).not.toBe(emptied);
+ const local = await localDrafts.readLocalDraft(draftId);
+ expect(decodeBase64Utf8(local?.content.body_html ?? '')).toContain(
+ 'Second version'
+ );
+ } finally {
+ reply.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'keeps reply text typed on %s after the emptied reply could not be queued for deletion',
+ async (_provider, inbox) => {
+ const { context, saves } = createQueueContext(inbox);
+ network.readRecordsByKeys = timedOutCacheRead;
+ const reply = mountReplyComposer(context);
+ try {
+ const emptied = await emptySavedReply(reply, saves);
+ await vi.waitFor(() =>
+ expect(context.notices.feedback.failure).toHaveBeenCalledWith(
+ 'Failed to delete draft'
+ )
+ );
+ reply.edit('Second version');
+
+ await expectSavedLocally(
+ reply,
+ vi.mocked(context.notices.feedback.failure)
+ );
+ const saved = await waitForSave(saves, (save) =>
+ saysIn(save, 'Second version')
+ );
+ expect(saved.clientHandles?.draftId).toBe(emptied);
+ const local = await localDrafts.readLocalDraft(emptied);
+ expect(decodeBase64Utf8(local?.content.body_html ?? '')).toContain(
+ 'Second version'
+ );
+ } finally {
+ reply.dispose();
+ }
+ }
+);
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.ts
index 9c9b0bfa50..8a006a5b16 100644
--- a/apps/web/src/features/email-compose/primitives/queued-send-notice.ts
+++ b/apps/web/src/features/email-compose/primitives/queued-send-notice.ts
@@ -57,8 +57,8 @@ export function announceQueuedSend(options: {
.with({ state: 'accepted' }, ({ undoUntil }) => {
accepted = true;
const remaining = Date.parse(undoUntil) - Date.now();
+ withdrawUndo();
if (!undoRequested && remaining > 0) offerUndo('Sending…', remaining);
- else withdrawUndo();
})
.with({ state: 'sent' }, () => {
withdrawUndo();
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.ts
index fcf992b9a5..fed98cfb20 100644
--- a/apps/web/src/features/email-compose/primitives/send-outcome.test.ts
+++ b/apps/web/src/features/email-compose/primitives/send-outcome.test.ts
@@ -252,6 +252,32 @@ it.each(providers)(
}
);
+it.each(providers)(
+ '%s: leaves no Undo on offer once a send accepted with time left is sent',
+ 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();
+ report({
+ state: 'accepted',
+ undoUntil: new Date(Date.now() + 10_000).toISOString(),
+ });
+ expect(openUndoOffers(context)).toBe(1);
+
+ report({ state: 'pending' });
+ report({ state: 'sent' });
+ 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) => {
diff --git a/apps/web/src/features/email-compose/views/compose-focus.test.tsx b/apps/web/src/features/email-compose/views/compose-focus.test.tsx
new file mode 100644
index 0000000000..4bd23a9d75
--- /dev/null
+++ b/apps/web/src/features/email-compose/views/compose-focus.test.tsx
@@ -0,0 +1,156 @@
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import userEvent from '@testing-library/user-event';
+import type { JSX, ParentProps } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useCompose } from '../context/compose-context';
+import { createComposeContext } from '../tests/capabilities';
+import { createEmailEditor, setEmailEditorText } from '../tests/editor';
+import { EmailComposeView } from './email-compose';
+
+vi.mock('@components/app/split-layout/components/SplitHeader', () => ({
+ SplitHeaderLeft: () => null,
+}));
+vi.mock('@components/app/split-layout/components/SplitLabel', () => ({
+ SplitHeaderBadge: () => null,
+ StaticSplitLabel: () => null,
+}));
+vi.mock('@core/mobile/WrapUnlessMobile', () => ({
+ WrapUnlessMobile: (props: ParentProps) => props.children,
+}));
+vi.mock('@core/hotkey/hotkeys', () => ({
+ registerHotkey: vi.fn(),
+ useHotkeyDOMScope: () => [vi.fn(), 'compose-email'],
+}));
+vi.mock('@core/context/user', () => ({
+ useEmail: () => () => '[email protected]',
+ useUserId: () => () => 'macro|[email protected]',
+}));
+vi.mock('@core/user/dmActivity', () => ({
+ useAugmentUserWithDmActivity: () => (user: unknown) => user,
+}));
+vi.mock('@core/component/HoverCard', () => ({
+ HoverCard: (props: { trigger: JSX.Element }) => <>{props.trigger}</>,
+}));
+vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => null }));
+vi.mock('virtua/solid', async () => {
+ const { For } = await import('solid-js');
+ return {
+ VList: (props: {
+ data: unknown[];
+ children: (item: unknown) => JSX.Element;
+ }) => <For each={props.data}>{props.children}</For>,
+ };
+});
+vi.mock('../components/signature-preview', () => ({
+ SignaturePreview: () => null,
+}));
+vi.mock('../components/email-schedule-summary', () => ({
+ EmailScheduleBar: () => null,
+}));
+vi.mock('./compose-toolbar', () => ({ EmailComposeToolbar: () => null }));
+// The rich text editor is out of scope; the body only needs to take typing.
+vi.mock('./compose-body', () => ({
+ ComposeBody: () => {
+ const state = useCompose();
+ const editor = createEmailEditor();
+ state.captureEditor(editor);
+ state.onContentChange('');
+ return (
+ <textarea
+ aria-label="Message"
+ onInput={(event) => {
+ setEmailEditorText(editor, event.currentTarget.value);
+ state.onContentChange(event.currentTarget.value);
+ }}
+ />
+ );
+ },
+}));
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: vi.fn(),
+ });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+const providers = ['GMAIL', 'OUTLOOK'] as const;
+
+function openCompose(provider: (typeof providers)[number]) {
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [
+ { id: 'inbox', email_address: '[email protected]', provider, settings: {} },
+ ];
+ render(() => <EmailComposeView context={context} />);
+ return {
+ to: screen.getByRole<HTMLInputElement>('combobox'),
+ subject: screen.getByPlaceholderText<HTMLInputElement>('Subject'),
+ message: screen.getByRole<HTMLTextAreaElement>('textbox', {
+ name: 'Message',
+ }),
+ };
+}
+
+// A busy main thread runs queued input before the composer's deferred
+// mount work.
+const runDeferredMountWork = () =>
+ new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+it.each(providers)(
+ 'keeps typing in the subject the user reached before To took focus (%s)',
+ async (provider) => {
+ const user = userEvent.setup({ delay: null });
+ const compose = openCompose(provider);
+
+ await user.click(compose.subject);
+ await user.keyboard('Quarterly');
+ await runDeferredMountWork();
+ await user.keyboard(' plan');
+
+ expect(compose.to.value).toBe('');
+ expect(compose.subject.value).toBe('Quarterly plan');
+ expect(document.activeElement).toBe(compose.subject);
+ }
+);
+
+it.each(providers)(
+ 'keeps typing in the message the user reached before To took focus (%s)',
+ async (provider) => {
+ const user = userEvent.setup({ delay: null });
+ const compose = openCompose(provider);
+
+ await user.click(compose.message);
+ await user.keyboard('Hello');
+ await runDeferredMountWork();
+ await user.keyboard(' there');
+
+ expect(compose.to.value).toBe('');
+ expect(compose.message.value).toBe('Hello there');
+ }
+);
+
+it.each(providers)(
+ 'focuses To when a new compose opens (%s)',
+ async (provider) => {
+ const user = userEvent.setup({ delay: null });
+ const compose = openCompose(provider);
+
+ await runDeferredMountWork();
+ await user.keyboard('colleague');
+
+ expect(document.activeElement).toBe(compose.to);
+ expect(compose.to.value).toBe('colleague');
+ }
+);
diff --git a/apps/web/src/features/email-compose/views/compose-layout.test.tsx b/apps/web/src/features/email-compose/views/compose-layout.test.tsx
index 6e8c4175f9..afeef2b9fd 100644
--- a/apps/web/src/features/email-compose/views/compose-layout.test.tsx
+++ b/apps/web/src/features/email-compose/views/compose-layout.test.tsx
@@ -83,6 +83,32 @@ describe('ComposeLayout root composition', () => {
).toContain('[email protected]');
});
+ it('keeps the sender row while inboxes load, then shows the default inbox', () => {
+ const context = createComposeContext();
+ const inboxes = context.accounts.inboxes();
+ const [loaded, setLoaded] = createSignal(false);
+ context.accounts = {
+ ...context.accounts,
+ inboxes: () => (loaded() ? inboxes : []),
+ loading: () => !loaded(),
+ primaryId: () => (loaded() ? 'inbox' : undefined),
+ };
+ const root = mountEmailComposer(context);
+ composeStatus.sender = root.state.context;
+ try {
+ render(() => <ComposeLayout />);
+ const row = screen.getByRole('group', { name: 'Sending inbox' });
+ expect(row.getAttribute('aria-busy')).toBe('true');
+ setLoaded(true);
+ expect(screen.getByRole('group', { name: 'Sending inbox' })).toBe(row);
+ expect(row.getAttribute('aria-busy')).toBeNull();
+ expect(row.textContent).toContain('[email protected]');
+ } finally {
+ cleanup();
+ root.dispose();
+ }
+ });
+
it('shows the missing-sender error and lets the user select the only remaining inbox', async () => {
vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
const context = createComposeContext();
diff --git a/apps/web/src/features/email-compose/views/compose-layout.tsx b/apps/web/src/features/email-compose/views/compose-layout.tsx
index c88d0c9f9a..a336a461d9 100644
--- a/apps/web/src/features/email-compose/views/compose-layout.tsx
+++ b/apps/web/src/features/email-compose/views/compose-layout.tsx
@@ -29,6 +29,38 @@ type ComposeLayoutRefs = {
messageInput: HTMLElement | undefined;
};
+function ComposeSender() {
+ const ctx = useCompose();
+ return (
+ <div class="flex items-center gap-2 min-w-0 flex-1 py-3">
+ <span class="w-14 shrink-0 text-sm text-ink-placeholder">From</span>
+ <Show
+ when={ctx.fromInboxes?.().length}
+ fallback={
+ <Show
+ when={ctx.fromAddress?.() || !ctx.inboxesLoading?.()}
+ fallback={
+ <span class="h-6 w-40 rounded-full bg-skeleton skeleton-shimmer" />
+ }
+ >
+ <span class="truncate text-sm">{ctx.fromAddress?.()}</span>
+ </Show>
+ }
+ >
+ <FromInboxSelector
+ pill
+ class="min-w-0"
+ disabled={ctx.disabled()}
+ links={ctx.fromInboxes?.() ?? []}
+ activeInboxId={ctx.selectedInboxId?.()}
+ activeEmail={ctx.fromAddress?.()}
+ onSelect={(id, email) => ctx.onSelectInbox?.(id, email)}
+ />
+ </Show>
+ </div>
+ );
+}
+
/**
* Pure UI layout for the email compose form.
* Renders recipients, subject, body, and toolbar.
@@ -190,42 +222,18 @@ export function ComposeLayout(props: {
when={
props.header ||
(!ctx.isMobile() &&
- (ctx.fromInboxes?.().length || ctx.fromAddress?.()))
+ (ctx.fromInboxes?.().length ||
+ ctx.fromAddress?.() ||
+ ctx.inboxesLoading?.()))
}
>
<div
role="group"
aria-label="Sending inbox"
+ aria-busy={ctx.inboxesLoading?.() || undefined}
class="min-h-12 flex items-center gap-2 border-b border-edge-muted"
>
- <Show
- when={props.header}
- fallback={
- <div class="flex items-center gap-2 min-w-0 flex-1 py-3">
- <span class="w-14 shrink-0 text-sm text-ink-placeholder">
- From
- </span>
- <Show
- when={ctx.fromInboxes?.().length}
- fallback={
- <span class="truncate text-sm">
- {ctx.fromAddress?.()}
- </span>
- }
- >
- <FromInboxSelector
- pill
- class="min-w-0"
- disabled={ctx.disabled()}
- links={ctx.fromInboxes?.() ?? []}
- activeInboxId={ctx.selectedInboxId?.()}
- activeEmail={ctx.fromAddress?.()}
- onSelect={(id, email) => ctx.onSelectInbox?.(id, email)}
- />
- </Show>
- </div>
- }
- >
+ <Show when={props.header} fallback={<ComposeSender />}>
{props.header}
</Show>
</div>
diff --git a/apps/web/src/features/email-compose/views/compose-offline.test.tsx b/apps/web/src/features/email-compose/views/compose-offline.test.tsx
new file mode 100644
index 0000000000..440e670bcb
--- /dev/null
+++ b/apps/web/src/features/email-compose/views/compose-offline.test.tsx
@@ -0,0 +1,231 @@
+import 'fake-indexeddb/auto';
+import * as draftQueue from '@queries/email/draft-queue';
+import * as confirmation from '@queries/email/local-draft-confirmation';
+import * as localDrafts from '@queries/email/local-drafts';
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import userEvent from '@testing-library/user-event';
+import { IDBFactory } from 'fake-indexeddb';
+import type { JSX, ParentProps } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type {
+ EmailInbox,
+ SaveEmailDraft,
+} from '../context/compose-capabilities';
+import { useCompose } from '../context/compose-context';
+import { createComposeContext } from '../tests/capabilities';
+import { createEmailEditor, setEmailEditorText } from '../tests/editor';
+import { EmailComposeView } from './email-compose';
+
+vi.mock('@app/lib/analytics', () => ({
+ analytics: { track: vi.fn(), posthog: { captureException: vi.fn() } },
+}));
+vi.mock('@queries/client', () => ({
+ queryClient: {
+ getQueryData: () => ({ authenticated: true, id: 'owner' }),
+ invalidateQueries: vi.fn(async () => {}),
+ },
+}));
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: { error: vi.fn(), info: vi.fn() },
+}));
+vi.mock('@service-storage/graphql-soup', () => ({
+ assertEmailDraftQueueAvailable: () => {},
+ dssGraphqlFetch: vi.fn(),
+ getGraphqlCacheHost: () => undefined,
+ getGraphqlSoupClient: () => undefined,
+ graphqlCacheEnabled: () => true,
+ graphqlCacheRecoveryState: () => undefined,
+ graphqlDraftQueueBlocked: () => false,
+ retryGraphqlCacheInitialization: async () => {},
+}));
+vi.mock('@components/app/split-layout/components/SplitHeader', () => ({
+ SplitHeaderLeft: () => null,
+}));
+vi.mock('@components/app/split-layout/components/SplitLabel', () => ({
+ SplitHeaderBadge: () => null,
+ StaticSplitLabel: () => null,
+}));
+vi.mock('@core/mobile/WrapUnlessMobile', () => ({
+ WrapUnlessMobile: (props: ParentProps) => props.children,
+}));
+vi.mock('@core/hotkey/hotkeys', () => ({
+ registerHotkey: vi.fn(),
+ useHotkeyDOMScope: () => [vi.fn(), 'compose-email'],
+}));
+vi.mock('@core/context/user', () => ({
+ useEmail: () => () => '[email protected]',
+ useUserId: () => () => 'macro|[email protected]',
+}));
+vi.mock('@core/user/dmActivity', () => ({
+ useAugmentUserWithDmActivity: () => (user: unknown) => user,
+}));
+vi.mock('@core/component/HoverCard', () => ({
+ HoverCard: (props: { trigger: JSX.Element }) => <>{props.trigger}</>,
+}));
+vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => null }));
+vi.mock('virtua/solid', async () => {
+ const { For } = await import('solid-js');
+ return {
+ VList: (props: {
+ data: unknown[];
+ children: (item: unknown) => JSX.Element;
+ }) => <For each={props.data}>{props.children}</For>,
+ };
+});
+vi.mock('../components/signature-preview', () => ({
+ SignaturePreview: () => null,
+}));
+vi.mock('../components/email-schedule-summary', () => ({
+ EmailScheduleBar: () => null,
+}));
+vi.mock('./compose-toolbar', () => ({ EmailComposeToolbar: () => null }));
+// The rich text editor is out of scope; the body only needs to take typing.
+vi.mock('./compose-body', () => ({
+ ComposeBody: () => {
+ const state = useCompose();
+ const editor = createEmailEditor();
+ state.captureEditor(editor);
+ state.onContentChange('');
+ return (
+ <textarea
+ aria-label="Message"
+ onInput={(event) => {
+ setEmailEditorText(editor, event.currentTarget.value);
+ state.onContentChange(event.currentTarget.value);
+ }}
+ />
+ );
+ },
+}));
+
+beforeEach(() => {
+ vi.stubGlobal('indexedDB', new IDBFactory());
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: vi.fn(),
+ });
+});
+afterEach(async () => {
+ cleanup();
+ await localDrafts.localDraftStore.close();
+ vi.unstubAllGlobals();
+});
+
+const providers: [string, EmailInbox][] = [
+ [
+ 'Gmail',
+ {
+ id: 'inbox',
+ email_address: '[email protected]',
+ provider: 'GMAIL',
+ settings: {},
+ },
+ ],
+ [
+ 'Outlook',
+ {
+ id: 'inbox',
+ email_address: '[email protected]',
+ provider: 'OUTLOOK',
+ settings: {},
+ },
+ ],
+];
+
+/**
+ * A new compose on the device's working copies. The server write is queued
+ * and stays unconfirmed until the test confirms it, as it does offline.
+ */
+function openCompose(inbox: EmailInbox, network: { offline: boolean }) {
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [inbox];
+ context.connectivity.looksOffline = () => network.offline;
+ context.drafts.saveLocalDraft = (input) =>
+ localDrafts.saveLocalDraft({
+ ...input,
+ senderEmail: inbox.email_address,
+ });
+ context.drafts.readDraft = draftQueue.readEmailDraft;
+ context.drafts.watchDrafts = draftQueue.watchEmailDrafts;
+ const saves: SaveEmailDraft[] = [];
+ context.drafts.saveDraft = vi.fn(async (input) => {
+ saves.push(input);
+ return {
+ draftId: input.clientHandles?.draftId ?? input.draft.db_id ?? '',
+ threadId: input.clientHandles?.threadId ?? input.draft.thread_db_id,
+ inboxId: input.inboxId ?? inbox.id,
+ persistence: 'queued' as const,
+ };
+ });
+ render(() => <EmailComposeView context={context} />);
+ return {
+ saves,
+ subject: screen.getByPlaceholderText<HTMLInputElement>('Subject'),
+ message: screen.getByRole<HTMLTextAreaElement>('textbox', {
+ name: 'Message',
+ }),
+ /** The server acknowledges the newest copy this device holds. */
+ async confirmOnServer() {
+ const handles = saves.at(-1)?.clientHandles;
+ const local = await localDrafts.readLocalDraft(handles?.draftId ?? '');
+ await confirmation.confirmLocalDraftSave(local, {
+ draftId: 'server-draft',
+ threadId: 'server-thread',
+ });
+ },
+ };
+}
+
+const unsyncedNotice = () =>
+ screen.queryByText('Saved on this device; waiting to sync');
+
+it.each(providers)(
+ 'shows that offline edits on %s are only on this device until the server has them',
+ async (_provider, inbox) => {
+ const user = userEvent.setup();
+ const network = { offline: true };
+ const compose = openCompose(inbox, network);
+
+ await user.click(compose.subject);
+ await user.keyboard('Quarterly plan');
+ await user.click(compose.message);
+ await user.keyboard('Numbers attached');
+
+ await vi.waitFor(() => expect(unsyncedNotice()).not.toBeNull(), {
+ timeout: 3_000,
+ });
+
+ network.offline = false;
+ await compose.confirmOnServer();
+ await vi.waitFor(() => expect(unsyncedNotice()).toBeNull(), {
+ timeout: 3_000,
+ });
+ }
+);
+
+it.each(providers)(
+ 'keeps saving silent on %s while online',
+ async (_provider, inbox) => {
+ const user = userEvent.setup();
+ const compose = openCompose(inbox, { offline: false });
+
+ await user.click(compose.subject);
+ await user.keyboard('Quarterly plan');
+ await user.click(compose.message);
+ await user.keyboard('Numbers attached');
+ await vi.waitFor(() => expect(compose.saves.length).toBeGreaterThan(0), {
+ timeout: 3_000,
+ });
+
+ expect(unsyncedNotice()).toBeNull();
+ expect(screen.queryByRole('alert')).toBeNull();
+ }
+);
diff --git a/apps/web/src/features/email-compose/views/email-compose.tsx b/apps/web/src/features/email-compose/views/email-compose.tsx
index 2dc4bc5842..930f3a2116 100644
--- a/apps/web/src/features/email-compose/views/email-compose.tsx
+++ b/apps/web/src/features/email-compose/views/email-compose.tsx
@@ -144,6 +144,7 @@ function LoadedEmailComposeView(
});
const sync = createDraftSyncStatus({
drafts: composeContext.drafts,
+ connectivity: composeContext.connectivity,
draftId: state.draftId,
localSaveState: state.localSaveState,
retry: state.retryDraft,
diff --git a/apps/web/src/features/email-compose/views/reply-input.tsx b/apps/web/src/features/email-compose/views/reply-input.tsx
index 3fb0b5e067..9e194d9eec 100644
--- a/apps/web/src/features/email-compose/views/reply-input.tsx
+++ b/apps/web/src/features/email-compose/views/reply-input.tsx
@@ -170,6 +170,7 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {
);
const sync = createDraftSyncStatus({
drafts: composeContext.drafts,
+ connectivity: composeContext.connectivity,
draftId: state.savedDraftId,
localSaveState: state.localSaveState,
retry: state.retryDraft,
diff --git a/apps/web/src/lib/core/component/RecipientSelector.tsx b/apps/web/src/lib/core/component/RecipientSelector.tsx
index e19967beb1..fff3c5db82 100644
--- a/apps/web/src/lib/core/component/RecipientSelector.tsx
+++ b/apps/web/src/lib/core/component/RecipientSelector.tsx
@@ -16,6 +16,7 @@ import {
} from '@core/user';
import { useAugmentUserWithDmActivity } from '@core/user/dmActivity';
import { createFreshSearch, FreshSearchPresets } from '@core/util/freshSort';
+import { isEditableInput } from '@core/util/isEditableInput';
import { matches } from '@core/util/match';
import { truncateString } from '@core/util/string';
import CheckIcon from '@icon/system/regular/check.svg';
@@ -475,7 +476,12 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
if (props.focusOnMount) {
onMount(() => {
+ const focusedAtMount = document.activeElement;
setTimeout(() => {
+ // A busy page can run this after the user has moved on to another
+ // field; their typing stays there.
+ const focused = document.activeElement;
+ if (focused !== focusedAtMount && isEditableInput(focused)) return;
inputRef()?.focus();
}, 0);
});
diff --git a/apps/web/src/lib/queries/email/draft-queue.ts b/apps/web/src/lib/queries/email/draft-queue.ts
index 2f993a79d3..6838f41363 100644
--- a/apps/web/src/lib/queries/email/draft-queue.ts
+++ b/apps/web/src/lib/queries/email/draft-queue.ts
@@ -40,6 +40,7 @@ import {
import { mapGraphqlEmailMessage } from './graphql/mapper';
import { emailKeys } from './keys';
import {
+ abandonDraftDelete,
beginDraftAttempt,
draftSyncPaused,
localDraftMessage,
@@ -376,22 +377,35 @@ export async function deleteEmailDraftQueued(input: {
assertEmailDraftQueueAvailable();
const local = await readLocalDraft(input.draftId);
const attempt = local ? await beginDraftAttempt(local, 'delete') : undefined;
- const cached = await readCachedDraftAndThread(input.draftId, input.threadId);
- const client = getGraphqlSoupClient();
- assertEmailDraftQueueAvailable();
- const outcome = await executeGraphqlDeleteEmailDraft(client, {
- existingThread: cached.existingThread,
- mutationUuid: cached.mutationUuid ?? input.draftId,
- draftId: local?.draftId ?? String(cached.draftId),
- clientMetadata: attempt,
- draftGeneration:
- input.draftGeneration ??
- local?.content.draft_generation ??
- cached.existingDraft?.draftGeneration ??
- 0,
- threadDbId: cached.threadDbId,
- });
+ const abandon = async () => {
+ if (attempt) await abandonDraftDelete(attempt).catch(reportError);
+ };
+ let outcome: Awaited<ReturnType<typeof executeGraphqlDeleteEmailDraft>>;
+ try {
+ const cached = await readCachedDraftAndThread(
+ input.draftId,
+ input.threadId
+ );
+ const client = getGraphqlSoupClient();
+ assertEmailDraftQueueAvailable();
+ outcome = await executeGraphqlDeleteEmailDraft(client, {
+ existingThread: cached.existingThread,
+ mutationUuid: cached.mutationUuid ?? input.draftId,
+ draftId: local?.draftId ?? String(cached.draftId),
+ clientMetadata: attempt,
+ draftGeneration:
+ input.draftGeneration ??
+ local?.content.draft_generation ??
+ cached.existingDraft?.draftGeneration ??
+ 0,
+ threadDbId: cached.threadDbId,
+ });
+ } catch (error) {
+ await abandon();
+ throw error;
+ }
if (outcome.kind === 'failed') {
+ await abandon();
return {
kind: 'rejected',
code: rejection(outcome.code, 'Failed to delete draft', input.threadId),
diff --git a/apps/web/src/lib/queries/email/draft.ts b/apps/web/src/lib/queries/email/draft.ts
index 2c99f32cda..27aa76b155 100644
--- a/apps/web/src/lib/queries/email/draft.ts
+++ b/apps/web/src/lib/queries/email/draft.ts
@@ -135,42 +135,69 @@ export function useDeleteDraftMutation(
}
/** Moving creates a new server identity; old queued mutations retain their old target. */
-export async function transferEmailDraft(input: {
+export function transferEmailDraft(input: {
operationId: string;
draftId: string;
draftGeneration?: number;
sourceInboxId: string;
destinationInboxId: string;
}) {
- let result;
- try {
- result = await throwOnErr(() =>
- emailClient.transferDraft(
- input.draftId,
- {
- operation_id: input.operationId,
- draft_generation: input.draftGeneration ?? 0,
- destination_link_id: input.destinationInboxId,
- },
- input.sourceInboxId
- )
- );
- } catch (originalError) {
- const recovery = await throwOnErr(() =>
- emailClient.recoverDraftTransfer(input.operationId)
- );
- if (!recovery.committed)
- throw new DraftTransferAborted(
- 'The inbox change did not complete. Your original draft is preserved; you can edit it and try again.',
- { cause: originalError }
+ return Telemetry.span('email.draft_transfer.request', async (span) => {
+ let result: TransferDraftResponse;
+ try {
+ result = await throwOnErr(() =>
+ emailClient.transferDraft(
+ input.draftId,
+ {
+ operation_id: input.operationId,
+ draft_generation: input.draftGeneration ?? 0,
+ destination_link_id: input.destinationInboxId,
+ },
+ input.sourceInboxId
+ )
);
- result = recovery.committed;
- }
- // Cache refresh errors must not turn a committed move into a failed write.
- // 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;
+ span.setAttr('email.draft_transfer.committed_by', 'response');
+ } catch (originalError) {
+ const recovery = await span.span(
+ 'email.draft_transfer.recover',
+ async (recover) => {
+ try {
+ return await throwOnErr(() =>
+ emailClient.recoverDraftTransfer(input.operationId)
+ );
+ } catch (error) {
+ recover.error('Draft transfer recovery failed');
+ span.error('Draft transfer recovery failed');
+ throw error;
+ }
+ }
+ );
+ if (!recovery.committed) {
+ span.error('Draft transfer aborted');
+ throw new DraftTransferAborted(
+ 'The inbox change did not complete. Your original draft is preserved; you can edit it and try again.',
+ { cause: originalError }
+ );
+ }
+ span.setAttr('email.draft_transfer.committed_by', 'recovery');
+ result = recovery.committed;
+ }
+ // Cache refresh errors must not turn a committed move into a failed write.
+ // The caller shows the moved draft first. Evicting the source thread
+ // replaces a route that still shows it with the not-found page.
+ fireAndForget(
+ span.span('email.draft_transfer.refresh', async (refresh) => {
+ try {
+ await refreshTransferredThreads(result);
+ } catch (error) {
+ refresh.error('Draft transfer refresh failed');
+ throw error;
+ }
+ }),
+ 'email-draft-transfer'
+ );
+ return result;
+ });
}
async function refreshTransferredThreads(result: TransferDraftResponse) {
diff --git a/apps/web/src/lib/queries/email/local-drafts.test.ts b/apps/web/src/lib/queries/email/local-drafts.test.ts
index c6e070f2b1..8777ae07eb 100644
--- a/apps/web/src/lib/queries/email/local-drafts.test.ts
+++ b/apps/web/src/lib/queries/email/local-drafts.test.ts
@@ -523,6 +523,29 @@ describe('draft queue recovery', () => {
acknowledgedRevision: draft.revision,
});
});
+ it('keeps edits after an abandoned delete and refuses its late replay', async () => {
+ const draft = await runtime.saveLocalDraft(input());
+ const deleting = await runtime.beginDraftAttempt(draft, 'delete');
+ await runtime.abandonDraftDelete(deleting);
+ await runtime.saveLocalDraft(input('Kept edit'));
+ const replay = { ...claimed(deleting), operationName: 'DeleteEmailDraft' };
+ expect(
+ await runtime.localDraftQueueLifecycle(host).beforeMutationAttempt!(
+ replay
+ )
+ ).toBe(false);
+ expect(await runtime.readLocalDraft('local')).toMatchObject({
+ status: 'dirty',
+ content: { subject: 'Kept edit' },
+ });
+ });
+ it('leaves an admitted delete to the queue', async () => {
+ const draft = await runtime.saveLocalDraft(input());
+ const deleting = await runtime.beginDraftAttempt(draft, 'delete');
+ await runtime.markDraftAttemptQueued(deleting);
+ await runtime.abandonDraftDelete(deleting);
+ expect((await runtime.readLocalDraft('local'))?.status).toBe('deleting');
+ });
it('does not acknowledge later edits or let an old result clear newer failure', async () => {
const first = await runtime.saveLocalDraft(input('First'));
const saving = await runtime.beginDraftAttempt(first, 'save');
diff --git a/apps/web/src/lib/queries/email/local-drafts.ts b/apps/web/src/lib/queries/email/local-drafts.ts
index 0765c00f3d..bac7e4f46d 100644
--- a/apps/web/src/lib/queries/email/local-drafts.ts
+++ b/apps/web/src/lib/queries/email/local-drafts.ts
@@ -503,6 +503,24 @@ export async function beginDraftAttempt(
return attempt;
}
+/**
+ * A delete that never reached the queue returns the working copy to its
+ * editor. Clearing the attempt also refuses a replay of an enqueue whose
+ * outcome was uncertain.
+ */
+export async function abandonDraftDelete(attempt: DraftAttempt): Promise<void> {
+ const owner = await emailStorageSession();
+ if (owner.accountId !== attempt.accountId) return;
+ await localDraftStore.update(owner, attempt.draftKey, (draft) =>
+ draft.generation !== attempt.generation ||
+ draft.latestAttemptId !== attempt.id ||
+ draft.queuedAttemptId === attempt.id ||
+ draft.status !== 'deleting'
+ ? draft
+ : { ...draft, latestAttemptId: undefined, status: 'dirty' }
+ );
+}
+
/** Admission is separate from intent: two stores cannot enqueue atomically. */
export async function markDraftAttemptQueued(
attempt: DraftAttempt
diff --git a/apps/web/src/lib/queries/email/outbox-session.test.ts b/apps/web/src/lib/queries/email/outbox-session.test.ts
new file mode 100644
index 0000000000..b3350a2b7f
--- /dev/null
+++ b/apps/web/src/lib/queries/email/outbox-session.test.ts
@@ -0,0 +1,58 @@
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { setEmailOutboxSession } from './outbox-session';
+import { useQueuedEmailSends } from './queued-sends';
+
+const mocks = vi.hoisted(() => ({
+ read: vi.fn(),
+ dispatcher: vi.fn(() => ({ dispose() {} })),
+}));
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: { info: vi.fn(), warn: vi.fn() },
+}));
+vi.mock('@service-storage/email-send', () => ({
+ cancelEmailSend: vi.fn(),
+ readEmailSendStatus: vi.fn(),
+ submitEmailSend: vi.fn(),
+}));
+vi.mock('./email-send-dispatcher', () => ({
+ createEmailSendDispatcher: mocks.dispatcher,
+}));
+vi.mock('./email-send-recovery', () => ({
+ createEmailSendRecovery: () => ({ dispose() {} }),
+}));
+vi.mock('./local-drafts', () => ({
+ emailStorageSession: async () => ({ accountId: 'owner', epoch: 'epoch' }),
+ localDraftStore: {},
+}));
+vi.mock('./server-sends', () => ({ setServerSendSession: vi.fn() }));
+vi.mock('./send-queue', () => ({
+ readEmailSendIntents: mocks.read,
+ watchEmailSends: () => () => {},
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('window', { addEventListener() {}, removeEventListener() {} });
+});
+afterEach(() => {
+ setEmailOutboxSession(undefined);
+ vi.unstubAllGlobals();
+});
+
+it('has the outbox ready for the first compose after sign-in', async () => {
+ mocks.read.mockResolvedValue([]);
+ setEmailOutboxSession('owner');
+ await vi.waitFor(() => expect(mocks.dispatcher).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ let dispose = () => {};
+ const compose = createRoot((cleanup) => {
+ dispose = cleanup;
+ return useQueuedEmailSends();
+ });
+ try {
+ expect(compose.ready()).toBe(true);
+ } finally {
+ dispose();
+ }
+});
diff --git a/apps/web/src/lib/queries/email/outbox-session.ts b/apps/web/src/lib/queries/email/outbox-session.ts
index 14e78da7d7..eb039d23b7 100644
--- a/apps/web/src/lib/queries/email/outbox-session.ts
+++ b/apps/web/src/lib/queries/email/outbox-session.ts
@@ -7,6 +7,7 @@ import {
import { createEmailSendDispatcher } from './email-send-dispatcher';
import { createEmailSendRecovery } from './email-send-recovery';
import { emailStorageSession, localDraftStore } from './local-drafts';
+import { setQueuedSendSession } from './queued-sends';
import {
emailSendFailureKind,
recordEmailSend,
@@ -31,6 +32,7 @@ export function setEmailOutboxSession(accountId: string | undefined): void {
recovery = undefined;
dispatcher = undefined;
setServerSendSession(accountId);
+ setQueuedSendSession(accountId);
if (accountId) fireAndForget(start(accountId, current), 'email-outbox');
}
diff --git a/apps/web/src/lib/queries/email/queued-sends.test.ts b/apps/web/src/lib/queries/email/queued-sends.test.ts
index c192a1f22f..0e23e21071 100644
--- a/apps/web/src/lib/queries/email/queued-sends.test.ts
+++ b/apps/web/src/lib/queries/email/queued-sends.test.ts
@@ -1,6 +1,6 @@
import { createRoot } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { useQueuedEmailSends } from './queued-sends';
+import { setQueuedSendSession, useQueuedEmailSends } from './queued-sends';
import type { EmailSendIntent } from './send-queue';
const mocks = vi.hoisted(() => ({
@@ -55,6 +55,7 @@ beforeEach(() => {
mocks.status.mockResolvedValue(null);
vi.stubGlobal('navigator', { onLine: true });
vi.stubGlobal('window', { addEventListener() {}, removeEventListener() {} });
+ setQueuedSendSession(undefined);
});
afterEach(() => vi.unstubAllGlobals());
@@ -99,27 +100,73 @@ it('reports unavailable storage once until a read succeeds, while preserving rea
}
});
-it.each([false, true])(
- 'starts and cleans up polling only for an enabled observer: %s',
- async (enabled) => {
- const interval = vi.spyOn(globalThis, 'setInterval');
- const clear = vi.spyOn(globalThis, 'clearInterval');
- mocks.read.mockResolvedValue([]);
- let dispose = () => {};
- createRoot((cleanup) => {
- dispose = cleanup;
- useQueuedEmailSends(() => enabled);
+it('polls while any surface is open and stops with the last one', () => {
+ const interval = vi.spyOn(globalThis, 'setInterval');
+ const clear = vi.spyOn(globalThis, 'clearInterval');
+ mocks.read.mockResolvedValue([]);
+ try {
+ const first = createRoot((cleanup) => {
+ useQueuedEmailSends();
+ return cleanup;
});
- await Promise.resolve();
- if (enabled)
- expect(interval).toHaveBeenCalledWith(expect.any(Function), 5_000);
- else expect(interval).not.toHaveBeenCalled();
- dispose();
- if (enabled) expect(clear).toHaveBeenCalled();
+ const second = createRoot((cleanup) => {
+ useQueuedEmailSends();
+ return cleanup;
+ });
+ expect(interval).toHaveBeenCalledOnce();
+ expect(interval).toHaveBeenCalledWith(expect.any(Function), 5_000);
+ first();
+ expect(clear).not.toHaveBeenCalled();
+ second();
+ expect(clear).toHaveBeenCalledOnce();
+ } finally {
interval.mockRestore();
clear.mockRestore();
}
-);
+});
+
+it('drops the previous account’s sends when the session changes', async () => {
+ mocks.read.mockResolvedValue([intent]);
+ let dispose = () => {};
+ const queue = createRoot((cleanup) => {
+ dispose = cleanup;
+ return useQueuedEmailSends();
+ });
+ try {
+ await queue.refresh();
+ expect(queue.intents()).toEqual([intent]);
+ mocks.read.mockResolvedValue([]);
+ setQueuedSendSession('next-account');
+ expect(queue.ready()).toBe(false);
+ expect(queue.intents()).toEqual([]);
+ await vi.waitFor(() => expect(queue.ready()).toBe(true));
+ expect(queue.intents()).toEqual([]);
+ } finally {
+ dispose();
+ }
+});
+
+it('opens a later surface with the sends an earlier surface already read', async () => {
+ mocks.read.mockResolvedValue([]);
+ const disposers: (() => void)[] = [];
+ const mount = () =>
+ createRoot((cleanup) => {
+ disposers.push(cleanup);
+ return useQueuedEmailSends();
+ });
+ try {
+ const composer = mount();
+ await composer.refresh();
+ // Send persists the intent and refreshes before the thread opens.
+ mocks.read.mockResolvedValue([intent]);
+ await composer.refresh();
+ const thread = mount();
+ expect(thread.ready()).toBe(true);
+ expect(thread.intents()).toEqual([intent]);
+ } finally {
+ for (const dispose of disposers) dispose();
+ }
+});
it('ignores a late failed read after a newer journal refresh succeeds', async () => {
mocks.read.mockResolvedValue([]);
diff --git a/apps/web/src/lib/queries/email/queued-sends.ts b/apps/web/src/lib/queries/email/queued-sends.ts
index 54c1d64d3e..9cda2280b4 100644
--- a/apps/web/src/lib/queries/email/queued-sends.ts
+++ b/apps/web/src/lib/queries/email/queued-sends.ts
@@ -7,54 +7,69 @@ import {
} from './send-queue';
import { emailSendFailureKind, recordEmailSend } from './send-telemetry';
-/** Owner-scoped observer; missed events are recovered by reading durable state. */
-export function useQueuedEmailSends(enabled: () => boolean = () => true) {
- const [intents, setIntents] = createSignal<EmailSendIntent[]>([]);
- const [ready, setReady] = createSignal(false);
- let disposed = false;
- let generation = 0;
- let storageFailureReported = false;
- const refresh = async () => {
- if (!enabled()) return;
- const current = ++generation;
- try {
- const rows = await readEmailSendIntents();
- if (disposed || current !== generation) return;
- storageFailureReported = false;
- setIntents(rows);
- setReady(true);
- } catch (error) {
- if (!disposed && current === generation && !storageFailureReported) {
- storageFailureReported = true;
- recordEmailSend({
- operation: 'refresh',
- outcome: 'error',
- failureKind: emailSendFailureKind(error),
- });
- }
- if (!disposed && current === generation)
- setReady(
- false
- ); /* Missing storage is uncertainty, not an empty queue. */
+// One snapshot per document, so a surface that mounts after Send, such as the
+// thread it opens, starts from what earlier surfaces already read.
+const [intents, setIntents] = createSignal<EmailSendIntent[]>([]);
+const [ready, setReady] = createSignal(false);
+let generation = 0;
+let storageFailureReported = false;
+let observers = 0;
+let stopObserving: (() => void) | undefined;
+
+async function refresh() {
+ const current = ++generation;
+ try {
+ const rows = await readEmailSendIntents();
+ if (current !== generation) return;
+ storageFailureReported = false;
+ setIntents(rows);
+ setReady(true);
+ } catch (error) {
+ if (current !== generation) return;
+ if (!storageFailureReported) {
+ storageFailureReported = true;
+ recordEmailSend({
+ operation: 'refresh',
+ outcome: 'error',
+ failureKind: emailSendFailureKind(error),
+ });
}
+ setReady(false); /* Missing storage is uncertainty, not an empty queue. */
+ }
+}
+
+const wake = () => fireAndForget(refresh(), 'email-queued-sends');
+
+function observe() {
+ const unsubscribe = watchEmailSends(wake);
+ window.addEventListener('online', wake);
+ const interval = setInterval(wake, 5_000);
+ return () => {
+ unsubscribe();
+ clearInterval(interval);
+ window.removeEventListener('online', wake);
};
+}
+
+/** Read at sign-in so the first compose starts unlocked; another account's
+ * sends never carry over. */
+export function setQueuedSendSession(accountId: string | undefined) {
+ generation++;
+ storageFailureReported = false;
+ setIntents([]);
+ setReady(false);
+ if (accountId) wake();
+}
+
+/** Shared outbox observer; missed events are recovered by reading durable state. */
+export function useQueuedEmailSends() {
onMount(() => {
- fireAndForget(refresh(), 'email-queued-sends');
- const unsubscribe = enabled()
- ? watchEmailSends(() => {
- fireAndForget(refresh(), 'email-queued-sends');
- })
- : () => {};
- const reconnect = () => {
- fireAndForget(refresh(), 'email-queued-sends');
- };
- window.addEventListener('online', reconnect);
- const interval = enabled() ? setInterval(reconnect, 5_000) : undefined;
+ wake();
+ if (observers++ === 0) stopObserving = observe();
onCleanup(() => {
- disposed = true;
- unsubscribe();
- if (interval !== undefined) clearInterval(interval);
- window.removeEventListener('online', reconnect);
+ if (--observers > 0) return;
+ stopObserving?.();
+ stopObserving = undefined;
});
});
return { intents, ready, refresh };
diff --git a/bun.lock b/bun.lock
index cf9ddbf276..289490844c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -181,6 +181,9 @@
"@graphql-codegen/cli": "^7.1.3",
"@graphql-codegen/typed-document-node": "^7.0.3",
"@graphql-codegen/typescript-operations": "^6.0.5",
+ "@opentelemetry/api": "^1.9.1",
+ "@opentelemetry/core": "^2.9.0",
+ "@opentelemetry/sdk-trace-base": "^2.9.0",
"@playwright/test": "^1.55.1",
"@solidjs/meta": "^0.29.4",
"@solidjs/testing-library": "^0.8.10",
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index dbd26df26a..cfb0ef5e91 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -570,6 +570,9 @@ Standalone compose uses one right-aligned row inside its 16px content padding:
delete, attach, format, schedule, and send. Touch compose uses its header toolbar.
`R` and `Alt+R` (`Option+R` on macOS) open reply-all for the selected message,
or the latest message when none is selected. `F` opens a forward and focuses To.
+A new email also focuses To once it mounts, unless the user already moved to
+another field: with the CPU throttled, click Subject right after opening compose
+and type; every character must stay in Subject.
In new emails, replies, reply-alls, and forwards, `Cmd+Shift+C` (`Ctrl+Shift+C`)
reveals and focuses Cc and `Cmd+Shift+B` does the same for Bcc, expanding a
collapsed reply header; inside a composer they never fall through to the
@@ -649,17 +652,22 @@ also enables sending immediately. A late lookup must not overwrite that choice.
Implicit senders omit `from` on edits and sends. An explicit sender is preserved
even while inboxes load or after disconnection; an unavailable sender blocks Send
until another connected inbox is selected. New emails default to the primary
-inbox after inboxes load. Repeat on mobile using the expanded `Cc/Bcc, From:` row.
+inbox after inboxes load; until then the desktop From row keeps its place with a
+placeholder. The first compose after sign-in, including from All inboxes, opens
+editable with Send available, because the device outbox is read at sign-in.
+Repeat on mobile using the expanded `Cc/Bcc, From:` row.
With GraphQL draft queuing enabled, working copies and pending attachment bytes
are saved on this device independently of the mutation queue. A failed server
save must leave the draft discoverable in **Drafts** (including grouped views)
-and in its reply thread. Saving is silent on desktop and mobile: no saved or
-syncing text appears, including offline. A failure shows a banner inside the
-composer, above the recipients, with **Retry** (or **Retry discard**); while the
-local cache waits for another owner the banner keeps **Retry** and retries by
-itself, and once local storage needs recovery it offers **Reload** instead. It
-never appears in the toolbar or the mobile header actions. Verify the banner on mobile
+and in its reply thread. Saving is silent on desktop and mobile while online: no
+saved or syncing text appears. Offline, once an edit is saved only on this
+device, the composer shows **Saved on this device; waiting to sync** above the
+recipients until the server acknowledges it. A failure shows a banner in the same
+place with **Retry** (or **Retry discard**); while the local cache waits for
+another owner the banner keeps **Retry** and retries by itself, and once local
+storage needs recovery it offers **Reload** instead. Neither appears in the
+toolbar or the mobile header actions. Verify the banner on mobile
sits below the header and that editing while failed continues saving locally
without repeatedly submitting the rejected request. If sender metadata is still
unavailable, the local draft is retained; reconnect and select an inbox before
@@ -780,6 +788,8 @@ Sending must leave the new message's reply composer closed. After delivery,
focus belongs to the sent message card in the same thread pane, even while
the thread refresh is still pending. Replying again requires clicking Reply
or using a reply shortcut.
+Sending a new email opens its thread with the message already shown as sent; it
+must not show the draft or **Loading draft…** first.
After a send is queued, its notice offers `Undo`. Undo restores the
sent envelope and editable content, including when the reply used another inbox;
@@ -1049,6 +1059,11 @@ 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.
+Clearing every field of a draft deletes it. Edits made while that delete is on
+the wire, such as re-adding a recipient during a slow Outlook delete, must save
+to a fresh draft (or the same draft when the delete failed) and never report
+**This draft session is no longer active**. Verify with the delete request
+delayed and with it timing out.
In Email's inline detail, deletion closes the detail and preserves the current
mail tab and filters; it must not navigate split history to an older composer.
Discarding a reply draft must preserve the remaining conversation. A previously
diff --git a/docs/agent-guide/observability.md b/docs/agent-guide/observability.md
index a7092e3e19..8a77169d66 100644
--- a/docs/agent-guide/observability.md
+++ b/docs/agent-guide/observability.md
@@ -68,6 +68,14 @@ trace context — timestamps + service are the only join for those.
- Most frontend spans stop at the fetch: websocket-delivered results such as AI edits
applying and message fan-out remain untraced. Call joining now has a user-action
trace; see below.
+- `email_service` wraps its routes in tower-http's default `TraceLayer`, not
+ `macro_tower_layers`. Its request span is DEBUG level, below the INFO trace
+ filter. The span also ignores `traceparent`, so browser traces of email_service
+ requests end at the `http` client span. The gap is read from the code and not
+ yet confirmed in Tempo.
+- With `ENABLE_BEARER_TOKEN_AUTH` (Playwright e2e and the native test runner),
+ `fetchWithAuth` awaits the API token before `safeFetch`. Its `http` client spans
+ then start outside the calling span and root their own traces.
## Account WebSocket sessions
@@ -124,6 +132,30 @@ calls similarly launch `start_channel_call` for recording, transcription, and
recipient notifications; these run concurrently outside the token response path.
A slow recorder or push provider should not hold the creator on Connecting.
+## Email From switch
+
+The composer's From switch moves a saved draft to an inbox on another account.
+Search Tempo for `{ name="email.draft_transfer" }`. One browser trace covers the
+move:
+
+| Span | What it measures |
+| --- | --- |
+| `email.draft_transfer.save` | The save before the move. A retry of an unanswered move skips it. |
+| `email.draft_transfer.request` | The transfer until the server commits or refuses it. `email.draft_transfer.committed_by` is `response` or `recovery`. |
+| `email.draft_transfer.recover` | The recovery request after the transfer request failed or lost its response. |
+| `email.draft_transfer.refresh` | The detached refresh of both threads' caches. It can end after the root. |
+
+The root's attributes use the `email.draft_transfer.` prefix. They are
+`draft_id`, `operation_id`, `source_inbox_id`, `destination_inbox_id`,
+`destination_provider`, `attachment_count`, `retry`, and `outcome`. The outcome
+is `moved`, `aborted`, `failed`, `rejected`, or `skipped`. Aborted and failed
+moves are errors. A rejection is not an error. It adds `rejection`, which is
+`pending_other_inbox`, `attachment_limit`, or `unconfirmed_draft`. A retry shares
+the first attempt's `operation_id`, so search by it to join attempts across
+traces. Errors carry fixed messages. Never add addresses, subjects, bodies, or
+file names. The `http POST` spans carry `traceparent`, but email_service does not
+join the trace yet (see known gaps).
+
## Agent sessions
A session's lifetime is reconstructable from these spans. All of them carry
diff --git a/docs/architecture/email.md b/docs/architecture/email.md
index b9fc4360ba..aebe13c95c 100644
--- a/docs/architecture/email.md
+++ b/docs/architecture/email.md
@@ -592,7 +592,12 @@ but the panel stays silent for routine delivery: it lists a send only while it
waits on this device, needs attention, or is scheduled. Thread surfaces project
approved immediate sends from the journal as sent messages
(`email-thread/primitives/optimistic-send.ts`) until the thread read shows them,
-and read the thread once when delivery is confirmed.
+and read the thread once when delivery is confirmed. Every surface reads one
+document-scoped journal snapshot (`queries/email/queued-sends.ts`). The outbox
+session reads it at sign-in and clears it on account change, the first mounted
+observer starts its watcher and poll, and Send refreshes it before the thread
+opens, so that thread mounts with the send already projected instead of its
+draft.
Deploy schema/migrations and all generation-aware backend writers before
releasing this frontend, including before applying `ios-update`: that workflow