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): recover first-use offline drafts in discovery (#8504)

Peter Chinman9a905a33a92b
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index b241124d18..9c2ead38c3 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -294,6 +294,9 @@ the user's newest account for that app from the last fifteen minutes.
- Always persist composer sends in account-scoped IndexedDB and dispatch through the fetch-only email client, without a feature flag; cache health and unrelated mutation queues must not gate delivery. See `docs/architecture/email.md` for state and rollout invariants.
- Retry cache bootstrap on reconnect/foreground or draft Retry only when storage was proven untouched; retain the same scope and block draft sync until the replacement queue is readable.
- Touch email replies and forwards use the full-screen composer with the shared new-email header actions; preserve thread state underneath and flush local edits before closing.
+- Include unsynced email working copies in Drafts and mobile name search even
+ before a GraphQL save, and warm sending accounts alongside backfill. Preserve
+ inbox, alias, and facet scope.
- Draft autosaves preserve active email thread messages; evict inactive legacy
caches on save and the active cache on thread exit. Revalidate GraphQL thread
pages only when a save cannot patch the message list (missing snapshot or a
diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.md
index ba5068f2ea..034515b365 100644
--- a/apps/web/docs/graphql-normalized-cache-plan.md
+++ b/apps/web/docs/graphql-normalized-cache-plan.md
@@ -933,9 +933,16 @@ message bodies are excluded. The frontend materializes only matched thread keys
with `EmailQuickAccessFields` and uses the projection text for ranking and pending
query filtering; cache hydration, visibility, and deletion changes refresh rows.
Desktop Command K explicitly excludes the email bucket; mobile Search includes it.
-
-Email Quick Access requires the existing `enable-graphql-soup` rollout and a healthy
-normalized cache; the legacy REST sources do not supply email Quick Access rows.
+Unsynced email working copies merge into that bucket before any normalized
+thread exists, using the same account-scoped recovery source as Drafts. Local
+subjects take precedence over stale cached copies; sync retires the recovery row.
+The backfill leader also warms `MailAccounts` concurrently with paged hydration
+so first-use offline composition can resolve sender ownership and aliases.
+
+Normalized email Quick Access results require the existing `enable-graphql-soup`
+rollout and a healthy normalized cache; local recovery rows remain available while
+that rollout is enabled even if the cache host is unavailable. The legacy REST
+sources do not supply email Quick Access rows.
Quick Access observes flag loading reactively so a cold launch can attach the cache
after PostHog responds. For a local native preview without PostHog configuration,
build with `VITE_ENABLE_GRAPHQL_SOUP=true` to exercise this path; do not change the
diff --git a/apps/web/src/features/block-email/component/Block.tsx b/apps/web/src/features/block-email/component/Block.tsx
index 50ed463f1d..c7f42586f5 100644
--- a/apps/web/src/features/block-email/component/Block.tsx
+++ b/apps/web/src/features/block-email/component/Block.tsx
@@ -79,6 +79,7 @@ export default function BlockEmail() {
result={threadLoadResult}
notificationSource={notificationSource}
threadId={threadId()}
+ isLocalDraft={source.isLocalDraft()}
linkId={threadData()?.link_id}
debounceTime={100}
onRetry={() => fireAndForget(threadQuery.refetch(), 'email-thread')}
diff --git a/apps/web/src/features/block-email/component/EmailThreadLoadGate.test.tsx b/apps/web/src/features/block-email/component/EmailThreadLoadGate.test.tsx
index c672788403..4b32d9eadd 100644
--- a/apps/web/src/features/block-email/component/EmailThreadLoadGate.test.tsx
+++ b/apps/web/src/features/block-email/component/EmailThreadLoadGate.test.tsx
@@ -1,10 +1,11 @@
+import type { LocalDraft } from '@app/features/email-compose/core/local-draft';
import { createEmailThreadSource } from '@app/features/email-thread/queries/thread-source';
import type { EntityLoadError } from '@core/component/EntityLoadGate';
import type { ThreadQueryData, ThreadQueryResult } from '@queries/email/thread';
import type { ApiThread } from '@service-email/generated/schemas';
import { cleanup, render, screen } from '@solidjs/testing-library';
import { batch, createSignal, onCleanup, onMount } from 'solid-js';
-import { afterEach, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import {
EmailThreadLoadGate,
type EmailThreadLoadGateProps,
@@ -14,6 +15,11 @@ const markers = vi.hoisted(() => ({
mounts: [] as string[],
releases: [] as string[],
}));
+const localDrafts = vi.hoisted(() => vi.fn<() => LocalDraft[]>(() => []));
+vi.mock('@queries/email/local-draft-source', () => ({
+ createLocalDraftSource: () => ({ drafts: localDrafts, ready: () => true }),
+}));
+beforeEach(() => localDrafts.mockReset().mockReturnValue([]));
vi.mock('@notifications', () => ({
EmailDebouncedReadMarker: (props: { threadId: string; linkId?: string }) => {
const id = props.threadId;
@@ -32,11 +38,81 @@ vi.mock('@core/mobile/native-network-status', () => ({
vi.mock('@core/component/AccessErrorViews/NotFound', () => ({
default: () => <div>Not found</div>,
}));
+vi.mock('@core/component/AccessErrorViews/Unauthorized', () => ({
+ default: () => <div>Access denied</div>,
+}));
vi.mock('@core/component/LoadingBlock', () => ({
LoadingBlock: () => <div>Loading</div>,
}));
afterEach(cleanup);
+it('opens an unqueued local draft after a server 404 without overriding access errors or confirmed deletion', () => {
+ const [draft, setDraft] = createSignal<LocalDraft>({
+ key: 'local-draft',
+ draftId: 'local-draft',
+ threadId: 'local-thread',
+ accountId: 'owner',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ content: { subject: 'Recovered subject', body_html: btoa('Saved body') },
+ attachments: [],
+ status: 'dirty',
+ updatedAt: Date.now(),
+ });
+ localDrafts.mockImplementation(() => [draft()]);
+ const [error, setError] = createSignal<EntityLoadError>('NOT_FOUND');
+ render(() => {
+ const source = createEmailThreadSource(() => 'local-thread', {
+ transport: 'graphql',
+ resolvedThreadId: 'local-thread',
+ isError: true,
+ isSuccess: false,
+ isLoading: false,
+ data: undefined,
+ } as ThreadQueryResult<ThreadQueryData>);
+ return (
+ <EmailThreadLoadGate
+ result={{ data: source.thread, error, isPending: source.isLoading }}
+ isLocalDraft={source.isLocalDraft()}
+ threadId="local-thread"
+ notificationSource={
+ {} as EmailThreadLoadGateProps<ApiThread>['notificationSource']
+ }
+ onRetry={() => {}}
+ >
+ <input
+ aria-label="Subject"
+ value={source.thread()?.messages[0].subject ?? ''}
+ />
+ </EmailThreadLoadGate>
+ );
+ });
+ expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe(
+ 'Recovered subject'
+ );
+ expect(screen.queryByTestId('read-marker')).toBeNull();
+ expect(screen.queryByText('Not found')).toBeNull();
+
+ setError('FORBIDDEN');
+ expect(screen.queryByRole('textbox')).toBeNull();
+ setError('NOT_FOUND');
+ expect(screen.getByRole('textbox')).toBeTruthy();
+
+ // Once the server has acknowledged the thread, a later 404 is authoritative.
+ setDraft({ ...draft(), serverThreadId: 'server-thread' });
+ expect(screen.queryByRole('textbox')).toBeNull();
+ expect(screen.getByText('Not found')).toBeTruthy();
+ // Editing a previously saved draft also proves a server identity even if
+ // its working copy has not separately recorded the server thread ID yet.
+ setDraft({
+ ...draft(),
+ serverThreadId: undefined,
+ serverDraftId: 'server-draft',
+ });
+ expect(screen.queryByRole('textbox')).toBeNull();
+});
+
it('clears the previous thread and read marker when a reused host navigates', () => {
const [route, setRoute] = createSignal('first');
const [pending, setPending] = createSignal(false);
diff --git a/apps/web/src/features/block-email/component/EmailThreadLoadGate.tsx b/apps/web/src/features/block-email/component/EmailThreadLoadGate.tsx
index 35f35aaf65..ed271278b2 100644
--- a/apps/web/src/features/block-email/component/EmailThreadLoadGate.tsx
+++ b/apps/web/src/features/block-email/component/EmailThreadLoadGate.tsx
@@ -13,6 +13,8 @@ export type EmailThreadLoadGateProps<Data> = ParentProps<{
typeof EmailDebouncedReadMarker
>['notificationSource'];
threadId: string;
+ /** An account-owned working copy whose thread has never been confirmed. */
+ isLocalDraft?: boolean;
linkId?: string;
debounceTime?: number;
onRetry: () => void;
@@ -22,12 +24,16 @@ export type EmailThreadLoadGateProps<Data> = ParentProps<{
export function EmailThreadLoadGate<Data>(
props: EmailThreadLoadGateProps<Data>
) {
+ const error = () => {
+ const error = props.result.error();
+ return error === 'NOT_FOUND' && props.isLocalDraft ? undefined : error;
+ };
return (
<Suspense fallback={<ContentLoading />}>
<EntityLoadGate
result={{
data: props.result.data,
- error: props.result.error,
+ error,
// Hosts supply identity-checked data from createEmailThreadSource.
// Keep that composer's data during server-ID adoption; navigation to
// another thread clears it and restores the loading state.
@@ -35,12 +41,12 @@ export function EmailThreadLoadGate<Data>(
// no data or error yet, the email is still waiting to load.
isPending: () =>
props.result.data() === undefined &&
- (props.result.isPending() || props.result.error() === undefined),
+ (props.result.isPending() || error() === undefined),
}}
loadErrorTitle="Unable to load this email"
onRetry={props.onRetry}
>
- <Show when={props.threadId} keyed>
+ <Show when={!props.isLocalDraft && props.threadId} keyed>
{(threadId) => (
<EmailDebouncedReadMarker
notificationSource={props.notificationSource}
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 4c43007f3d..0572628bac 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts
@@ -373,11 +373,15 @@ export function createEmailComposer(props: EmailComposerOptions) {
operation: 'save' | 'delete'
) {
props.notices.reportError(error);
+ const failureMessage =
+ operation === 'save' && props.drafts.saveLocalDraft
+ ? 'Draft could not be synced'
+ : `Failed to ${operation} draft`;
if (!session.serverConfirmed()) {
// A best-effort pre-send save may fail while delivery still succeeds.
// Background saves and explicit draft actions report their own failure.
if (schedule?.pending() || !submitting()) {
- props.notices.feedback.failure(`Failed to ${operation} draft`);
+ props.notices.feedback.failure(failureMessage);
}
return;
}
@@ -405,7 +409,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
return;
}
}
- props.notices.feedback.failure(`Failed to ${operation} draft`);
+ props.notices.feedback.failure(failureMessage);
}
function handleAlreadySent() {
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 6106dcd39d..9d253a5690 100644
--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts
@@ -626,11 +626,15 @@ export function createReplyComposer(
operation: 'save' | 'delete'
) {
props.notices.reportError(error);
+ const failureMessage =
+ operation === 'save' && props.drafts.saveLocalDraft
+ ? 'Draft could not be synced'
+ : `Failed to ${operation} draft`;
if (!session.serverConfirmed()) {
// A best-effort pre-send save may fail while delivery still succeeds.
// Background saves and explicit draft actions report their own failure.
if (schedule?.pending() || !submitting()) {
- props.notices.feedback.failure(`Failed to ${operation} draft`);
+ props.notices.feedback.failure(failureMessage);
}
return;
}
@@ -651,7 +655,7 @@ export function createReplyComposer(
);
return;
}
- props.notices.feedback.failure(`Failed to ${operation} draft`);
+ props.notices.feedback.failure(failureMessage);
}
// Reset notifications must not autosave the draft that was just discarded.
diff --git a/apps/web/src/features/email-thread/queries/offline-reply.test.ts b/apps/web/src/features/email-thread/queries/offline-reply.test.ts
index febd33900a..f4ff12255e 100644
--- a/apps/web/src/features/email-thread/queries/offline-reply.test.ts
+++ b/apps/web/src/features/email-thread/queries/offline-reply.test.ts
@@ -5,7 +5,7 @@ import {
saveLocalDraft,
} from '@queries/email/local-drafts';
import type { ThreadQueryData, ThreadQueryResult } from '@queries/email/thread';
-import { createMemo, createRoot } from 'solid-js';
+import { createEffect, createMemo, createRoot } from 'solid-js';
import { afterEach, expect, it, vi } from 'vitest';
import { decodeBase64Utf8 } from '../../email-compose/core/decode-base64';
import { createComposeContext } from '../../email-compose/tests/capabilities';
@@ -104,3 +104,45 @@ it.each([false, true])(
}
}
);
+
+it('reopens a first-use local draft without sender metadata or any server thread', async () => {
+ await saveLocalDraft({
+ clientHandles: { draftId: 'first-draft', threadId: 'first-thread' },
+ draft: {
+ subject: 'First offline draft',
+ body_html: btoa('<p>Keep this text</p>'),
+ },
+ attachments: [],
+ });
+ await localDraftStore.close();
+ const loaded = Promise.withResolvers<void>();
+ const reopened = createRoot((dispose) => {
+ const source = createEmailThreadSource(() => 'first-thread', {
+ transport: 'graphql',
+ isSuccess: false,
+ isError: false,
+ isLoading: true,
+ resolvedThreadId: 'first-thread',
+ get data() {
+ throw new Error('Pending remote thread must not suspend recovery');
+ },
+ } as ThreadQueryResult<ThreadQueryData>);
+ createEffect(() => {
+ if (source.thread()) loaded.resolve();
+ });
+ return { source, dispose };
+ });
+ try {
+ await loaded.promise;
+ expect(reopened.source.thread()?.messages).toHaveLength(1);
+ expect(reopened.source.isLoading()).toBe(false);
+ expect(reopened.source.thread()?.messages[0]).toMatchObject({
+ db_id: 'first-draft',
+ subject: 'First offline draft',
+ body_html_sanitized: btoa('<p>Keep this text</p>'),
+ });
+ expect(reopened.source.thread()?.link_id).toBe('');
+ } finally {
+ reopened.dispose();
+ }
+});
diff --git a/apps/web/src/features/email-thread/queries/thread-source.ts b/apps/web/src/features/email-thread/queries/thread-source.ts
index ccfb1d52d8..0bcd801b89 100644
--- a/apps/web/src/features/email-thread/queries/thread-source.ts
+++ b/apps/web/src/features/email-thread/queries/thread-source.ts
@@ -110,7 +110,7 @@ export function toEmailThread(thread: ApiThread): EmailThread {
export function createEmailThreadSource(
threadId: Accessor<string>,
query: ThreadQueryResult<ThreadQueryData>
-): EmailThreadSource {
+): EmailThreadSource & { isLocalDraft: Accessor<boolean> } {
// Status guards prevent a pending Solid resource from suspending its owner.
const snapshot = createMemo<{ requested: string; thread?: EmailThread }>(
(previous) => {
@@ -230,6 +230,22 @@ export function createEmailThreadSource(
return {
id: () => thread()?.db_id ?? query.resolvedThreadId ?? threadId(),
thread,
+ // A first-use working copy may not have reached the mutation queue, so
+ // its temporary thread ID can still return NOT_FOUND from the server.
+ isLocalDraft: () =>
+ query.transport === 'graphql' &&
+ query.resolvedThreadId === threadId() &&
+ !!thread() &&
+ local
+ .drafts()
+ .some(
+ (draft) =>
+ draft.threadId === threadId() &&
+ !draft.serverDraftId &&
+ !draft.serverThreadId &&
+ !draft.content.replying_to_id &&
+ draft.status !== 'synced'
+ ),
isError: () =>
query.isError && (query.transport !== 'graphql' || !thread()),
isLoading: () =>
diff --git a/apps/web/src/features/email-view/components/EmailDetailView.tsx b/apps/web/src/features/email-view/components/EmailDetailView.tsx
index 479701b1c3..ccb44731a3 100644
--- a/apps/web/src/features/email-view/components/EmailDetailView.tsx
+++ b/apps/web/src/features/email-view/components/EmailDetailView.tsx
@@ -272,6 +272,7 @@ export function EmailDetailView(props: {
tabIndex={-1}
>
<EmailThreadLoadGate
+ isLocalDraft={source.isLocalDraft()}
result={loadResult}
notificationSource={notificationSource}
threadId={props.thread.id}
diff --git a/apps/web/src/features/email-view/queries/use-email-query.test.ts b/apps/web/src/features/email-view/queries/use-email-query.test.ts
index cc12082dae..e888ec7c4a 100644
--- a/apps/web/src/features/email-view/queries/use-email-query.test.ts
+++ b/apps/web/src/features/email-view/queries/use-email-query.test.ts
@@ -1,3 +1,4 @@
+import type { LocalDraft } from '@app/features/email-compose/core/local-draft';
import type { EmailEntity } from '@entity/types/entity';
import {
type SoupAstItemsQuery,
@@ -15,6 +16,15 @@ import {
useEmailDataSource,
} from './use-email-query';
+const localDrafts = vi.hoisted(() => ({ read: (): LocalDraft[] => [] }));
+vi.mock('@queries/email/local-draft-source', async () => ({
+ ...(await import('@queries/email/local-draft-entities')),
+ createLocalDraftSource: (enabled: () => boolean) => ({
+ drafts: () => (enabled() ? localDrafts.read() : []),
+ ready: () => true,
+ }),
+}));
+
const searchQueryMock = vi.hoisted(() => vi.fn());
const favoritesQueryMock = vi.hoisted(() => vi.fn());
vi.mock('@queries/favorites/favorites', () => ({
@@ -386,6 +396,7 @@ describe('Email list query transitions', () => {
expect(root.source.isLoading()).toBe(false);
});
beforeEach(() => {
+ localDrafts.read = () => [];
vi.clearAllMocks();
favoritesQueryMock.mockReturnValue({
isSuccess: true,
@@ -850,3 +861,160 @@ vi.mock('./use-reminder-email-source', () => ({
refresh: async () => {},
}),
}));
+
+it('recovers a first-use draft before remote discovery and preserves mailbox/search scope', () => {
+ const [copies, setCopies] = createSignal<LocalDraft[]>([
+ {
+ key: 'local-draft',
+ draftId: 'local-draft',
+ threadId: 'local-thread',
+ accountId: 'alice',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ content: { subject: 'Offline receipt' },
+ attachments: [],
+ status: 'dirty',
+ updatedAt: 1,
+ },
+ ]);
+ localDrafts.read = copies;
+ const state = mount();
+ state.setState({ tab: 'drafts', inboxIds: undefined });
+ state.setLoading(true);
+ expect(ids(state.source)).toEqual(['local-thread']);
+ expect(state.source.isLoading()).toBe(false);
+ state.setState('inboxIds', ['inbox-a']);
+ expect(ids(state.source)).toEqual([]);
+ setCopies([
+ { ...copies()[0], inboxId: 'inbox-a', senderEmail: '[email protected]' },
+ ]);
+ expect(ids(state.source)).toEqual(['local-thread']);
+ state.setState('aliasFilter', {
+ inboxId: 'inbox-a',
+ emailAddress: '[email protected]',
+ });
+ expect(ids(state.source)).toEqual([]);
+ state.setState('aliasFilter', undefined);
+ state.setState('search', 'receipt');
+ expect(ids(state.source)).toContain('local-thread');
+ state.setState('search', 'unrelated');
+ expect(ids(state.source)).not.toContain('local-thread');
+ state.setState({ search: '', facets: { read: ['unread'] } });
+ expect(ids(state.source)).toEqual([]);
+ state.setState({ facets: {}, tab: 'sent' });
+ expect(ids(state.source)).toEqual([]);
+ state.setState('tab', 'drafts');
+ state.setLoading(false);
+ state.setEntities([{ ...email('local-thread'), isDraft: true }]);
+ expect(ids(state.source)).toEqual(['local-thread']);
+ expect(
+ state.source.items().find((row) => row.kind === 'entity')?.entity.name
+ ).toBe('Offline receipt');
+ setCopies([{ ...copies()[0], status: 'synced', acknowledgedRevision: 1 }]);
+ expect(ids(state.source)).toEqual(['local-thread']);
+});
+
+it('keeps confirmed thread flags when a local reply supplies newer draft text', () => {
+ localDrafts.read = () => [
+ {
+ key: 'reply',
+ draftId: 'reply',
+ threadId: 'thread',
+ accountId: 'alice',
+ inboxId: 'inbox-a',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ content: { subject: 'Local reply' },
+ attachments: [],
+ status: 'dirty',
+ updatedAt: 1,
+ },
+ ];
+ const state = mount();
+ state.setState('tab', 'drafts');
+ state.setEntities([
+ {
+ ...email('thread'),
+ isDraft: true,
+ isRead: false,
+ done: true,
+ isImportant: true,
+ isSignal: false,
+ },
+ ]);
+ state.setState('facets', { read: ['unread'], done: ['done'] });
+ expect(ids(state.source)).toEqual(['thread']);
+ expect(
+ state.source.items().find((row) => row.kind === 'entity')?.entity
+ ).toMatchObject({
+ name: 'Local reply',
+ isRead: false,
+ done: true,
+ isImportant: true,
+ isSignal: false,
+ });
+});
+
+it('does not resurrect a filtered thread with synthetic local draft flags', () => {
+ localDrafts.read = () => [
+ {
+ key: 'reply',
+ draftId: 'reply',
+ threadId: 'thread',
+ accountId: 'alice',
+ inboxId: 'inbox-a',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ content: { subject: 'Local reply' },
+ attachments: [],
+ status: 'dirty',
+ updatedAt: 1,
+ },
+ ];
+ const state = mount();
+ state.setState({ tab: 'drafts', facets: { done: ['not-done'] } });
+ state.setDiscoveryEntities([]);
+ state.setRetainedEntities([
+ { ...email('thread'), isDraft: true, done: true },
+ ]);
+ expect(ids(state.source)).toEqual([]);
+ state.setState('facets', { done: ['done'] });
+ expect(ids(state.source)).toEqual(['thread']);
+});
+
+it('retains a remote body-search match when its local draft subject does not match', () => {
+ localDrafts.read = () => [
+ {
+ key: 'reply',
+ draftId: 'reply',
+ threadId: 'thread',
+ accountId: 'alice',
+ inboxId: 'inbox-a',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ content: { subject: 'Weekly update' },
+ attachments: [],
+ status: 'dirty',
+ updatedAt: 1,
+ },
+ ];
+ const state = mount('invoice');
+ state.setState('tab', 'all');
+ state.setSearchEntities([
+ {
+ ...email('thread'),
+ name: 'Weekly update',
+ snippet: 'Your invoice is attached',
+ },
+ ]);
+ expect(ids(state.source)).toEqual(['thread']);
+ expect(
+ state.source.items().find((row) => row.kind === 'entity')?.entity
+ ).toMatchObject({
+ snippet: 'Your invoice is attached',
+ });
+});
diff --git a/apps/web/src/features/email-view/queries/use-email-query.ts b/apps/web/src/features/email-view/queries/use-email-query.ts
index b947106f4e..48c168d378 100644
--- a/apps/web/src/features/email-view/queries/use-email-query.ts
+++ b/apps/web/src/features/email-view/queries/use-email-query.ts
@@ -15,12 +15,17 @@ import { withEntityNotifications } from '@app/features/soup/entity-notifications
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { useUserId } from '@core/context/user';
import { arrayEquals } from '@core/util/compareUtils';
+import { matchesTokenSubsequences } from '@core/util/string';
import {
type EmailEntity,
type EntityData,
isEmailEntity,
type WithNotification,
} from '@entity';
+import {
+ createLocalDraftSource,
+ localDraftEntities,
+} from '@queries/email/local-draft-source';
import { useFavoritesQuery } from '@queries/favorites/favorites';
import { useSoupAstItemsQuery } from '@queries/soup/items';
import { useSearchSoupQuery } from '@queries/soup/search';
@@ -155,6 +160,9 @@ export function useEmailDataSource(
const query = useSoupAstItemsQuery(queryArgs, () => ({
enabled: sourceEnabled(),
}));
+ const localDrafts = createLocalDraftSource(
+ () => query.transport === 'graphql'
+ );
const isListPending = () =>
!filtersReady() || query.isPending || query.isPlaceholderData;
@@ -175,8 +183,7 @@ export function useEmailDataSource(
return selected;
};
- // The quick-access pool behind local search holds no email threads, so
- // every search result comes from the search service.
+ // Mail search retains server relevance; recoverable local drafts are merged below.
const search = createSearchState({
surface: () => 'email',
text: () => state.search,
@@ -398,7 +405,82 @@ export function useEmailDataSource(
},
{ scope: '', items: [], resolved: new Map() }
);
- const entities = () => publication().items;
+ // Working copies can exist before sender metadata allows a GraphQL save.
+ // Keep them discoverable without waiting for the remote list/search.
+ const recoverable = () =>
+ state.tab === 'drafts' || (state.tab === 'all' && !!state.search.trim())
+ ? localDraftEntities(localDrafts.drafts()).filter(
+ (email) => email.ownerId === userId()
+ )
+ : [];
+ // Resolve recovery threads independently of the active filters. Otherwise an
+ // excluded thread could reappear with the synthetic first-use draft flags.
+ const recoveryBatches = createMemo(() =>
+ emailAdmissionBatches(recoverable())
+ );
+ const recoveryQueries = indexArray(recoveryBatches, (ids) =>
+ useSoupAstItemsQuery(
+ () => ({
+ ...buildEmailQuery(
+ {
+ tab: 'all',
+ inboxIds: undefined,
+ facets: {},
+ facetContext: facetContext(),
+ },
+ ids()
+ ),
+ transport: 'graphql',
+ }),
+ () => ({ enabled: sourceEnabled(), keepPreviousData: false })
+ )
+ );
+ const localRows = () => {
+ if (!filtersReady()) return [];
+ const remote = new Map(
+ [
+ ...recoveryQueries().flatMap((query) =>
+ !query.isPending && !query.isPlaceholderData
+ ? (query.data?.entities.filter(isEmailEntity) ?? [])
+ : []
+ ),
+ ...rawEntities().filter(isEmailEntity),
+ ...publication().items,
+ ].map((email) => [email.id, email])
+ );
+ return recoverable()
+ .map((email) => {
+ const confirmed = remote.get(email.id);
+ return confirmed
+ ? {
+ ...confirmed,
+ name: email.name,
+ snippet: email.snippet,
+ updatedAt: email.updatedAt,
+ }
+ : email;
+ })
+ .filter(
+ (email) =>
+ email.ownerId === userId() &&
+ (!state.inboxIds?.length ||
+ (!!email.linkId && state.inboxIds.includes(email.linkId))) &&
+ (!state.aliasFilter ||
+ (email.linkId === state.aliasFilter.inboxId &&
+ email.senderEmail?.toLowerCase() ===
+ state.aliasFilter.emailAddress.toLowerCase())) &&
+ testFacets(state.facets, EMAIL_FACETS, email, facetContext()) &&
+ matchesTokenSubsequences(email.name, state.search.trim())
+ );
+ };
+ const entities = () => {
+ const recovered = localRows();
+ const ids = new Set(recovered.map((email) => email.id));
+ return [
+ ...recovered,
+ ...publication().items.filter((email) => !ids.has(email.id)),
+ ];
+ };
const listEntities = createMemo((): WithNotification<EntityData>[] =>
entities().map((email) =>
@@ -464,6 +546,7 @@ export function useEmailDataSource(
const items = createSoupRowStore(builtItems);
const isLoading = () => {
+ if (localRows().length > 0) return false;
if (search.isSearching() && showsFavorites() && favorites.isError)
return false;
if (!filtersReady()) return true;
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
index 49ed3472ee..466e58498f 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
@@ -1,3 +1,4 @@
+import type { LocalDraft } from '@app/features/email-compose/core/local-draft';
import type {
CrmCompanyEntity,
CrmContactEntity,
@@ -44,6 +45,14 @@ import {
type QuickAccessListOptions,
} from './types';
+const localDrafts = vi.hoisted(() => ({ read: (): LocalDraft[] => [] }));
+vi.mock('@queries/email/local-draft-source', async () => ({
+ createLocalDraftSource: (enabled: () => boolean) => ({
+ drafts: () => (enabled() ? localDrafts.read() : []),
+ ready: () => true,
+ }),
+}));
+
const mocks = vi.hoisted(() => ({
search: vi.fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>(),
history: [] as HistoryItem[],
@@ -235,6 +244,7 @@ function page(start: number, count: number, more = false): SearchCachePage {
};
}
beforeEach(() => {
+ localDrafts.read = () => [];
vi.clearAllMocks();
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
mocks.history = [];
@@ -1423,3 +1433,106 @@ describe('database command discovery', () => {
expect(mocks.history).toEqual([]);
});
});
+
+it('finds an unqueued first-use draft by title without a cached thread and retires it after sync', async () => {
+ const [copies, setCopies] = createSignal<LocalDraft[]>([
+ {
+ key: 'local-draft',
+ draftId: 'local-draft',
+ threadId: 'local-thread',
+ accountId: 'viewer',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ content: { subject: 'Offline receipt' },
+ attachments: [],
+ status: 'dirty',
+ updatedAt: 1,
+ },
+ ]);
+ localDrafts.read = copies;
+ const [term, setTerm] = createSignal('receipt');
+ const { source, list, notes } = setup((source) => ({
+ source,
+ list: source.useList({ buckets: ['email'], searchTerm: term }),
+ notes: source.useList({ buckets: ['note'], searchTerm: term }),
+ }));
+ expect(list.items().map((item) => item.id)).toEqual(['local-thread']);
+ expect(source.getById('local-thread')?.data.name).toBe('Offline receipt');
+ expect(notes.items()).toEqual([]);
+ setTerm('unrelated');
+ expect(list.items()).toEqual([]);
+ setTerm('receipt');
+ setCopies([{ ...copies()[0], status: 'synced', acknowledgedRevision: 1 }]);
+ expect(list.items()).toEqual([]);
+ expect(source.getById('local-thread')).toBeUndefined();
+});
+
+it('keeps a cached sender hit when the same thread has an unmatched local draft', async () => {
+ localDrafts.read = () => [
+ {
+ key: 'reply',
+ draftId: 'reply',
+ threadId: 'thread-1',
+ accountId: 'viewer',
+ generation: 'generation',
+ revision: 1,
+ acknowledgedRevision: 0,
+ content: { subject: 'Weekly update' },
+ attachments: [],
+ status: 'dirty',
+ updatedAt: 1,
+ },
+ ];
+ mocks.search.mockResolvedValue({
+ documents: [
+ {
+ profile: 'quick-access-v1',
+ recordKey: 'GraphqlSoupEmailThread:thread-1',
+ bucket: 'email',
+ searchText: 'weekly update | teo | [email protected]',
+ timestampMs: 1,
+ sourceHash: 'hash',
+ },
+ ],
+ nextCursor: null,
+ });
+ mocks.readRecordsByKeys.mockResolvedValue({
+ revision: INITIAL_CACHE_REVISION,
+ records: [
+ {
+ recordKey: 'GraphqlSoupEmailThread:thread-1',
+ record: {
+ __typename: 'GraphqlSoupEmailThread',
+ id: 'thread-1',
+ name: 'Weekly update',
+ ownerId: 'viewer',
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ viewedAt: null,
+ senderName: 'Teo',
+ senderEmail: '[email protected]',
+ linkId: 'inbox',
+ isRead: true,
+ isDraft: false,
+ isImportant: false,
+ inboxVisible: true,
+ },
+ },
+ ],
+ });
+ const loaded = Promise.withResolvers<void>();
+ const list = setup((source) => {
+ const list = source.useList({
+ buckets: ['email'],
+ searchTerm: () => 'teo',
+ });
+ createRenderEffect(() => {
+ if (!list.isLoading()) loaded.resolve();
+ });
+ return list;
+ });
+ await loaded.promise;
+ expect(list.items().map((item) => item.id)).toEqual(['thread-1']);
+ expect(list.items()[0].searchText).toContain('[email protected]');
+});
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
index f62caa39c9..3b6adde14a 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
@@ -39,7 +39,11 @@ import {
type CachedGraphqlChannel,
materializeCachedGraphqlChannels,
} from '@queries/channel/graphql';
-import { materializeCachedEmailItems } from '@queries/email/quick-access';
+import { createLocalDraftSource } from '@queries/email/local-draft-source';
+import {
+ localDraftQuickAccessItems,
+ materializeCachedEmailItems,
+} from '@queries/email/quick-access';
import { queryReadyGate } from '@queries/gate';
import { materializeCachedGraphqlHistoryItems } from '@queries/history/graphql';
import { type HistoryItem, useHistoryQuery } from '@queries/history/history';
@@ -400,6 +404,10 @@ export function createQuickAccessValue(): QuickAccessContextValue {
const graphqlCacheHost = getGraphqlSoupCacheHost();
return graphqlCacheHost?.disabled ? undefined : graphqlCacheHost;
});
+ const localDrafts = createLocalDraftSource(() => graphqlFlag().enabled);
+ const draftItems = createMemo(() =>
+ localDraftQuickAccessItems(localDrafts.drafts())
+ );
const [manualRefreshRevision, setManualRefreshRevision] = createSignal(0);
const cachedChannelsQuery = useCachedGraphqlChannelsQuery(cacheHost);
createEffect(() => {
@@ -980,7 +988,9 @@ export function createQuickAccessValue(): QuickAccessContextValue {
});
const getById = (id: string): QuickAccessItem | undefined => {
- return itemCache.get(id)?.item;
+ return (
+ draftItems().find((item) => item.id === id) ?? itemCache.get(id)?.item
+ );
};
const resolveEntries = (entries: IndexEntry[]): QuickAccessItem[] => {
@@ -1094,7 +1104,10 @@ export function createQuickAccessValue(): QuickAccessContextValue {
}
}
- return resolveEntries(indices);
+ return [
+ ...(activeBuckets.includes('email') ? draftItems() : []),
+ ...resolveEntries(indices),
+ ];
});
const localItems = createLazyMemo(() =>
@@ -1237,8 +1250,15 @@ export function createQuickAccessValue(): QuickAccessContextValue {
// Search describes cached contents, not corpus completeness. Merge known
// rows before sorting recency so hydration cannot promote older items.
+ const matched = new Set(local);
+ const localDraftIds = new Set(
+ draftItems()
+ .filter((item) => matched.has(item))
+ .map((item) => item.id)
+ );
const ranked = projected
.items()
+ .filter((item) => !localDraftIds.has(item.id))
.map((item) => itemCache.get(item.id)?.item ?? item);
const seen = new Set(ranked.map((item) => item.id));
const combined = ranked.concat(
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index b43ee988af..f3263d7dee 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -123,7 +123,8 @@ describe('createTauriCacheHost', () => {
});
it('reports asynchronous native initialization failures', async () => {
- const onInitializationError = vi.fn();
+ const failed = Promise.withResolvers<Error>();
+ const onInitializationError = vi.fn(failed.resolve);
invokeMock.mockImplementation((command: string) =>
command === 'graphql_cache_init_with_schema'
? Promise.reject(new Error('init failed'))
@@ -135,9 +136,8 @@ describe('createTauriCacheHost', () => {
onInitializationError,
});
- await vi.waitFor(() =>
- expect(onInitializationError).toHaveBeenCalledOnce()
- );
+ await failed.promise;
+ expect(onInitializationError).toHaveBeenCalledOnce();
expect(onInitializationError).toHaveBeenCalledWith(
expect.objectContaining({ message: 'init failed' })
);
diff --git a/apps/web/src/lib/queries/email/local-draft-entities.ts b/apps/web/src/lib/queries/email/local-draft-entities.ts
new file mode 100644
index 0000000000..395c432042
--- /dev/null
+++ b/apps/web/src/lib/queries/email/local-draft-entities.ts
@@ -0,0 +1,46 @@
+import type { LocalDraft } from '@app/features/email-compose/core/local-draft';
+import type { EmailEntity } from '@entity';
+
+/** One conversation row, even when several local reply drafts share it. */
+export function localDraftEntities(
+ drafts: readonly LocalDraft[]
+): EmailEntity[] {
+ const rows = new Map<string, EmailEntity>();
+ for (const draft of drafts) {
+ if (
+ draft.status === 'synced' ||
+ (draft.status === 'deleting' &&
+ draft.queuedAttemptId &&
+ draft.queuedAttemptId === draft.latestAttemptId)
+ )
+ continue;
+ const id = draft.serverThreadId ?? draft.threadId ?? draft.key;
+ if (rows.has(id)) continue;
+ rows.set(id, {
+ type: 'email',
+ id,
+ name: draft.content.subject || 'Draft email',
+ ownerId: draft.accountId,
+ isRead: true,
+ isDraft: true,
+ isImportant: false,
+ isSignal: true,
+ done: false,
+ linkId: draft.inboxId,
+ senderEmail: draft.senderEmail,
+ participants: (draft.content.to ?? []).map((contact) => ({
+ email: contact.email,
+ name: contact.name ?? undefined,
+ })),
+ createdAt: new Date(draft.updatedAt),
+ updatedAt: new Date(draft.updatedAt),
+ snippet:
+ draft.status === 'failed' ||
+ draft.status === 'unconfirmed' ||
+ draft.status === 'delete-failed'
+ ? 'Saved on this device · Not synced'
+ : 'Saved on this device',
+ });
+ }
+ return [...rows.values()];
+}
diff --git a/apps/web/src/lib/queries/email/local-draft-source.ts b/apps/web/src/lib/queries/email/local-draft-source.ts
index 2082dfb864..02c64d1f12 100644
--- a/apps/web/src/lib/queries/email/local-draft-source.ts
+++ b/apps/web/src/lib/queries/email/local-draft-source.ts
@@ -4,7 +4,7 @@ import type {
QueryState,
} from '@app/features/next-soup/filters/filter-store/types';
import { fireAndForget } from '@core/util/fireAndForget';
-import type { EmailEntity } from '@entity';
+import { Telemetry } from '@macro-inc/observability';
import {
type Accessor,
createEffect,
@@ -16,6 +16,8 @@ import { authKeys } from '../auth/keys';
import { queryClient } from '../client';
import { listLocalDrafts, localDraftStore } from './local-drafts';
+export { localDraftEntities } from './local-draft-entities';
+
/** Account-scoped local data source; notifications are invalidations, never the truth. */
export function createLocalDraftSource(enabled: Accessor<boolean>) {
const [drafts, setDrafts] = createSignal<LocalDraft[]>([]);
@@ -29,13 +31,17 @@ export function createLocalDraftSource(enabled: Accessor<boolean>) {
setReady(true);
return;
}
+ const span = Telemetry.span('email.drafts.discover');
try {
const entries = await listLocalDrafts();
+ span.setAttr('email.draft_count', entries.length);
if (!disposed && request === generation)
setDrafts(entries.sort((a, b) => b.updatedAt - a.updatedAt));
} catch {
+ span.error('Unable to read local email drafts');
if (!disposed && request === generation) setDrafts([]);
} finally {
+ span.end();
if (!disposed && request === generation) setReady(true);
}
};
@@ -63,50 +69,6 @@ export function createLocalDraftSource(enabled: Accessor<boolean>) {
return { drafts: () => (enabled() ? drafts() : []), ready };
}
-/** One conversation row, even when several local reply drafts share it. */
-export function localDraftEntities(
- drafts: readonly LocalDraft[]
-): EmailEntity[] {
- const rows = new Map<string, EmailEntity>();
- for (const draft of drafts) {
- if (
- draft.status === 'synced' ||
- (draft.status === 'deleting' &&
- draft.queuedAttemptId &&
- draft.queuedAttemptId === draft.latestAttemptId)
- )
- continue;
- const id = draft.serverThreadId ?? draft.threadId ?? draft.key;
- if (rows.has(id)) continue;
- rows.set(id, {
- type: 'email',
- id,
- name: draft.content.subject || 'Draft email',
- ownerId: draft.accountId,
- isRead: true,
- isDraft: true,
- isImportant: false,
- isSignal: true,
- done: false,
- linkId: draft.inboxId,
- senderEmail: draft.senderEmail,
- participants: (draft.content.to ?? []).map((contact) => ({
- email: contact.email,
- name: contact.name ?? undefined,
- })),
- createdAt: new Date(draft.updatedAt),
- updatedAt: new Date(draft.updatedAt),
- snippet:
- draft.status === 'failed' ||
- draft.status === 'unconfirmed' ||
- draft.status === 'delete-failed'
- ? 'Saved on this device · Not synced'
- : 'Saved on this device',
- });
- }
- return [...rows.values()];
-}
-
/** Server email filters also apply to recovery rows, which never visit that server. */
export function localDraftMatchesFilters(
draft: LocalDraft,
diff --git a/apps/web/src/lib/queries/email/mail-accounts.ts b/apps/web/src/lib/queries/email/mail-accounts.ts
index da8529b41f..9d86c35c74 100644
--- a/apps/web/src/lib/queries/email/mail-accounts.ts
+++ b/apps/web/src/lib/queries/email/mail-accounts.ts
@@ -3,6 +3,7 @@ import { type Span, Telemetry } from '@macro-inc/observability';
import { MailAccountsDocument } from '@service-storage/graphql/generated/graphql';
import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
import { createRequest } from '@urql/core';
+import type { Accessor } from 'solid-js';
import { createLiveQuery } from '../../graphql-cache/solid/create-live-query';
/** Reconcile account edits with mounted composers and the durable catalog. */
@@ -49,11 +50,12 @@ export function refreshMailAccounts(parentSpan?: Span): Promise<void> {
/** One identity-scoped GraphQL catalog for inboxes and their verified senders.
* Alias failures are per inbox; a partial response still exposes healthy accounts. */
-export function useMailAccountsQuery() {
+export function useMailAccountsQuery(enabled: Accessor<boolean> = () => true) {
const query = createLiveQuery(
MailAccountsDocument,
() => ({}),
() => ({
+ enabled: enabled(),
client: getGraphqlSoupClient(),
requestPolicy: 'cache-and-network' as const,
select: (data) => ({
diff --git a/apps/web/src/lib/queries/email/quick-access.ts b/apps/web/src/lib/queries/email/quick-access.ts
index c39c070eb9..16ffadf789 100644
--- a/apps/web/src/lib/queries/email/quick-access.ts
+++ b/apps/web/src/lib/queries/email/quick-access.ts
@@ -1,3 +1,4 @@
+import type { LocalDraft } from '@app/features/email-compose/core/local-draft';
import type { EntityItem } from '@core/context/quickAccess/types';
import type { EmailEntity } from '@entity';
import {
@@ -7,6 +8,7 @@ import {
selectRecords,
} from '@graphql-cache/index';
import { EmailQuickAccessFieldsFragmentDoc } from '@service-storage/graphql/generated/graphql';
+import { localDraftEntities } from './local-draft-entities';
/** Materialize cached thread hits only; matching uses the projection's subject/sender text. */
export async function materializeCachedEmailItems(
@@ -63,3 +65,18 @@ export async function materializeCachedEmailItems(
];
});
}
+
+/** Unsynced working copies have no normalized thread/search record yet. */
+export function localDraftQuickAccessItems(
+ drafts: readonly LocalDraft[]
+): EntityItem<EmailEntity>[] {
+ return localDraftEntities(drafts).map((email) => ({
+ id: email.id,
+ kind: 'entity',
+ bucket: 'email',
+ searchText: [email.name, email.senderEmail].filter(Boolean).join(' '),
+ sortTimestamp: new Date(email.updatedAt ?? 0).getTime(),
+ timestamps: { updatedAt: email.updatedAt, createdAt: email.createdAt },
+ data: email,
+ }));
+}
diff --git a/apps/web/src/lib/queries/email/settings.test.ts b/apps/web/src/lib/queries/email/settings.test.ts
index ded7d4c422..807776b7d1 100644
--- a/apps/web/src/lib/queries/email/settings.test.ts
+++ b/apps/web/src/lib/queries/email/settings.test.ts
@@ -7,6 +7,7 @@ import type { MailAccountsQuery } from '@service-storage/graphql/generated/graph
import { QueryClient } from '@tanstack/solid-query';
import { type Client, createClient, fetchExchange } from '@urql/core';
import { ok } from 'neverthrow';
+import { createEffect, createRoot } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { emailKeys } from './keys';
import { useMailAccountsQuery } from './mail-accounts';
@@ -67,8 +68,9 @@ function accounts(signature: string, replySignature = true): MailAccountsQuery {
};
}
-function setupCatalog() {
- let stored: unknown = accounts('Old signature');
+function setupCatalog(initial: unknown = accounts('Old signature')) {
+ let stored: unknown = initial;
+ const persisted = Promise.withResolvers<void>();
let server = accounts('Old signature');
let offline = false;
let persistence: Promise<void> | undefined;
@@ -86,10 +88,14 @@ function setupCatalog() {
onCacheGenerationChanged: () => () => {},
onMutationSettled: () => () => {},
claimNextMutation: async () => undefined,
- readQuery: async () => ({ kind: 'hit', data: structuredClone(stored) }),
+ readQuery: async () =>
+ stored === null
+ ? { kind: 'miss' }
+ : { kind: 'hit', data: structuredClone(stored) },
writeQuery: async (args) => {
await persistence;
stored = structuredClone(args.data);
+ persisted.resolve();
return {
revision: INITIAL_CACHE_REVISION,
revisionAdvanced: false,
@@ -125,6 +131,7 @@ function setupCatalog() {
return {
fetch,
stored: () => stored,
+ persisted: persisted.promise,
setServer: (data: MailAccountsQuery) => {
server = data;
},
@@ -260,3 +267,33 @@ describe('email settings account reconciliation', () => {
});
});
});
+
+it('warms an empty sender catalog before first composition and reopens it offline', async () => {
+ const catalog = setupCatalog(null);
+ const disposeBackground = createRoot((dispose) => {
+ useMailAccountsQuery(() => true);
+ return dispose;
+ });
+ await catalog.persisted;
+ expect(catalog.stored()).toEqual(accounts('Old signature'));
+ disposeBackground();
+ catalog.goOffline();
+ catalog.newClient();
+ const composer = mountComposerAccounts();
+ const loaded = Promise.withResolvers<void>();
+ const stop = createRoot((dispose) => {
+ createEffect(() => {
+ if (composer.inboxes.inboxes().length) loaded.resolve();
+ });
+ return dispose;
+ });
+ try {
+ await loaded.promise;
+ expect(composer.inboxes.inboxes()[0]?.id).toBe('inbox-1');
+ expect(composer.inboxes.inboxes()[0]?.email_address).toBe(
+ );
+ } finally {
+ stop();
+ }
+});
diff --git a/apps/web/src/lib/queries/soup/backfill.test.tsx b/apps/web/src/lib/queries/soup/backfill.test.tsx
index 97d4af4617..90f6fe1756 100644
--- a/apps/web/src/lib/queries/soup/backfill.test.tsx
+++ b/apps/web/src/lib/queries/soup/backfill.test.tsx
@@ -30,6 +30,11 @@ const graphqlMocks = vi.hoisted(() => ({
hydrateGraphqlSoup: vi.fn(),
}));
+const mailAccounts = vi.hoisted(() => vi.fn());
+vi.mock('../email/mail-accounts', () => ({
+ useMailAccountsQuery: mailAccounts,
+}));
+
const leaderMocks = vi.hoisted(() => ({
createTabLeaderSignal: vi.fn(),
}));
@@ -1055,3 +1060,31 @@ describe('runSoupBackfills', () => {
expect(fetchSignals[1]?.aborted).toBe(true);
});
});
+
+it('warms sender metadata before paged backfill and pauses it without identity or leadership', () => {
+ const [user, setUser] = createSignal<string>();
+ const [leader, setLeader] = createSignal(true);
+ const [enabled, setEnabled] = createSignal(true);
+ featureFlagMocks.useFeatureFlag.mockReturnValue(() => ({
+ enabled: enabled(),
+ }));
+ leaderMocks.createTabLeaderSignal.mockReturnValue(leader);
+ mailAccounts.mockClear();
+ const rendered = render(() => {
+ useSoupBackfills(user);
+ return null;
+ });
+ try {
+ const active = mailAccounts.mock.calls[0][0];
+ expect(active()).toBe(false);
+ setUser('owner');
+ expect(active()).toBe(true);
+ setLeader(false);
+ expect(active()).toBe(false);
+ setLeader(true);
+ setEnabled(false);
+ expect(active()).toBe(false);
+ } finally {
+ rendered.unmount();
+ }
+});
diff --git a/apps/web/src/lib/queries/soup/backfill.ts b/apps/web/src/lib/queries/soup/backfill.ts
index e6e68065b4..362b3d7a80 100644
--- a/apps/web/src/lib/queries/soup/backfill.ts
+++ b/apps/web/src/lib/queries/soup/backfill.ts
@@ -24,6 +24,7 @@ import * as Effect from 'effect/Effect';
import * as Fiber from 'effect/Fiber';
import * as Schedule from 'effect/Schedule';
import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';
+import { useMailAccountsQuery } from '../email/mail-accounts';
// Bump when a default backfill input or completion guarantee changes so
// persisted cursors cannot retain an older hydration contract.
@@ -692,6 +693,15 @@ export function useSoupBackfills(userId: Accessor<string | undefined>): void {
const isLeader = createTabLeaderSignal(
`graphql-soup-backfill:v${BACKFILL_VERSION}:coordinator`
);
+ // Sender metadata must be durable before the first composer is opened.
+ // This small catalog runs alongside the paged backfill, never behind it.
+ useMailAccountsQuery(
+ () =>
+ ENABLE_GRAPHQL_BACKFILL &&
+ graphqlSoupFlag().enabled &&
+ isLeader() &&
+ !!userId()
+ );
const [cacheHost, setCacheHost] = createSignal<CacheHost>();
const [cacheGeneration, setCacheGeneration] = createSignal(0);
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index a0458e4966..d12dc4f30d 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -535,7 +535,23 @@ syncing text appears, including offline. A failure shows a banner inside the
composer, above the recipients, with **Retry** (or **Retry discard**); it never
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.
+without repeatedly submitting the rejected request. If sender metadata is still
+unavailable, the local draft is retained; reconnect and select an inbox before
+editing to resume synchronization.
+
+Unqueued first-use drafts also appear in mobile name search and the current Mail
+view's Drafts search, without requiring a cached thread record. A working copy
+preserves confirmed thread flags for facet filters, and a subject mismatch never
+hides a matching server body or cached sender hit. Inbox, alias, and facet
+selections still apply; a draft without an inbox is visible with All inboxes
+selected. Sender metadata warms alongside GraphQL backfill, before opening a
+composer. Test an empty sender catalog too: create a draft offline, restart, find
+it in Drafts/name search, and reopen its subject and body. Reconnect, select the
+sending inbox, edit, and verify it syncs without a duplicate row. Reopen an
+unqueued local draft while online too: its temporary thread's server 404 must
+not hide the local composer or mark that temporary ID read. Confirmed server
+threads still respect deletion/access errors; local working copies do not
+override authentication or permission failures.
Local draft storage reopens unexpectedly closed IndexedDB connections. If creating
a transaction fails because the connection is closing, it retries once before
running any writes. When WebKit aborts a started transaction (typically while the