Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): add spam and trash views (#9079)
gbirman08bfd9ac3c84
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 26961272ef..8e1dc883ef 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -377,6 +377,11 @@ not to account-wide paired runtime count; a user can pair several computers.- All Mail previews exclude spam/junk and trash. Keep draft edits from restoringan excluded preview or timestamp, including synced Macro drafts; Drafts andSent retain their own canonical membership.+- Spam and Trash use scoped REST pages without shared preview normalization or+ service search; restore through the provider-neutral thread-state mutation.+ Refresh these isolated lists after read-state writes, provider sync events, and+ settled Outlook operations; shared-cache updates cannot reach them. Preserve+ newer selections when a pending folder restore finishes.Agent split headers show live viewers through `BlockLiveIndicators` with theresolved session ID; keep the existing `AgentSessionProvider` subscription to@@ -684,6 +689,8 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to## Rules+- Pass persistent touch row controls through `ListEntity.touchActions`; hover actions are hidden on touch, and the narrow inbox layout must retain the touch controls.+Conventions for this app live in `.agents/rules/web/` and load when you touchmatching files: data fetching, Solid reactivity, architecture, UI, UI primitives,the startup bundle, Lexical nodes, and translated menu labels.diff --git a/apps/web/src/features/email-thread/queries/thread-operations.ts b/apps/web/src/features/email-thread/queries/thread-operations.tsindex d99f7f5f75..075dedc333 100644--- a/apps/web/src/features/email-thread/queries/thread-operations.ts+++ b/apps/web/src/features/email-thread/queries/thread-operations.ts@@ -1,5 +1,7 @@+import { fireAndForget } from '@core/util/fireAndForget';import { thrownResultErrorHasCode, throwOnErr } from '@core/util/result';import { refreshEmailThreadCache } from '@queries/email/cache-cleanup';+import { invalidateEmailFolderQueries } from '@queries/email/folder-cache';import { emailKeys } from '@queries/email/keys';import { emailClient } from '@service-email/client';import type { MailboxOperation } from '@service-email/generated/schemas';@@ -36,8 +38,10 @@ function threadOperationsQueryOptions(threadId: string, enabled: boolean) {const operations = await throwOnErr(() =>emailClient.threadOperations(threadId));- if (wasPending && !hasPending(operations))- void refreshEmailThreadCache(threadId).catch(() => {});+ if (wasPending && !hasPending(operations)) {+ fireAndForget(refreshEmailThreadCache(threadId), 'email-operations');+ fireAndForget(invalidateEmailFolderQueries(), 'email-operations');+ }return operations;},refetchInterval: operationsPollInterval,diff --git a/apps/web/src/features/email-view/components/EmailEmptyState.tsx b/apps/web/src/features/email-view/components/EmailEmptyState.tsxindex 10cca2bedb..2c81cba503 100644--- a/apps/web/src/features/email-view/components/EmailEmptyState.tsx+++ b/apps/web/src/features/email-view/components/EmailEmptyState.tsx@@ -9,6 +9,7 @@ import { FOCUS_WINDOW_DAYS } from '@queries/email/focus';import { EmptyStatePanel, FilteredHiddenBanner } from '@ui';import { Match, Switch } from 'solid-js';import { match } from 'ts-pattern';+import { canSearchEmailTab } from '../constants';import { useEmailView } from '../email-view-context';import type { EmailTab } from '../types';@@ -62,6 +63,16 @@ function tabCopy(tab: EmailTab): { title: string; description: string } {title: 'Nothing needs you',description: `Signal email worth your attention from the last ${FOCUS_WINDOW_DAYS} days appears here.`,}))+ .with('spam', () => ({+ title: 'No spam',+ description:+ 'Email marked as spam or junk in your connected inboxes appears here.',+ }))+ .with('trash', () => ({+ title: 'Trash is empty',+ description:+ 'Deleted email from your connected inboxes appears here until it is permanently removed.',+ })).with('all', () => ({title: 'No email yet',description: 'Everything in your inbox will appear here as it arrives.',@@ -75,9 +86,7 @@ export function EmailEmptyState() {const startAddInbox = useAddInboxFlow();// Scheduled has no search or filters; text typed on another tab stays behind.const searchText = () =>- state.tab === 'scheduled' || state.tab === 'reminders'- ? ''- : state.search.trim();+ canSearchEmailTab(state.tab) ? state.search.trim() : '';const noInboxesSelected = () => state.inboxIds?.length === 0;const hasActiveFilters = () =>Object.values(state.facets).some((optionIds) => optionIds.length > 0);diff --git a/apps/web/src/features/email-view/components/EmailHeader.tsx b/apps/web/src/features/email-view/components/EmailHeader.tsxindex 2d956dbbc6..9c60b7b83d 100644--- a/apps/web/src/features/email-view/components/EmailHeader.tsx+++ b/apps/web/src/features/email-view/components/EmailHeader.tsx@@ -17,6 +17,7 @@ import { tourTarget } from '@ui/components/Tour';import { createSignal, Show } from 'solid-js';import { composeEmail } from '../compose-email';import {+ canSearchEmailTab,EMAIL_INBOX_TAB_IDS,EMAIL_TAB_LABELS,EMAIL_TABS,@@ -103,8 +104,7 @@ export function EmailHeader(props: EmailHeaderProps) {focusSearch?.();return true;};- const canSearch = () =>- state.tab !== 'scheduled' && state.tab !== 'reminders';+ const canSearch = () => canSearchEmailTab(state.tab);// Mail clients search with `/`; elsewhere it opens the app's search view.registerHotkey({@@ -180,7 +180,7 @@ export function EmailHeader(props: EmailHeaderProps) {onClick={() => composeEmail(openWithSplit, state.inboxIds)}/></div>- <Show when={state.tab !== 'reminders' && state.tab !== 'scheduled'}>+ <Show when={canSearch()}><ListHeaderSearchref={searchTarget}label="Search email"diff --git a/apps/web/src/features/email-view/components/EmailList.tsx b/apps/web/src/features/email-view/components/EmailList.tsxindex 73056f4981..431db4887d 100644--- a/apps/web/src/features/email-view/components/EmailList.tsx+++ b/apps/web/src/features/email-view/components/EmailList.tsx@@ -20,11 +20,13 @@ import {viewedProjectIdFromContent,} from '@app/features/soup';import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';+import { t } from '@app/lib/i18n';import { makePersistedState } from '@app/lib/persistence';import { PullToRefresh } from '@components/app/mobile/PullToRefresh';import { SwipableRowProvider } from '@components/app/mobile/SwipableRow';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { createSplitAutofocus } from '@components/app/split-layout/utils/createSplitAutofocus';+import { toast } from '@core/component/Toast/Toast';import { TOKENS } from '@core/hotkey/tokens';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { createScrollTopFade } from '@core/util/createScrollTopFade';@@ -41,6 +43,7 @@ import BellIcon from '@icon/system/regular/bell-simple.svg';import CaretDownIcon from '@icon/system/regular/caret-down.svg';import CheckIcon from '@icon/system/regular/check.svg';import SpinnerIcon from '@icon/system/regular/spinner.svg';+import { useRestoreEmailFolderMutation } from '@queries/email/folders';import { createElementSize } from '@solid-primitives/resize-observer';import { Button, cn } from '@ui';import { tourTarget } from '@ui/components/Tour';@@ -65,6 +68,7 @@ import {soupNavigationTouchHighlight,} from '../../next-soup/soup-view/soup-navigation-touch-highlight';import { openEntityInSplitFromUnifiedList } from '../../next-soup/utils';+import { isExcludedEmailFolder } from '../constants';import {type EmailListActivationMetadata,useEmailView,@@ -74,6 +78,7 @@ import {DEFAULT_EMAIL_LIST_STATE,type EmailListStateSnapshot,} from '../persistence';+import { createEmailFolderRestore } from '../primitives/folder-restore';import { createEmailRowActionState } from '../primitives/row-action-state';import { createScrollAnchor } from '../primitives/scroll-anchor';import type { EmailDataSourceItem } from '../queries/use-email-query';@@ -409,6 +414,33 @@ export function EmailList(props: EmailListProps) {}const rowActionState = createEmailRowActionState();+ const restoreFolder = useRestoreEmailFolderMutation();+ const restoreLabel = () =>+ state.tab === 'spam'+ ? t('entityActions.notSpam')+ : t('entityActions.restoreEmail');+ const restoreFolderThreads = createEmailFolderRestore({+ tab: () => state.tab,+ isPending: () => restoreFolder.isPending,+ selection: list.selection.requestedKeys,+ clearSelection: listInteractions.selection.clear,+ restore: (input) => restoreFolder.mutateAsync(input),+ onRestored: () =>+ toast.success(t('entityActions.toastEmailRestoreRequested')),+ onFailed: (count) =>+ toast.failure(t('entityActions.toastEmailRestoreFailed', { count })),+ });+ function restoreThreads(+ entities: EntityData[],+ action: { clearSelection?: boolean } = {}+ ) {+ return restoreFolderThreads(+ entities+ .filter((entity) => entity.type === 'email')+ .map((entity) => entity.id),+ action+ );+ }async function runRowAction(row: EmailActionRow,@@ -440,7 +472,23 @@ export function EmailList(props: EmailListProps) {archived={archived()}canArchive={entityActionViewContext().supportsMarkDone}canUnarchive={canMarkNotDone(props.row.entity)}- pending={rowActionState.isPending(props.row.rowId)}+ pending={+ rowActionState.isPending(props.row.rowId) || restoreFolder.isPending+ }+ restore={+ isExcludedEmailFolder(state.tab)+ ? {+ label: restoreLabel(),+ run: () =>+ fireAndForget(+ restoreThreads([props.row.entity], {+ clearSelection: false,+ }),+ 'email-view'+ ),+ }+ : undefined+ }onFocus={() => focusActionRow(props.row)}onArchive={() =>fireAndForget(@@ -867,6 +915,20 @@ export function EmailList(props: EmailListProps) {/></Show>}+ touchActions={+ <Show+ when={isExcludedEmailFolder(+ state.tab+ )}+ >+ <RowActions+ row={{+ entity: entityRow().entity,+ rowId: entityRow().id,+ }}+ />+ </Show>+ }checked={list.selection.isSelected(entityRow().id)}@@ -999,7 +1061,22 @@ export function EmailList(props: EmailListProps) {selected={selectedEntities()}onClear={listInteractions.selection.clear}analyticsSource="email_view_selection_toolbar"- />+ >+ <Show when={isExcludedEmailFolder(state.tab)}>+ <Button+ size="sm"+ disabled={restoreFolder.isPending}+ onClick={() =>+ fireAndForget(+ restoreThreads(selectedEntities()),+ 'email-view'+ )+ }+ >+ {restoreLabel()}+ </Button>+ </Show>+ </EntitySelectionToolbar></Show></div></MaybeSoupEntityActionDrawerManager>diff --git a/apps/web/src/features/email-view/components/EmailRowActions.test.tsx b/apps/web/src/features/email-view/components/EmailRowActions.test.tsxindex 37d22f0fd0..f59b8e8c75 100644--- a/apps/web/src/features/email-view/components/EmailRowActions.test.tsx+++ b/apps/web/src/features/email-view/components/EmailRowActions.test.tsx@@ -23,6 +23,31 @@ function Actions(}describe('email row actions', () => {+ it('restores folder mail without also offering archive or activating the row', () => {+ const restore = vi.fn();+ const openThread = vi.fn();+ render(() => (+ <div onClick={openThread}>+ <EmailRowActions+ archived+ canArchive={false}+ canUnarchive={false}+ pending={false}+ restore={{ label: 'Not spam', run: restore }}+ onArchive={vi.fn()}+ onCommands={vi.fn()}+ onFocus={vi.fn()}+ />+ </div>+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Not spam' }));+ expect(restore).toHaveBeenCalledOnce();+ expect(openThread).not.toHaveBeenCalled();+ expect(+ screen.queryByRole('button', { name: 'Unarchive email' })+ ).toBeNull();+ });+it('runs the clicked action without activating or dragging the row', () => {const openThread = vi.fn();const startDrag = vi.fn();diff --git a/apps/web/src/features/email-view/components/EmailRowActions.tsx b/apps/web/src/features/email-view/components/EmailRowActions.tsxindex f98e2a2870..edf4548adc 100644--- a/apps/web/src/features/email-view/components/EmailRowActions.tsx+++ b/apps/web/src/features/email-view/components/EmailRowActions.tsx@@ -75,10 +75,25 @@ export function EmailRowActions(props: {onArchive: () => void;onCommands: () => void;onFocus: () => void;+ restore?: { label: string; run: () => void };}) {return (<EmailActionGroup onFocus={props.onFocus}>- <Show when={!props.archived || props.canUnarchive}>+ <Show when={props.restore}>+ {(restore) => (+ <Button+ aria-label={restore().label}+ tooltip={{ content: restore().label }}+ variant="ghost"+ size="icon-sm"+ disabled={props.pending}+ onClick={() => restore().run()}+ >+ <ArrowCounterClockwiseIcon class="size-4" />+ </Button>+ )}+ </Show>+ <Show when={!props.restore && (!props.archived || props.canUnarchive)}><Buttonaria-label={props.archived ? 'Unarchive email' : 'Archive email'}tooltip={{diff --git a/apps/web/src/features/email-view/components/EmailSidebar.tsx b/apps/web/src/features/email-view/components/EmailSidebar.tsxindex 93156857dc..bc7c11f3d5 100644--- a/apps/web/src/features/email-view/components/EmailSidebar.tsx+++ b/apps/web/src/features/email-view/components/EmailSidebar.tsx@@ -4,6 +4,7 @@ import {ViewSidebar,} from '@app/components/view-shell';import { SidebarCreateButton } from '@app/components/view-shell/SidebarCreateButton';+import { t } from '@app/lib/i18n';import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { isTouchDevice } from '@core/mobile/isTouchDevice';@@ -15,7 +16,9 @@ import FocusIcon from '@icon/system/regular/crosshair.svg';import EnvelopeIcon from '@icon/system/regular/envelope.svg';import FileIcon from '@icon/system/regular/file.svg';import PaperPlaneTiltIcon from '@icon/system/regular/paper-plane-tilt.svg';+import SpamIcon from '@icon/system/regular/prohibit.svg';import StarIcon from '@icon/system/regular/star.svg';+import TrashIcon from '@icon/system/regular/trash.svg';import TrayIcon from '@icon/system/regular/tray.svg';import UsersThreeIcon from '@icon/system/regular/users-three.svg';import SignalIcon from '@icon/system/regular/wave-sine.svg';@@ -28,6 +31,7 @@ import { type Component, For, Show } from 'solid-js';import { Dynamic } from 'solid-js/web';import { composeEmail } from '../compose-email';import {+ canSearchEmailTab,EMAIL_INBOX_TAB_IDS,EMAIL_TAB_IDS,EMAIL_TAB_LABELS,@@ -53,6 +57,8 @@ const LIBRARY_TAB_IDS = ['all','archived','shared',+ 'spam',+ 'trash',] as const satisfies readonly EmailTab[];const DESKTOP_TAB_IDS = ['important',@@ -73,6 +79,8 @@ const TAB_ICONS: Record<EmailTab, Component<{ class?: string }>> = {archived: ArchiveIcon,all: EnvelopeIcon,focus: FocusIcon,+ spam: SpamIcon,+ trash: TrashIcon,};function Tab(props: { id: EmailTab; label?: string; onNavigate?: () => void }) {@@ -136,15 +144,15 @@ export function EmailNavigation(props: { onNavigate?: () => void }) {<ViewSidebar.Icon><TrayIcon class="size-4" /></ViewSidebar.Icon>- <span class="truncate">Inbox</span>+ <span class="truncate">{t('viewMenus.inbox')}</span></ViewSidebar.Item><For each={PRIMARY_TAB_IDS.filter(isVisible)}>{(id) => <Tab id={id} onNavigate={props.onNavigate} />}</For></ViewSidebar.Nav>- <section aria-label="Library" class="shrink-0">+ <section aria-label={t('viewMenus.library')} class="shrink-0"><h2 class="flex h-(--sidebar-row-height) items-center px-(--sidebar-item-inset) text-xs font-medium text-ink-muted">- Library+ {t('viewMenus.library')}</h2><ViewSidebar.Navaria-label="Email library"@@ -203,14 +211,18 @@ export function EmailSidebar() {<Show when={!isTouchDevice()}><ViewSidebar.HeadersearchLabel="Search email"- search={() => (- <SearchBar- label="Search email"- placeholder="Search email"- value={state.search}- onValueChange={(search) => setState('search', search)}- />- )}+ search={+ canSearchEmailTab(state.tab)+ ? () => (+ <SearchBar+ label="Search email"+ placeholder="Search email"+ value={state.search}+ onValueChange={(search) => setState('search', search)}+ />+ )+ : undefined+ }><div class="flex min-w-0 items-center gap-1"><ViewSidebar.CloseButton class="shrink-0" />diff --git a/apps/web/src/features/email-view/constants.ts b/apps/web/src/features/email-view/constants.tsindex a56880f16e..9ffc69c1a0 100644--- a/apps/web/src/features/email-view/constants.ts+++ b/apps/web/src/features/email-view/constants.ts@@ -1,38 +1,49 @@-/**- * Existing tab ids match the legacy mail view (`important` is Signal).- * Favorites extends that list; entity action capabilities use `${view}-${tab}`.- * Focus comes last so the Signal/Noise pair keeps its position and hotkeys;- * the Inbox tabs and the touch layouts draw it before them.- */-export const EMAIL_TAB_IDS = [- 'important',- 'noise',- 'favorites',- 'sent',- 'scheduled',- 'reminders',- 'calendar',- 'drafts',- 'shared',- 'archived',- 'all',- 'focus',-] as const;+import { t } from '@app/lib/i18n';++import { EMAIL_TAB_IDS, type EmailTab } from './tabs';-export type EmailTab = (typeof EMAIL_TAB_IDS)[number];+export { EMAIL_TAB_IDS, type EmailTab } from './tabs';export const EMAIL_TAB_LABELS = {- important: 'Signal',- noise: 'Noise',- favorites: 'Favorites',- sent: 'Sent',- scheduled: 'Scheduled',- reminders: 'Reminders',- calendar: 'Calendar',- drafts: 'Drafts',- shared: 'Shared',- archived: 'Archived',- all: 'All',+ get important() {+ return t('viewMenus.signal');+ },+ get noise() {+ return t('viewMenus.noise');+ },+ get favorites() {+ return t('viewMenus.favorites');+ },+ get sent() {+ return t('viewMenus.sent');+ },+ get scheduled() {+ return t('viewMenus.scheduled');+ },+ get reminders() {+ return t('viewMenus.reminders');+ },+ get calendar() {+ return t('viewMenus.calendar');+ },+ get drafts() {+ return t('viewMenus.drafts');+ },+ get shared() {+ return t('viewMenus.shared');+ },+ get archived() {+ return t('viewMenus.archived');+ },+ get all() {+ return t('viewMenus.all');+ },+ get spam() {+ return t('viewMenus.spam');+ },+ get trash() {+ return t('viewMenus.trash');+ },focus: 'Focus',} as const satisfies Record<EmailTab, string>;@@ -43,7 +54,9 @@ export type EmailTabItem = {export const EMAIL_TABS: readonly EmailTabItem[] = EMAIL_TAB_IDS.map((id) => ({id,- label: EMAIL_TAB_LABELS[id],+ get label() {+ return EMAIL_TAB_LABELS[id];+ },}));export const DEFAULT_EMAIL_TAB: EmailTab = 'important';@@ -83,3 +96,11 @@ export const EMAIL_FOCUS_SORT_OPTIONS: readonly {{ id: 'importance', label: 'Importance' },{ id: 'recent', label: 'Most recent' },];++/** Provider folders have separate membership and currently use network pages. */+export const isExcludedEmailFolder = (tab: EmailTab): tab is 'spam' | 'trash' =>+ tab === 'spam' || tab === 'trash';++/** Full-text search does not yet expose provider spam/trash folder scopes. */+export const canSearchEmailTab = (tab: EmailTab): boolean =>+ tab !== 'scheduled' && tab !== 'reminders' && !isExcludedEmailFolder(tab);diff --git a/apps/web/src/features/email-view/email-view.tsx b/apps/web/src/features/email-view/email-view.tsxindex 6392e3c06e..90c20980d9 100644--- a/apps/web/src/features/email-view/email-view.tsx+++ b/apps/web/src/features/email-view/email-view.tsx@@ -174,7 +174,12 @@ function EmailDesktopLayout(props: {const MOBILE_EMAIL_TABS: PillTabItem<EmailTab>[] = [...EMAIL_TABS.filter((tab) => tab.id === 'focus'),...EMAIL_TABS.filter((tab) => tab.id !== 'focus'),-].map((tab) => ({ value: tab.id, label: tab.label }));+].map((tab) => ({+ value: tab.id,+ get label() {+ return tab.label;+ },+}));function EmailMobileLayout(props: ParentProps) {const isVisible = useVisibleEmailTab();diff --git a/apps/web/src/features/email-view/primitives/folder-restore.test.ts b/apps/web/src/features/email-view/primitives/folder-restore.test.tsnew file mode 100644index 0000000000..82ecfcf49d--- /dev/null+++ b/apps/web/src/features/email-view/primitives/folder-restore.test.ts@@ -0,0 +1,132 @@+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import { createListController } from '../../../components/list/create-list-controller';+import type { EmailTab } from '../tabs';+import { createEmailFolderRestore } from './folder-restore';++describe('folder restore selection lifetime', () => {+ it('preserves unrelated selections when restoring an individual row', async () => {+ const selection = new Set(['first', 'second']);+ const clearSelection = vi.fn(() => selection.clear());+ const restore = createEmailFolderRestore({+ tab: () => 'trash',+ isPending: () => false,+ selection: () => selection,+ clearSelection,+ restore: async () => ({ failedIds: [] }),+ onRestored: vi.fn(),+ onFailed: vi.fn(),+ });+ await restore(['third'], { clearSelection: false });+ expect([...selection]).toEqual(['first', 'second']);+ expect(clearSelection).not.toHaveBeenCalled();+ });++ it.each([+ 'new selection',+ 'switch folder',+ 'reselect same row',+ 'refresh rows',+ 'unchanged',+ ])('handles %s during a pending restore', async (change) => {+ let dispose = () => {};+ const setup = createRoot((cleanup) => {+ dispose = cleanup;+ const [tab, setTab] = createSignal<EmailTab>('spam');+ const [items, setItems] = createSignal(['first', 'second']);+ const list = createListController({ items, getKey: (id) => id });+ list.selection.select('first');+ const pending = Promise.withResolvers<{ failedIds: string[] }>();+ const restore = vi.fn(() => pending.promise);+ const onRestored = vi.fn();+ const onFailed = vi.fn();+ const run = createEmailFolderRestore({+ tab,+ isPending: () => false,+ selection: list.selection.requestedKeys,+ clearSelection: list.selection.clear,+ restore,+ onRestored,+ onFailed,+ });+ return {+ setTab,+ setItems,+ list,+ pending,+ restore,+ onRestored,+ onFailed,+ run,+ };+ });+ try {+ const completion = setup.run(['first']);+ if (change === 'new selection') setup.list.selection.select('second');+ if (change === 'switch folder') {+ setup.setTab('trash');+ setup.list.selection.clear();+ setup.list.selection.select('second');+ }+ if (change === 'reselect same row') {+ setup.list.selection.clear();+ setup.list.selection.select('first');+ }+ if (change === 'refresh rows') setup.setItems([]);+ const beforeCompletion = [...setup.list.selection.requestedKeys()];+ setup.pending.resolve({ failedIds: [] });+ await completion;+ expect(setup.restore).toHaveBeenCalledExactlyOnceWith({+ folder: 'spam',+ threadIds: ['first'],+ });+ expect([...setup.list.selection.requestedKeys()]).toEqual(+ change === 'unchanged' || change === 'refresh rows'+ ? []+ : beforeCompletion+ );+ expect(setup.onRestored).toHaveBeenCalledOnce();+ expect(setup.onFailed).not.toHaveBeenCalled();+ } finally {+ dispose();+ }+ });++ it.each(['partial', 'rejected'])(+ 'preserves selection after %s failure',+ async (outcome) => {+ let dispose = () => {};+ const setup = createRoot((cleanup) => {+ dispose = cleanup;+ const list = createListController({+ items: () => ['first'],+ getKey: (id) => id,+ });+ list.selection.select('first');+ const onFailed = vi.fn();+ const onRestored = vi.fn();+ const run = createEmailFolderRestore({+ tab: () => 'trash',+ isPending: () => false,+ selection: list.selection.requestedKeys,+ clearSelection: list.selection.clear,+ restore: async () => {+ if (outcome === 'rejected') throw new Error('Unavailable');+ return { failedIds: ['first'] };+ },+ onFailed,+ onRestored,+ });+ return { list, run, onFailed, onRestored };+ });+ try {+ await setup.run(['first']);+ expect([...setup.list.selection.requestedKeys()]).toEqual(['first']);+ expect(setup.onFailed).toHaveBeenCalledExactlyOnceWith(1);+ expect(setup.onRestored).not.toHaveBeenCalled();+ } finally {+ dispose();+ }+ }+ );+});diff --git a/apps/web/src/features/email-view/primitives/folder-restore.ts b/apps/web/src/features/email-view/primitives/folder-restore.tsnew file mode 100644index 0000000000..cc9527787a--- /dev/null+++ b/apps/web/src/features/email-view/primitives/folder-restore.ts@@ -0,0 +1,43 @@+import type { Accessor } from 'solid-js';+import { type EmailTab, isExcludedEmailFolder } from '../constants';++type FolderRestoreOptions = {+ tab: Accessor<EmailTab>;+ isPending: Accessor<boolean>;+ /** Stable requested-key snapshot, replaced only when selection changes. */+ selection: Accessor<ReadonlySet<string>>;+ clearSelection: () => void;+ restore: (input: {+ folder: 'spam' | 'trash';+ threadIds: string[];+ }) => Promise<{ failedIds: string[] }>;+ onRestored: () => void;+ onFailed: (count: number) => void;+};++/** Restore the captured folder without clearing a newer list selection. */+export function createEmailFolderRestore(options: FolderRestoreOptions) {+ return async (+ threadIds: string[],+ action: { clearSelection?: boolean } = {}+ ) => {+ const folder = options.tab();+ if (!isExcludedEmailFolder(folder) || options.isPending()) return;+ const selection = options.selection();+ try {+ const result = await options.restore({ folder, threadIds });+ if (result.failedIds.length) {+ options.onFailed(result.failedIds.length);+ } else {+ if (+ action.clearSelection !== false &&+ options.selection() === selection+ )+ options.clearSelection();+ options.onRestored();+ }+ } catch {+ options.onFailed(threadIds.length);+ }+ };+}diff --git a/apps/web/src/features/email-view/queries/email-query.test.ts b/apps/web/src/features/email-view/queries/email-query.test.tsindex 884d957da2..d97db782aa 100644--- a/apps/web/src/features/email-view/queries/email-query.test.ts+++ b/apps/web/src/features/email-view/queries/email-query.test.ts@@ -166,6 +166,8 @@ describe('buildEmailQuery', () => {['archived', 'all'],['all', 'all'],['focus', 'all'],+ ['spam', 'spam'],+ ['trash', 'trash'],]);for (const tab of EMAIL_TAB_IDS) {@@ -175,6 +177,26 @@ describe('buildEmailQuery', () => {}});+ it.each(['spam', 'trash'] as const)(+ 'keeps %s in its provider folder with inbox and alias scope',+ (tab) => {+ const args = buildEmailQuery(+ contextFor({+ tab,+ inboxIds: ['inbox-a'],+ aliasFilter: {+ inboxId: 'inbox-a',+ emailAddress: '[email protected]',+ },+ })+ );+ expect(args.transport).toBe('rest');+ expect(args.body.emailView).toBe(tab);+ expect(serialize(args.body.ef)).toContain('inbox-a');+ expect(serialize(args.body.ef)).toContain('[email protected]');+ }+ );+it('confines every non-email target to nothing', () => {const { body } = buildEmailQuery(contextFor());@@ -322,6 +344,17 @@ describe('buildEmailQuery', () => {describe('buildEmailSearchRequest', () => {const search = { query: 'invoice', matchType: 'partial' as const };+ it.each(['spam', 'trash'] as const)(+ 'fails closed for %s even with retained IDs',+ (tab) => {+ expect(+ buildEmailSearchRequest(contextFor({ tab }), search, [+ 'retained-thread',+ ]).body.filters?.email_filters?.email_thread_ids+ ).toEqual([NIL]);+ }+ );+const requestFor = (overrides: Partial<EmailQueryContext> = {}) => {const { body } = buildEmailSearchRequest(contextFor(overrides), search);if (!body.filters) throw new Error('search request has no filters');diff --git a/apps/web/src/features/email-view/queries/email-query.ts b/apps/web/src/features/email-view/queries/email-query.tsindex dce1bce2cc..1eddc01fcf 100644--- a/apps/web/src/features/email-view/queries/email-query.ts+++ b/apps/web/src/features/email-view/queries/email-query.ts@@ -10,6 +10,7 @@ import {} from '@app/features/soup';import type { SoupAstBody, SoupAstItemsQueryArgs } from '@queries/soup/items';import { match } from 'ts-pattern';+import { isExcludedEmailFolder } from '../constants';import { EMAIL_FACETS, type EmailFacetContext } from '../filters/email-facets';import type { EmailTab } from '../types';@@ -36,6 +37,8 @@ export const emailViewForTab = (tab: EmailTab): string =>// Soup source on drafts so its query shape remains valid while disabled..with('scheduled', () => 'drafts').with('sent', () => 'sent')+ .with('spam', () => 'spam')+ .with('trash', () => 'trash').with('favorites','calendar',@@ -102,6 +105,8 @@ function tabClause(context: EmailQueryContext): TargetExpr {'all','reminders','focus',+ 'spam',+ 'trash',anyThread).exhaustive(anyThread)@@ -160,7 +165,11 @@ export function buildEmailQuery(// Newest activity first: `updated_at` is the thread's latest message time.return {- ...(context.aliasFilter ? { transport: 'graphql' as const } : {}),+ ...(isExcludedEmailFolder(context.tab)+ ? { transport: 'rest' as const }+ : context.aliasFilter+ ? { transport: 'graphql' as const }+ : {}),params: {expand: true,limit: 100,diff --git a/apps/web/src/features/email-view/queries/email-search.ts b/apps/web/src/features/email-view/queries/email-search.tsindex 118bd90875..b9487f6192 100644--- a/apps/web/src/features/email-view/queries/email-search.ts+++ b/apps/web/src/features/email-view/queries/email-search.ts@@ -10,6 +10,7 @@ import type {EntityFilters,} from '@service-search/generated/models';import { match } from 'ts-pattern';+import { isExcludedEmailFolder } from '../constants';import type { EmailTab } from '../types';import type { EmailQueryContext } from './email-query';@@ -30,28 +31,32 @@ const nonEmailFilters: EntityFilters = {// filter archive state either, so `emailMatchesTab` trims Archived hits.function tabFilters(tab: EmailTab): EmailFilters {// Focus filters its own list on the client; this search stays dormant there.- return match(tab)- .with('important', 'focus', () => ({- importance: true,- shared: 'exclude' as const,- }))- .with('noise', () => ({ importance: false, shared: 'exclude' as const }))- .with('calendar', () => ({- calendar_only: true,- shared: 'exclude' as const,- }))- .with('shared', () => ({ shared: 'only' as const }))- .with('archived', () => ({ shared: 'exclude' as const }))- .with(- 'favorites',- 'drafts',- 'scheduled',- 'reminders',- 'sent',- 'all',- () => ({})- )- .exhaustive(() => ({}));+ return (+ match(tab)+ .with('important', 'focus', () => ({+ importance: true,+ shared: 'exclude' as const,+ }))+ .with('noise', () => ({ importance: false, shared: 'exclude' as const }))+ .with('calendar', () => ({+ calendar_only: true,+ shared: 'exclude' as const,+ }))+ .with('shared', () => ({ shared: 'only' as const }))+ // These views disable service search; fail closed if called independently.+ .with('spam', 'trash', () => ({ email_thread_ids: [NIL_UUID] }))+ .with('archived', () => ({ shared: 'exclude' as const }))+ .with(+ 'favorites',+ 'drafts',+ 'scheduled',+ 'reminders',+ 'sent',+ 'all',+ () => ({})+ )+ .exhaustive(() => ({}))+ );}const soleSelection = (selection: string[] | undefined) =>@@ -89,8 +94,9 @@ export function buildEmailSearchRequest(admittedIds?: readonly string[]): SearchSoupQueryArgs {// Both discovery and retained unread results must stay within favorites.- const threadIds =- context.tab === 'favorites'+ const threadIds = isExcludedEmailFolder(context.tab)+ ? [NIL_UUID]+ : context.tab === 'favorites'? (context.favoriteThreadIds ?? []).filter((id) => admittedIds === undefined || admittedIds.includes(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.tsindex f52c6720ed..d05de2a717 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@@ -324,6 +324,28 @@ function mount(search = '') {describe('Email list query transitions', () => {const alias = { inboxId: 'inbox-a', emailAddress: '[email protected]' };+ it.each(['spam', 'trash'] as const)(+ 'ignores stale search and isolates %s discovery and retained previews',+ (tab) => {+ const root = mount('invoice');+ root.setState({ tab, facets: { read: ['unread'] } });+ root.setEntities([email('folder-result')]);+ expect(ids(root.source)).toEqual(['folder-result']);+ for (const [args, options] of vi.mocked(useSoupAstItemsQuery).mock+ .calls) {+ const request = typeof args === 'function' ? args() : args;+ const settings = options?.();+ expect(request.transport).toBe('rest');+ expect(settings?.keepPreviousData).toBe(false);+ expect(settings?.meta?.normalize).toBe(false);+ expect(settings?.meta?.insertFilter?.({} as never)).toBe(false);+ }+ for (const [, options] of searchQueryMock.mock.calls) {+ expect(options().enabled).toBe(false);+ }+ }+ );+it('refreshes the current alias membership readers after refreshing search, but not inactive readers', async () => {const root = mount('invoice');root.setSearchHasMore(false);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.tsindex ab3b6fe39b..f1c03726d9 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@@ -33,6 +33,7 @@ import { useSearchSoupQuery } from '@queries/soup/search';import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';import { type Accessor, createMemo, createSignal, indexArray } from 'solid-js';import { match } from 'ts-pattern';+import { canSearchEmailTab, isExcludedEmailFolder } from '../constants';import { EMAIL_FACETS, type EmailFacetContext } from '../filters/email-facets';import type { EmailTab, EmailViewState } from '../types';import { advanceEmptyAliasPages } from './advance-empty-alias-pages';@@ -95,12 +96,25 @@ function emailMatchesTab('calendar','all','focus',+ 'spam',+ 'trash',() => true).exhaustive(() => true));}+// Provider-neutral folder membership needs a server lookup; arbitrary realtime+// entities cannot establish it from labels (Outlook has no Gmail system labels).+const rejectFolderInsert = () => false;+const folderQueryOptions = (tab: EmailTab) =>+ isExcludedEmailFolder(tab)+ ? {+ keepPreviousData: false,+ meta: { normalize: false, insertFilter: rejectFolderInsert },+ }+ : {};+type AdmittedEmails = {scope: string;items: EmailEntity[];@@ -172,6 +186,8 @@ export function useEmailDataSource(});const query = useSoupAstItemsQuery(queryArgs, () => ({enabled: sourceEnabled(),+ // Folder previews must not overwrite the same thread's All Mail preview.+ ...folderQueryOptions(state.tab),}));const localDrafts = createLocalDraftSource(() => query.transport === 'graphql'@@ -201,7 +217,7 @@ export function useEmailDataSource(// Mail search retains server relevance; recoverable local drafts are merged below.const search = createSearchState({surface: () => 'email',- text: () => state.search,+ text: () => (canSearchEmailTab(state.tab) ? state.search : ''),enabled: () => sourceEnabled() && searchFavoritesReady(),disableLocalSearch: () => true,buildRequest: (request) =>@@ -225,6 +241,7 @@ export function useEmailDataSource(() => ({enabled: !!state.aliasFilter && search.usesServiceSearch(),keepPreviousData: false,+ ...folderQueryOptions(state.tab),})));@@ -328,6 +345,7 @@ export function useEmailDataSource(() => ({enabled:filtersReady() && (!search.isSearching() || !!state.aliasFilter),+ ...folderQueryOptions(state.tab),}));const searchQuery = useSearchSoupQuery(diff --git a/apps/web/src/features/email-view/tabs.ts b/apps/web/src/features/email-view/tabs.tsnew file mode 100644index 0000000000..ca7bebd9d4--- /dev/null+++ b/apps/web/src/features/email-view/tabs.ts@@ -0,0 +1,23 @@+/**+ * Existing tab ids match the legacy mail view (`important` is Signal).+ * Keep existing IDs ordered to preserve tab hotkeys.+ * Favorites extends that list; entity action capabilities use `${view}-${tab}`.+ */+export const EMAIL_TAB_IDS = [+ 'important',+ 'noise',+ 'favorites',+ 'sent',+ 'scheduled',+ 'reminders',+ 'calendar',+ 'drafts',+ 'shared',+ 'archived',+ 'all',+ 'focus',+ 'spam',+ 'trash',+] as const;++export type EmailTab = (typeof EMAIL_TAB_IDS)[number];diff --git a/apps/web/src/features/entity/composed/ListEntity.tsx b/apps/web/src/features/entity/composed/ListEntity.tsxindex 92e5b3a1e4..f7bc8baea3 100644--- a/apps/web/src/features/entity/composed/ListEntity.tsx+++ b/apps/web/src/features/entity/composed/ListEntity.tsx@@ -102,6 +102,7 @@ export function ListEntity(props: ListEntityProps) {// Legacy Soup callers do not pass row behavior explicitly yet.const soupView = useMaybeSoupView();const rowActions = children(() => props.actions);+ const touchActions = children(() => props.touchActions);const leadingAction = children(() => props.leadingAction);const titleLeading = children(() => props.titleLeading);const icon = children(() => props.icon);@@ -165,7 +166,7 @@ export function ListEntity(props: ListEntityProps) {const layoutProps = (): LayoutProps => ({entity: props.entity,actions: !isTouchDevice() ? rowActions() : undefined,- leadingAction: !isTouchDevice() ? leadingAction() : undefined,+ leadingAction: isTouchDevice() ? touchActions() : leadingAction(),titleLeading: titleLeading(),icon: icon(),titleTrailing: titleTrailing(),diff --git a/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx b/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsxindex 39f6af8a6c..298667d15f 100644--- a/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx+++ b/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx@@ -43,6 +43,7 @@ export function NarrowInboxLayout(props: LayoutProps) {style={{// A scheduled send's badge is wider than a date, so it sizes its column.'grid-template-columns':+ props.leadingAction ||props.referenceProperties ||props.scheduleStatus ||(isEmailEntity(props.entity) && props.entity.scheduledSendTime)@@ -130,6 +131,7 @@ export function NarrowInboxLayout(props: LayoutProps) {placement="timestamp"class="flex items-center justify-end gap-1 text-xs text-right text-ink-extra-muted font-light pt-3 pr-4">+ {props.leadingAction}{props.referenceProperties}{props.scheduleStatus}<Showdiff --git a/apps/web/src/features/entity/composed/list-entity/shared.tsx b/apps/web/src/features/entity/composed/list-entity/shared.tsxindex 4e9eca48b7..ec5ef30542 100644--- a/apps/web/src/features/entity/composed/list-entity/shared.tsx+++ b/apps/web/src/features/entity/composed/list-entity/shared.tsx@@ -40,6 +40,8 @@ export interface BaseListEntityProps<E extends EntityData = EntityData>hovered?: boolean;/** Caller-owned quick actions, revealed on pointer hover or keyboard focus. */actions?: JSX.Element;+ /** Persistent controls for touch devices, before the timestamp. */+ touchActions?: JSX.Element;/** Persistent status/action immediately before the timestamp. */leadingAction?: JSX.Element;/** Caller-owned marker between the icon and the title, e.g. a priority. */diff --git a/apps/web/src/features/entity/queries/key.ts b/apps/web/src/features/entity/queries/key.tsindex f25fbfb7ea..0885715133 100644--- a/apps/web/src/features/entity/queries/key.ts+++ b/apps/web/src/features/entity/queries/key.ts@@ -43,6 +43,8 @@ const EMAIL_VIEW_EXCLUDES_DONE: Record<PreviewViewStandardLabel, boolean> = {starred: false,sent: false,drafts: false,+ spam: false,+ trash: false,};/**diff --git a/apps/web/src/lib/i18n/locales/en/entity-actions.ts b/apps/web/src/lib/i18n/locales/en/entity-actions.tsindex 22ea3ff6f3..763a9132f8 100644--- a/apps/web/src/lib/i18n/locales/en/entity-actions.ts+++ b/apps/web/src/lib/i18n/locales/en/entity-actions.ts@@ -1,4 +1,11 @@export default {+ notSpam: 'Not spam',+ restoreEmail: 'Restore',+ toastEmailRestoreRequested: 'Restore requested',+ toastEmailRestoreFailed: {+ one: 'Could not restore {{count}} email. Try again.',+ other: 'Could not restore {{count}} emails. Try again.',+ },// Action labels shared by the entity menus, file menu, command menu and// project/folder menus.markDone: 'Mark Done',diff --git a/apps/web/src/lib/i18n/locales/en/view-menus.ts b/apps/web/src/lib/i18n/locales/en/view-menus.tsindex 0cbe9872a3..f773c76663 100644--- a/apps/web/src/lib/i18n/locales/en/view-menus.ts+++ b/apps/web/src/lib/i18n/locales/en/view-menus.ts@@ -1,5 +1,13 @@export default {// View tabs+ favorites: 'Favorites',+ scheduled: 'Scheduled',+ reminders: 'Reminders',+ archived: 'Archived',+ spam: 'Spam',+ trash: 'Trash',+ inbox: 'Inbox',+ library: 'Library',signal: 'Signal',noise: 'Noise',all: 'All',diff --git a/apps/web/src/lib/queries/email/folder-cache.test.ts b/apps/web/src/lib/queries/email/folder-cache.test.tsnew file mode 100644index 0000000000..a570632eb9--- /dev/null+++ b/apps/web/src/lib/queries/email/folder-cache.test.ts@@ -0,0 +1,64 @@+import { QueryClient } from '@tanstack/solid-query';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++let client: QueryClient;+vi.mock('../client', () => ({+ get queryClient() {+ return client;+ },+}));+vi.mock('./backfill', () => ({+ clearBackfillProgress: vi.fn(),+ invalidateBackfillJobs: vi.fn(),+ setBackfillProgress: vi.fn(),+}));+vi.mock('./link', () => ({ invalidateEmailLinks: vi.fn() }));+vi.mock('../soup/normalized-cache', () => ({ invalidateAllSoup: vi.fn() }));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: vi.fn(), failure: vi.fn() },+}));++import { soupKeys } from '../soup/keys';+import { handleRefreshEmail } from './sync';++beforeEach(() => {+ vi.useFakeTimers();+ client = new QueryClient();+});+afterEach(() => {+ vi.runOnlyPendingTimers();+ client.clear();+ vi.useRealTimers();+});++it('refreshes isolated folder queries on provider changes without refetching All Mail', async () => {+ const keys = ['spam', 'trash', 'all'].map(+ (emailView) =>+ soupKeys.astItems({ params: {}, body: { emailView }, transport: 'rest' })+ .queryKey+ );+ const reset = () =>+ keys.forEach((key) => client.setQueryData(key, { pages: [] }));+ reset();+ handleRefreshEmail({ event: 'update_labels', link_id: 'inbox' });+ expect(keys.map((key) => client.getQueryState(key)?.isInvalidated)).toEqual([+ true,+ true,+ false,+ ]);+ reset();+ handleRefreshEmail({ event: 'upsert_message', link_id: 'inbox' });+ handleRefreshEmail({ event: 'delete_message', link_id: 'inbox' });+ // Bursts coalesce, but the last change still refreshes both folders.+ expect(keys.map((key) => client.getQueryState(key)?.isInvalidated)).toEqual([+ false,+ false,+ false,+ ]);+ await vi.advanceTimersByTimeAsync(5000);+ expect(keys.map((key) => client.getQueryState(key)?.isInvalidated)).toEqual([+ true,+ true,+ false,+ ]);+});diff --git a/apps/web/src/lib/queries/email/folder-cache.ts b/apps/web/src/lib/queries/email/folder-cache.tsnew file mode 100644index 0000000000..7c78b496a8--- /dev/null+++ b/apps/web/src/lib/queries/email/folder-cache.ts@@ -0,0 +1,17 @@+import { queryClient } from '../client';+import { soupKeys } from '../soup/keys';++/** Folder previews are intentionally outside both shared entity caches. */+export function invalidateEmailFolderQueries() {+ return queryClient.invalidateQueries({+ queryKey: soupKeys.astItems._def,+ predicate: (query) =>+ query.queryKey.some(+ (part) =>+ typeof part === 'object' &&+ part !== null &&+ 'emailView' in part &&+ (part.emailView === 'spam' || part.emailView === 'trash')+ ),+ });+}diff --git a/apps/web/src/lib/queries/email/folders.test.ts b/apps/web/src/lib/queries/email/folders.test.tsnew file mode 100644index 0000000000..dc8b1e7b07--- /dev/null+++ b/apps/web/src/lib/queries/email/folders.test.ts@@ -0,0 +1,176 @@+import { err, ok } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ update: vi.fn(),+ refresh: vi.fn(),+ invalidate: vi.fn(),+ invalidateSoup: vi.fn(),+ refreshLists: vi.fn(),+ spanActive: false,+}));+vi.mock('./cache-cleanup', () => ({+ updateEmailThreadState: mocks.update,+ refreshEmailThreadCache: mocks.refresh,+}));+vi.mock('../client', () => ({+ queryClient: { invalidateQueries: mocks.invalidate },+}));+vi.mock('../soup/normalized-cache', () => ({+ invalidateAllSoup: mocks.invalidateSoup,+}));+vi.mock('../soup/graphql/active-queries', () => ({+ refreshActiveGraphqlSoupQueries: mocks.refreshLists,+}));+vi.mock('@macro-inc/observability', () => {+ // Match the browser context manager: active context ends at an await.+ const run = <T>(work: () => T): T => {+ const previous = mocks.spanActive;+ mocks.spanActive = true;+ try {+ return work();+ } finally {+ mocks.spanActive = previous;+ }+ };+ return {+ Telemetry: {+ span: (_name: string, work: (span: unknown) => unknown) =>+ run(() => work({ setAttr: vi.fn(), error: vi.fn(), run })),+ },+ };+});++import { restoreEmailFolderThreads } from './folders';++beforeEach(() => {+ vi.clearAllMocks();+});++describe('restore provider folders', () => {+ it.each([+ ['spam', 'junk'],+ ['trash', 'trashed'],+ ] as const)(+ 'restores %s through semantic mailbox state and refreshes successful threads',+ async (folder, field) => {+ mocks.update.mockResolvedValue(ok(undefined));+ const result = await restoreEmailFolderThreads({+ folder,+ threadIds: ['one', 'one', 'two'],+ });+ expect(mocks.update.mock.calls).toEqual([+ [{ thread_id: 'one', field, value: false }],+ [{ thread_id: 'two', field, value: false }],+ ]);+ expect(result).toEqual({ restoredIds: ['one', 'two'], failedIds: [] });+ expect(mocks.refresh.mock.calls).toEqual([['one'], ['two']]);+ expect(mocks.invalidateSoup).toHaveBeenCalledOnce();+ expect(mocks.refreshLists).toHaveBeenCalledWith({+ unmaintainedOnly: true,+ });+ }+ );++ it('keeps failed IDs separate without undoing successful restores', async () => {+ mocks.update+ .mockResolvedValueOnce(ok(undefined))+ .mockResolvedValueOnce(+ err([{ code: 'FORBIDDEN', message: 'Access denied' }])+ );+ const result = await restoreEmailFolderThreads({+ folder: 'spam',+ threadIds: ['one', 'two'],+ });+ expect(result).toEqual({ restoredIds: ['one'], failedIds: ['two'] });+ expect(mocks.refresh.mock.calls).toEqual([['one']]);+ });++ it('does not refresh lists when every request fails', async () => {+ mocks.update.mockRejectedValue(new Error('Offline'));+ const result = await restoreEmailFolderThreads({+ folder: 'trash',+ threadIds: ['one'],+ });+ expect(result.failedIds).toEqual(['one']);+ expect(mocks.refresh).not.toHaveBeenCalled();+ expect(mocks.invalidateSoup).not.toHaveBeenCalled();+ });+ it('bounds bulk writes and continues after a partial batch failure', async () => {+ let active = 0;+ let peak = 0;+ let release!: () => void;+ const firstBatch = new Promise<void>((resolve) => {+ release = resolve;+ });+ let started!: () => void;+ const batchStarted = new Promise<void>((resolve) => {+ started = resolve;+ });+ mocks.update.mockImplementation(+ async ({ thread_id }: { thread_id: string }) => {+ active++;+ peak = Math.max(peak, active);+ if (active === 8) started();+ if (Number(thread_id) < 8) await firstBatch;+ active--;+ if (thread_id === '3') throw new Error('Provider unavailable');+ return ok(undefined);+ }+ );+ const result = restoreEmailFolderThreads({+ folder: 'trash',+ threadIds: Array.from({ length: 25 }, (_, i) => String(i)),+ });+ await batchStarted;+ expect(mocks.update).toHaveBeenCalledTimes(8);+ release();+ expect(await result).toEqual({+ restoredIds: Array.from({ length: 25 }, (_, i) => String(i)).filter(+ (id) => id !== '3'+ ),+ failedIds: ['3'],+ });+ expect(peak).toBeLessThanOrEqual(8);+ expect(mocks.invalidateSoup).toHaveBeenCalledOnce();+ });++ it('preserves accepted restores when refreshing one thread fails', async () => {+ mocks.update.mockResolvedValue(ok(undefined));+ mocks.refresh.mockRejectedValueOnce(new Error('Refresh timed out'));+ expect(+ await restoreEmailFolderThreads({+ folder: 'spam',+ threadIds: ['one', 'two'],+ })+ ).toEqual({ restoredIds: ['one', 'two'], failedIds: [] });+ expect(mocks.invalidateSoup).toHaveBeenCalledOnce();+ });++ it('keeps writes and follow-up reads in the restore trace across batches', async () => {+ const dispatched: boolean[] = [];+ mocks.update.mockImplementation(async () => {+ dispatched.push(mocks.spanActive);+ await Promise.resolve();+ return ok(undefined);+ });+ for (const request of [+ mocks.refresh,+ mocks.invalidate,+ mocks.invalidateSoup,+ mocks.refreshLists,+ ]) {+ request.mockImplementation(async () => {+ dispatched.push(mocks.spanActive);+ await Promise.resolve();+ });+ }+ const ids = Array.from({ length: 9 }, (_, index) => String(index));+ expect(+ await restoreEmailFolderThreads({ folder: 'trash', threadIds: ids })+ ).toEqual({ restoredIds: ids, failedIds: [] });+ expect(dispatched).toHaveLength(38);+ expect(dispatched.every(Boolean)).toBe(true);+ expect(mocks.spanActive).toBe(false);+ });+});diff --git a/apps/web/src/lib/queries/email/folders.ts b/apps/web/src/lib/queries/email/folders.tsnew file mode 100644index 0000000000..485e3db8f9--- /dev/null+++ b/apps/web/src/lib/queries/email/folders.ts@@ -0,0 +1,96 @@+import { throwOnErr } from '@core/util/result';+import { Telemetry } from '@macro-inc/observability';+import { useMutation } from '@tanstack/solid-query';+import { queryClient } from '../client';+import { refreshActiveGraphqlSoupQueries } from '../soup/graphql/active-queries';+import { invalidateAllSoup } from '../soup/normalized-cache';+import {+ refreshEmailThreadCache,+ updateEmailThreadState,+} from './cache-cleanup';+import { emailKeys } from './keys';++const FOLDER_RESTORE_CONCURRENCY = 8;++type RestoreFolderThreads = {+ folder: 'spam' | 'trash';+ threadIds: string[];+};++/** Provider-neutral writes also preserve per-thread authorization and pending state. */+export function restoreEmailFolderThreads(input: RestoreFolderThreads) {+ return Telemetry.span('email.folder.restore', async (span) => {+ const ids = [...new Set(input.threadIds)];+ span.setAttr('email.folder', input.folder);+ span.setAttr('email.thread.count', ids.length);+ const restoredIds: string[] = [];+ const failedIds: string[] = [];+ // Bound provider writes and their follow-up reads even for select-all.+ for (+ let start = 0;+ start < ids.length;+ start += FOLDER_RESTORE_CONCURRENCY+ ) {+ const batch = ids.slice(start, start + FOLDER_RESTORE_CONCURRENCY);+ const outcomes = await span.run(() =>+ Promise.allSettled(+ batch.map((threadId) =>+ throwOnErr(() =>+ updateEmailThreadState({+ thread_id: threadId,+ field: input.folder === 'spam' ? 'junk' : 'trashed',+ value: false,+ })+ )+ )+ )+ );+ for (const [index, id] of batch.entries()) {+ if (outcomes[index].status === 'fulfilled') restoredIds.push(id);+ else failedIds.push(id);+ }+ }+ span.setAttr('email.restore.failed_count', failedIds.length);+ if (failedIds.length) span.error('Some mailbox restores failed');+ if (restoredIds.length) {+ for (+ let start = 0;+ start < restoredIds.length;+ start += FOLDER_RESTORE_CONCURRENCY+ ) {+ // A failed refresh cannot turn an accepted provider write into a failed+ // restore. Keep the outcome and invalidate the lists for another read.+ const refreshes = await Promise.allSettled(+ restoredIds+ .slice(start, start + FOLDER_RESTORE_CONCURRENCY)+ .map(async (id) => {+ await span.run(() => refreshEmailThreadCache(id));+ await span.run(() =>+ Promise.all([+ queryClient.invalidateQueries({+ queryKey: emailKeys.threadMessages(id).queryKey,+ }),+ queryClient.invalidateQueries({+ queryKey: emailKeys.threadOperations(id).queryKey,+ }),+ ])+ );+ })+ );+ if (refreshes.some((result) => result.status === 'rejected'))+ span.error('Mailbox restore refresh failed');+ }+ // A restored thread can enter lists it was absent from, so refresh REST+ // membership and only the GraphQL lists not maintained by the snapshot.+ span.run(invalidateAllSoup);+ await span.run(() =>+ refreshActiveGraphqlSoupQueries({ unmaintainedOnly: true })+ );+ }+ return { restoredIds, failedIds };+ });+}++export function useRestoreEmailFolderMutation() {+ return useMutation(() => ({ mutationFn: restoreEmailFolderThreads }));+}diff --git a/apps/web/src/lib/queries/email/read-state-graphql.test.tsx b/apps/web/src/lib/queries/email/read-state-graphql.test.tsxindex a7c0ae26e4..5c468647c7 100644--- a/apps/web/src/lib/queries/email/read-state-graphql.test.tsx+++ b/apps/web/src/lib/queries/email/read-state-graphql.test.tsx@@ -67,6 +67,7 @@ import {} from '@service-storage/graphql/generated/graphql';import { soupOptimisticResolvers } from '../optimistic-resolvers';import { registerGraphqlSoupRevalidations } from '../soup/graphql/active-queries';+import { soupKeys } from '../soup/keys';import { emailKeys } from './keys';import {trackExternalThreadArchive,@@ -141,6 +142,20 @@ describe('email read state with GraphQL Soup', () => {'propagates isRead=$read before the request settles (GraphQL=$graphql)',async ({ read, graphql }) => {mocks.graphqlEnabled = graphql;+ const folderKeys = ['spam', 'trash'].map(+ (emailView) =>+ soupKeys.astItems({+ params: {},+ body: { emailView },+ transport: 'rest',+ }).queryKey+ );+ const allKey = soupKeys.astItems({+ params: {},+ body: { emailView: 'all' },+ }).queryKey;+ for (const key of [...folderKeys, allKey])+ client.setQueryData(key, { pages: [] });let finish!: () => void;const network = new Promise<void>((resolve) => {finish = resolve;@@ -211,8 +226,11 @@ describe('email read state with GraphQL Soup', () => {finish();await result;}- // The cached record carries the change to every list.+ // Shared-cache lists stay local; isolated folder previews need a new read.expect(mocks.refresh).not.toHaveBeenCalled();+ for (const key of folderKeys)+ expect(client.getQueryState(key)?.isInvalidated).toBe(true);+ expect(client.getQueryState(allKey)?.isInvalidated).toBe(false);});diff --git a/apps/web/src/lib/queries/email/sync.ts b/apps/web/src/lib/queries/email/sync.tsindex 37d984e968..9bf0b625d4 100644--- a/apps/web/src/lib/queries/email/sync.ts+++ b/apps/web/src/lib/queries/email/sync.ts@@ -1,5 +1,6 @@import { toast } from '@core/component/Toast/Toast';import { ENABLE_INBOX_SYNC_STATUS } from '@core/constant/featureFlags';+import { fireAndForget } from '@core/util/fireAndForget';import { queryClient } from '@queries/client';import { invalidateAllSoup } from '@queries/soup/normalized-cache';import {@@ -10,6 +11,7 @@ import {} from '@service-email/generated/schemas';import { leadingAndTrailing, throttle } from '@solid-primitives/scheduled';import { clearBackfillProgress, setBackfillProgress } from './backfill';+import { invalidateEmailFolderQueries } from './folder-cache';import { emailKeys } from './keys';import { invalidateEmailLinks } from './link';@@ -21,6 +23,12 @@ const throttledBackfillSoupRefresh = leadingAndTrailing(BACKFILL_SOUP_REFRESH_INTERVAL);+const throttledFolderRefresh = leadingAndTrailing(+ throttle,+ () => fireAndForget(invalidateEmailFolderQueries(), 'email-folders'),+ BACKFILL_SOUP_REFRESH_INTERVAL+);+// The gateway double-encodes the payload, so callers must JSON-parse `data.data`// (via `withParsedWebsocketPayload`) before passing it here.function asRefreshEmailEvent(payload: unknown): RefreshEmailEvent | undefined {@@ -34,9 +42,8 @@ function asRefreshEmailEvent(payload: unknown): RefreshEmailEvent | undefined {/*** Handles `refresh_email` websocket events. Steady-state mutations* (`upsert_message`, `update_labels`, `delete_message`) already invalidate soup- * through the notification-driven path, and reacting to them again would- * double-refetch, so only `backfill_progress`, `backfill`, `link_removed`, and- * `photo_synced` act here.+ * through the notification-driven path. Spam/Trash use isolated REST previews,+ * so refresh those lists explicitly without refetching cache-maintained views.** Backfill produces no notifications, so these are its only refresh signals.* `backfill_progress` carries live progress: it refetches soup (throttled,@@ -55,6 +62,7 @@ export function handleRefreshEmail(payload: unknown): void {event.event === 'update_labels' ||event.event === 'delete_message') {+ throttledFolderRefresh();queryClient.invalidateQueries({queryKey: emailKeys.composeDraftState._def,});diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.tsindex 015eddda43..8cae23e842 100644--- a/apps/web/src/lib/queries/email/thread.ts+++ b/apps/web/src/lib/queries/email/thread.ts@@ -41,6 +41,7 @@ import { invalidateAllSoup } from '../soup/normalized-cache';import { type UndoHandle, useUndoableMutation } from '../undo';import { type MutationCallbacks, withCallbacks } from '../utils';import { updateEmailThreadState } from './cache-cleanup';+import { invalidateEmailFolderQueries } from './folder-cache';import {createGraphqlEmailThreadQuery,fetchGraphqlEmailThread,@@ -384,6 +385,7 @@ export function useMarkThreadAsSeenMutation(...withCallbacks<void, Error, MarkThreadAsSeenParams>({onMutate: threadSeenOnMutate,+ onSettled: () => invalidateEmailFolderQueries(),// Note: We intentionally don't invalidate thread messages in onSuccess.// The optimistic update already sets isRead in soup, and invalidating// thread messages triggers Suspense which resets scroll position.@@ -442,7 +444,10 @@ export function useMarkThreadAsUnreadMutation();},...withCallbacks<void, Error, MarkThreadAsUnreadParams>(- { onMutate: threadUnreadOnMutate },+ {+ onMutate: threadUnreadOnMutate,+ onSettled: () => invalidateEmailFolderQueries(),+ },callbacks),}));diff --git a/apps/web/src/lib/queries/soup/items.ts b/apps/web/src/lib/queries/soup/items.tsindex 7cc8eba2f3..32daa169a3 100644--- a/apps/web/src/lib/queries/soup/items.ts+++ b/apps/web/src/lib/queries/soup/items.ts@@ -80,6 +80,8 @@ interface SoupItemsQueryOptions {/** Seed mixed lists from indexed non-email members; keep the full server query. */graphqlLocalReconciliation?: 'without-email';meta?: {+ /** Keep view-specific REST previews out of the shared entity normalizer. */+ normalize?: boolean;groupBy?: GroupByField;groupKey?: string;itemFilter?: (item: SoupApiItem) => boolean;@@ -244,7 +246,8 @@ function restSoupAstItemsQueryOptions(enabled: boolean | undefined,staleTime: StaleTime | undefined,meta: RestSoupAstItemsMeta,- showSupportedForeignEntities: boolean | undefined+ showSupportedForeignEntities: boolean | undefined,+ keepPrevious: boolean | undefined) {const { params, body, groupBy, transport } = args;@@ -313,6 +316,7 @@ function restSoupAstItemsQueryOptions(// Retry remains available explicitly from that state.staleTime,placeholderData: (prev, prevQuery) => {+ if (keepPrevious === false) return undefined;// Keep the previous rows on screen while params/filters change, but// not across a grouping switch — the old groups would render under// the new grouping (e.g. status groups while assignee groups load).@@ -329,7 +333,7 @@ function restSoupAstItemsQueryOptions(meta: {...meta,groupBy,- normalize: true,+ normalize: meta?.normalize ?? true,},});}@@ -345,7 +349,8 @@ const useRestSoupAstItemsQuery = (options?.().enabled !== false && !options?.().networkPaused,options?.().staleTime,options?.().meta,- options?.().showSupportedForeignEntities+ options?.().showSupportedForeignEntities,+ options?.().keepPreviousData));};diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/previewView.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/previewView.tsindex a346ab4f14..9ac98f48a8 100644--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/previewView.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/previewView.ts@@ -14,6 +14,8 @@ export type PreviewView =| 'drafts'| 'starred'| 'all'+ | 'spam'+ | 'trash'| 'important'| 'other'| string;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/previewViewStandardLabel.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/previewViewStandardLabel.tsindex 393ca4151d..2b189e53a5 100644--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/previewViewStandardLabel.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/previewViewStandardLabel.ts@@ -15,6 +15,8 @@ export const PreviewViewStandardLabel = {drafts: 'drafts',starred: 'starred',all: 'all',+ spam: 'spam',+ trash: 'trash',important: 'important',other: 'other',} as const;diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.jsonindex fe30d6a7e6..4671c31a92 100644--- a/apps/web/src/lib/service-clients/service-email/openapi.json+++ b/apps/web/src/lib/service-clients/service-email/openapi.json@@ -7142,6 +7142,8 @@"drafts","starred","all",+ "spam",+ "trash","important","other"]@@ -7161,6 +7163,8 @@"drafts","starred","all",+ "spam",+ "trash","important","other"]diff --git a/apps/web/tests/e2e/email-folders.config.ts b/apps/web/tests/e2e/email-folders.config.tsnew file mode 100644index 0000000000..95935c17d5--- /dev/null+++ b/apps/web/tests/e2e/email-folders.config.ts@@ -0,0 +1,26 @@+import { defineConfig } from '@playwright/test';++export default defineConfig({+ testDir: '.',+ testMatch: 'email-folders.spec.ts',+ workers: 1,+ projects: [+ { name: 'desktop', use: { viewport: { width: 1200, height: 850 } } },+ {+ name: 'mobile-touch',+ use: {+ viewport: { width: 390, height: 844 },+ isMobile: true,+ hasTouch: true,+ },+ },+ ],+ use: {+ baseURL: process.env.EMAIL_FOLDERS_TEST_URL ?? 'http://127.0.0.1:43190',+ headless: true,+ launchOptions: {+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,+ },+ trace: 'retain-on-failure',+ },+});diff --git a/apps/web/tests/e2e/email-folders.spec.ts b/apps/web/tests/e2e/email-folders.spec.tsnew file mode 100644index 0000000000..71867fdbe4--- /dev/null+++ b/apps/web/tests/e2e/email-folders.spec.ts@@ -0,0 +1,164 @@+import { expect, type Page, test } from '@playwright/test';++async function mockFolderApi(page: Page, fail = false) {+ const restored = new Set<string>();+ const writes: { field: string; value: boolean; id: string }[] = [];+ await page.route('**/*', (route) => {+ const url = new URL(route.request().url());+ return url.hostname === '127.0.0.1' || url.hostname === 'localhost'+ ? route.continue()+ : route.fulfill({ status: 404, json: {} });+ });+ await page.route('**/items/soup/ast**', async (route) => {+ const { emailView } = route.request().postDataJSON();+ const items = ['Gmail', 'Outlook'].flatMap((provider, index) => {+ const id = `019f0000-0000-7000-8000-00000000000${index + 1}`;+ if (restored.has(`${emailView}:${id}`)) return [];+ return [+ {+ tag: 'emailThread',+ frecency_score: 0,+ is_favorited: false,+ data: {+ id,+ name: `${provider} folder message`,+ ownerId: 'macro|[email protected]',+ createdAt: '2026-10-01T12:00:00Z',+ updatedAt: '2026-10-01T12:00:00Z',+ sortTs: '2026-10-01T12:00:00Z',+ isRead: true,+ isDraft: false,+ isImportant: false,+ isSignal: false,+ inboxVisible: false,+ senderName: provider,+ senderEmail: '[email protected]',+ properties: [],+ labels: [],+ participants: [],+ attachments: [],+ },+ },+ ];+ });+ await route.fulfill({ json: { items, next_cursor: null } });+ });+ await page.route('**/email/threads/*/state', async (route) => {+ const { field, value } = route.request().postDataJSON();+ const id = new URL(route.request().url()).pathname.split('/').at(-2)!;+ writes.push({ field, value, id });+ if (fail)+ return route.fulfill({ status: 503, json: { message: 'Retry restore' } });+ restored.add(`${field === 'junk' ? 'spam' : 'trash'}:${id}`);+ await route.fulfill({ json: {} });+ });+ return writes;+}++test('restore controls work in Spam and Trash', async ({+ page,+ isMobile,+}, info) => {+ const writes = await mockFolderApi(page);+ await page.goto('/tests/e2e/fixtures/email-folders.html');+ const rows = page+ .getByRole('list', { name: 'Folder emails' })+ .getByRole('listitem');+ await expect(rows).toHaveCount(2);+ if (!isMobile) await rows.first().hover();+ await page+ .getByRole('button', { name: 'Not spam', exact: true })+ .first()+ .click();+ await expect(rows).toHaveCount(1);+ await expect(rows).toContainText('Outlook');+ await page.getByRole('button', { name: 'Trash', exact: true }).click();+ await expect(+ page.getByRole('heading', { name: 'Trash', exact: true })+ ).toBeVisible();+ await expect(rows).toHaveCount(2);+ if (!isMobile) await rows.last().hover();+ await page.screenshot({ path: info.outputPath('trash-controls.png') });+ await page+ .getByRole('button', { name: 'Restore', exact: true })+ .last()+ .click();+ await expect(rows).toHaveCount(1);+ await expect(rows).toContainText('Gmail');+ expect(writes.map(({ field, value }) => ({ field, value }))).toEqual([+ { field: 'junk', value: false },+ { field: 'trashed', value: false },+ ]);+});++test('restoring one row preserves other selected rows', async ({+ page,+ isMobile,+}) => {+ await mockFolderApi(page);+ await page.goto('/tests/e2e/fixtures/email-folders.html');+ const rows = page.getByRole('listitem');+ await expect(rows).toHaveCount(2);+ const selection = rows.last().getByRole('checkbox');+ await selection.click();+ if (!isMobile) await rows.first().hover();+ await rows+ .first()+ .getByRole('button', { name: 'Not spam', exact: true })+ .click();+ await expect(rows).toHaveCount(1);+ await expect(rows.first().getByRole('checkbox')).toBeChecked();+});++test('failed restore remains available for retry', async ({+ page,+ isMobile,+}) => {+ await mockFolderApi(page, true);+ await page.goto('/tests/e2e/fixtures/email-folders.html');+ const restore = page+ .getByRole('button', { name: 'Not spam', exact: true })+ .first();+ if (!isMobile) await page.getByRole('listitem').first().hover();+ await restore.click();+ await expect(page.getByRole('alert')).toContainText(+ 'Could not restore email'+ );+ await expect(restore).toBeEnabled();+ await expect(page.getByRole('listitem')).toHaveCount(2);+});++test('pending restore preserves a selection made in another folder', async ({+ page,+ isMobile,+}) => {+ await mockFolderApi(page);+ const started = Promise.withResolvers<void>();+ const released = Promise.withResolvers<void>();+ await page.route('**/email/threads/*/state', async (route) => {+ started.resolve();+ await released.promise;+ await route.fallback();+ });+ await page.goto('/tests/e2e/fixtures/email-folders.html');+ const rows = page+ .getByRole('list', { name: 'Folder emails' })+ .getByRole('listitem');+ await expect(rows).toHaveCount(2);+ if (!isMobile) await rows.first().hover();+ await page+ .getByRole('button', { name: 'Not spam', exact: true })+ .first()+ .click();+ await started.promise;+ await page.getByRole('button', { name: 'Trash', exact: true }).click();+ await expect(rows).toHaveCount(2);+ const selection = rows.last().getByRole('checkbox');+ await selection.click();+ await expect(selection).toBeChecked();+ released.resolve();+ await expect(+ page.getByRole('button', { name: 'Restore', exact: true }).last()+ ).toBeEnabled();+ await expect(selection).toBeChecked();+});diff --git a/apps/web/tests/e2e/fixtures/email-folders.html b/apps/web/tests/e2e/fixtures/email-folders.htmlnew file mode 100644index 0000000000..b3822424e6--- /dev/null+++ b/apps/web/tests/e2e/fixtures/email-folders.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Email folder controls</title></head>+ <body><div id="root"></div><script type="module" src="./email-folders.tsx"></script></body>+</html>diff --git a/apps/web/tests/e2e/fixtures/email-folders.tsx b/apps/web/tests/e2e/fixtures/email-folders.tsxnew file mode 100644index 0000000000..80e238c6e4--- /dev/null+++ b/apps/web/tests/e2e/fixtures/email-folders.tsx@@ -0,0 +1,188 @@+import '@fontsource-variable/inter';+import { QueryClientProvider } from '@tanstack/solid-query';+import { createSignal, For, Show, Suspense } from 'solid-js';+import { render } from 'solid-js/web';+import { PillTabs } from '../../../src/components/app/mobile/PillTabs';+import { createSelectionState } from '../../../src/components/list/create-selection-state';+import { ViewSidebar } from '../../../src/components/view-shell/ViewSidebar';+import { EmailRowActions } from '../../../src/features/email-view/components/EmailRowActions';+import {+ EMAIL_TABS,+ type EmailTab,+} from '../../../src/features/email-view/constants';+import { createEmailFolderRestore } from '../../../src/features/email-view/primitives/folder-restore';+import {+ ListEntity,+ ListLayoutProvider,+} from '../../../src/features/entity/composed/ListEntity';+import { isEmailEntity } from '../../../src/features/entity/types/entity';+import { TagSetsProvider } from '../../../src/features/property/tags/tag-sets-context';+import { AnalyticsContextProvider } from '../../../src/lib/analytics/analytics-context';+import { PosthogProvider } from '../../../src/lib/analytics/posthog';+import { EmailLinksContextProvider } from '../../../src/lib/core/context/emailLinks';+import { UserContextProvider } from '../../../src/lib/core/context/user';+import { queryClient } from '../../../src/lib/queries/client';+import '../../../src/index.css';++// Production REST folder query, semantic restore mutation, invalidation, and row+// controls. Playwright supplies deterministic provider responses at HTTP boundaries.+function FolderQueryFixture() {+ const [container, setContainer] = createSignal<HTMLElement>();+ const [tab, setTab] = createSignal<EmailTab>('spam');+ const selection = createSelectionState<string>({+ items: () => [],+ getKey: (id) => id,+ });+ function changeTab(next: EmailTab) {+ selection.clear();+ setTab(next);+ }+ const mutation = useRestoreEmailFolderMutation();+ const pending = () => mutation.isPending;+ const [error, setError] = createSignal('');+ const touch = navigator.maxTouchPoints > 0;+ document.documentElement.dataset.touchDevice = String(touch);+ const label = () => (tab() === 'spam' ? 'Not spam' : 'Restore');+ const query = useSoupAstItemsQuery(+ () =>+ buildEmailQuery({+ tab: tab(),+ inboxIds: undefined,+ facets: {},+ facetContext: { tagPropertyDefinitionByOptionId: new Map() },+ }),+ () => ({+ keepPreviousData: false,+ meta: { normalize: false, insertFilter: () => false },+ })+ );+ const rows = () => query.data?.entities.filter(isEmailEntity) ?? [];+ const restore = createEmailFolderRestore({+ tab,+ isPending: pending,+ selection: selection.keys,+ clearSelection: selection.clear,+ restore: async (input) => {+ setError('');+ return mutation.mutateAsync(input);+ },+ onRestored: () => {},+ onFailed: () => setError('Could not restore email. Try again.'),+ });++ return (+ <div class="flex h-screen bg-page text-ink">+ <Show when={!touch}>+ <div class="w-60 border-r border-edge p-3">+ <ViewSidebar.Root aria-label="Email navigation">+ <h1 class="p-2 text-sm font-medium">Email</h1>+ <ViewSidebar.Nav aria-label="Email tabs">+ <For each={EMAIL_TABS}>+ {(item) => (+ <ViewSidebar.Item+ active={tab() === item.id}+ onClick={() => changeTab(item.id)}+ >+ {item.label}+ </ViewSidebar.Item>+ )}+ </For>+ </ViewSidebar.Nav>+ </ViewSidebar.Root>+ </div>+ </Show>+ <main class="min-w-0 flex-1 p-4">+ <Show when={touch}>+ <PillTabs+ scrollable+ items={EMAIL_TABS.map((item) => ({+ value: item.id,+ label: item.label,+ }))}+ value={tab()}+ onChange={changeTab}+ />+ </Show>+ <h2 class="my-5 text-sm font-medium">+ {EMAIL_TABS.find((item) => item.id === tab())?.label}+ </h2>+ <Show when={error()}>+ <p role="alert">{error()}</p>+ </Show>+ <Suspense fallback={<p role="status">Loading folder…</p>}>+ <ul ref={setContainer} aria-label="Folder emails">+ <ListLayoutProvider ref={container} narrowLayout="inbox">+ <For each={rows()}>+ {(entity) => {+ const controls = () => (+ <EmailRowActions+ archived+ canArchive={false}+ canUnarchive={false}+ pending={pending()}+ onArchive={() => {}}+ onFocus={() => {}}+ onCommands={() => {}}+ restore={{+ label: label(),+ run: () =>+ restore([entity.id], { clearSelection: false }),+ }}+ />+ );+ return (+ <li>+ <ListEntity+ entity={entity}+ checked={selection.isSelected(entity.id)}+ onChecked={(checked) =>+ checked+ ? selection.select(entity.id)+ : selection.deselect(entity.id)+ }+ deferInteractions+ actions={controls()}+ touchActions={controls()}+ />+ </li>+ );+ }}+ </For>+ </ListLayoutProvider>+ </ul>+ </Suspense>+ </main>+ </div>+ );+}++function Fixture() {+ return (+ <QueryClientProvider client={queryClient}>+ <UserContextProvider>+ <EmailLinksContextProvider>+ <AnalyticsContextProvider>+ <PosthogProvider>+ <TagSetsProvider tagSets={() => []}>+ <FolderQueryFixture />+ </TagSetsProvider>+ </PosthogProvider>+ </AnalyticsContextProvider>+ </EmailLinksContextProvider>+ </UserContextProvider>+ </QueryClientProvider>+ );+}++// Initialize row components before app query adapters, matching app bootstrap+// order and avoiding the existing barrel-import cycles in the Vite fixture.+const { buildEmailQuery } = await import(+ '../../../src/features/email-view/queries/email-query'+);+const { useSoupAstItemsQuery } = await import(+ '../../../src/lib/queries/soup/items'+);+const { useRestoreEmailFolderMutation } = await import(+ '../../../src/lib/queries/email/folders'+);+render(Fixture, document.getElementById('root')!);diff --git a/apps/web/tests/native/README.md b/apps/web/tests/native/README.mdindex 8fc2111a62..ce6fd5f028 100644--- a/apps/web/tests/native/README.md+++ b/apps/web/tests/native/README.md@@ -125,10 +125,11 @@ is covered yet.All registered Email and Tasks tabs must have an explicit source classification.The nine Soup-backed Email tabs include Favorites and Archived; the three task-predicate tabs are My tasks, Created by me and All tasks. Scheduled email uses+predicate tabs are My tasks, All tasks and Created by me. Scheduled email usesthe scheduled-message service, Reminders gets membership from its reminder-collection, and Tasks → Projects uses a project collection. Those separate-surfaces are reported in `outsidePredicateMatrix`, not exercised through their+collection, Spam and Trash use network-backed provider folder pages, and+Tasks → My projects, All projects and Created by me use project collections.+Those separate surfaces are reported in `outsidePredicateMatrix`, not exercised through theirdormant Soup queries or claimed as offline predicate coverage. They need separatesource-specific tests. Adding an unclassified tab fails the registry guard.diff --git a/apps/web/tests/native/filter-matrix.ts b/apps/web/tests/native/filter-matrix.tsindex d1fe1e46ec..5ffb0bfb24 100644--- a/apps/web/tests/native/filter-matrix.ts+++ b/apps/web/tests/native/filter-matrix.ts@@ -93,15 +93,23 @@ const emailTabSources = {archived: 'soup',all: 'soup',focus: 'focus-list',+ spam: 'provider-folder-rest',+ trash: 'provider-folder-rest',} as const satisfies Record<(typeof EMAIL_TABS)[number]['id'],- 'soup' | 'scheduled-message-service' | 'reminder-collection' | 'focus-list'+ | 'soup'+ | 'scheduled-message-service'+ | 'reminder-collection'+ | 'provider-folder-rest'+ | 'focus-list'>;const taskTabSources = {'my-tasks': 'soup',- 'created-by-me': 'soup','team-tasks': 'soup',+ 'created-by-me': 'soup',+ 'my-projects': 'project-collection',projects: 'project-collection',+ 'created-projects': 'project-collection',} as const satisfies Record<(typeof TASK_TABS)[number]['id'],'soup' | 'project-collection'diff --git a/apps/web/tests/native/fixtures/filter-corpus.ts b/apps/web/tests/native/fixtures/filter-corpus.tsindex f4565c4db0..dc53eb477b 100644--- a/apps/web/tests/native/fixtures/filter-corpus.ts+++ b/apps/web/tests/native/fixtures/filter-corpus.ts@@ -329,6 +329,7 @@ export function filterCorpus(isSignal: n % 3 === 0,isImportant: n % 3 === 0,isDraft: false,+ hasReceivedMail: true,snippet: `Email ${n}`,senderEmail: '[email protected]',senderName: 'Sender',@@ -344,6 +345,7 @@ export function filterCorpus(mailSentPreview: n % 4 === 0 ? preview(30000, `Sent ${n}`) : null,notifications: [],participants: [],+ senders: [],labels: [],isFavorited: favorite,attachments: [diff --git a/apps/web/tests/native/fixtures/filter-oracle.test.ts b/apps/web/tests/native/fixtures/filter-oracle.test.tsindex 487b1c8e23..82d17156bf 100644--- a/apps/web/tests/native/fixtures/filter-oracle.test.ts+++ b/apps/web/tests/native/fixtures/filter-oracle.test.ts@@ -1,5 +1,5 @@import { expect, test } from 'bun:test';-import type { EmailTab } from '../../../src/features/email-view/constants';+import type { EmailTab } from '../../../src/features/email-view/tabs';import { filterCorpus, LINKS, TAGS } from './filter-corpus';import { ALL_INBOXES, emailMatchesSelection } from './filter-oracle';import { fixtureId } from './mail';@@ -52,7 +52,7 @@ test('All and Shared retain their distinct inbox and sharing scopes', () => {expect(matching('shared')).toEqual([60, 71, 72].map(fixtureId));});-test.each(['scheduled', 'reminders'] as const)(+test.each(['scheduled', 'reminders', 'spam', 'trash'] as const)('does not pretend the dormant Soup query owns the %s collection',(tab) => {expect(() => matching(tab)).toThrow(diff --git a/apps/web/tests/native/fixtures/filter-oracle.ts b/apps/web/tests/native/fixtures/filter-oracle.tsindex 60a57f6dac..6cdc5b6234 100644--- a/apps/web/tests/native/fixtures/filter-oracle.ts+++ b/apps/web/tests/native/fixtures/filter-oracle.ts@@ -1,5 +1,5 @@import { match } from 'ts-pattern';-import type { EmailTab } from '../../../src/features/email-view/constants';+import type { EmailTab } from '../../../src/features/email-view/tabs';import { type FixtureRow, LINKS } from './filter-corpus';import { USER_ID } from './mail';@@ -14,7 +14,13 @@ export function emailMatchesSelection(tab: EmailTab,selection: Record<string, string[]>): boolean {- if (tab === 'scheduled' || tab === 'reminders' || tab === 'focus') {+ if (+ tab === 'scheduled' ||+ tab === 'reminders' ||+ tab === 'focus' ||+ tab === 'spam' ||+ tab === 'trash'+ ) {throw new Error(`${tab} membership is not owned by the Soup query`);}if (row.kind !== 'email') return false;diff --git a/apps/web/tests/native/fixtures/mail.ts b/apps/web/tests/native/fixtures/mail.tsindex e47e176e3e..cf93589dd3 100644--- a/apps/web/tests/native/fixtures/mail.ts+++ b/apps/web/tests/native/fixtures/mail.ts@@ -15,6 +15,7 @@ export function fixtureMailAccount(return {id,macroId: USER_ID,+ provider: 'GMAIL',emailAddress,photoUrl: null,isPrimary,@@ -55,6 +56,7 @@ export const mail = [4, 6, 8, 9, 10, 12].map((n) => {isSignal: n % 3 === 0,isImportant: n % 3 === 0,isDraft: false,+ hasReceivedMail: true,snippet: `Fixture message ${n}`,senderEmail: '[email protected]',senderName: 'Fixture sender',@@ -66,6 +68,7 @@ export const mail = [4, 6, 8, 9, 10, 12].map((n) => {viewedAt: null,notifications: [],participants: [],+ senders: [],attachments: [],labels: [],properties: [],diff --git a/apps/web/tests/native/fixtures/server.test.ts b/apps/web/tests/native/fixtures/server.test.tsindex f819669eed..53d27b84fd 100644--- a/apps/web/tests/native/fixtures/server.test.ts+++ b/apps/web/tests/native/fixtures/server.test.ts@@ -70,11 +70,13 @@ test.each([false, true])((emailAddress, index) => ({id: fixtureId(1000 + index),macroId: USER_ID,+ provider: 'GMAIL',emailAddress,photoUrl: null,isPrimary: index === 0,needsReauth: false,draftIsSignal: false,+ sendAs: null,settings: { signature: null, signatureOnRepliesForwards: false },}))diff --git a/apps/web/tests/native/tsconfig.json b/apps/web/tests/native/tsconfig.jsonindex 24e1df2c35..e1112be84d 100644--- a/apps/web/tests/native/tsconfig.json+++ b/apps/web/tests/native/tsconfig.json@@ -3,6 +3,7 @@"target": "ESNext","module": "ESNext","moduleResolution": "bundler",+ "paths": { "@core/*": ["../../src/lib/core/*"] },"strict": true,"skipLibCheck": true,"noEmit": true,diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.mdindex 204e2f0219..5325a92cdc 100644--- a/crates/email/AGENTS.md+++ b/crates/email/AGENTS.md@@ -61,6 +61,9 @@ tools — hexagonal, heavily feature-gated.Synced Macro drafts in junk/trash must not advance All Mail timestamps.Filtered and unfiltered All Mail share the dynamic builder and its per-inboxordered, limited scans; do not add a separate whole-mailbox sort.+- Spam and Trash seed candidates from indexed provider labels/folder state plus pending positive moves, then recheck canonical mailbox facts before pagination. Order by the latest matching message date; metadata touches and unrelated replies must not move folder rows. Only Trash relaxes the default trash exclusion.+- Restore Outlook junk drafts to Drafts without Inbox membership; continue rejecting+ attempts to mark clean drafts as junk.- Reconcile deferred message deletion before claiming scheduled work; unresolved sends retain their message, attachments, and delivery job.- Durable send admission supports Gmail and Outlook; Outlook delivery stays with its provider coordinator.@@ -70,6 +73,7 @@ tools — hexagonal, heavily feature-gated.provider write per inbox holding only the messages whose labels changed(`stage_thread_labels` / `commit_thread_label_write` in`domain/service/thread_labels.rs`); route new label actions through them.+- Recompute thread metadata inside staged Gmail SPAM/TRASH writes so restored All Mail previews, ordering, and signal state do not wait for the provider worker.- `.eml` downloads go through `domain/message_source.rs`, which authorizes likeattachment reads and fetches the provider's original RFC 822 bytes (Gmail`format=raw`, Graph `$value`); drafts and unsynced messages have no source.diff --git a/crates/email/fixtures/email_folders.sql b/crates/email/fixtures/email_folders.sqlnew file mode 100644index 0000000000..c6acd3f974--- /dev/null+++ b/crates/email/fixtures/email_folders.sql@@ -0,0 +1,8 @@+INSERT INTO email_contacts (id, link_id, email_address, name) VALUES+ ('0d000000-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Sender'),+ ('0d000000-0000-0000-0000-000000000002', '0a000000-0000-0000-0000-000000000001', '[email protected]', 'Sender');++UPDATE email_messages m SET from_contact_id = c.id+FROM email_contacts c+WHERE c.link_id = m.link_id AND c.email_address = '[email protected]'+ AND m.id::text LIKE '0c000000-%';diff --git a/crates/email/src/domain/mailbox/commands.rs b/crates/email/src/domain/mailbox/commands.rsindex 1f2c5f7d01..69762fd0b5 100644--- a/crates/email/src/domain/mailbox/commands.rs+++ b/crates/email/src/domain/mailbox/commands.rs@@ -282,7 +282,13 @@ fn provider_action(}}MailboxAction::Junk(true) if !current.state.in_junk => FolderRole::Junk,- MailboxAction::Junk(false) if current.state.in_junk => FolderRole::Inbox,+ MailboxAction::Junk(false) if current.state.in_junk => {+ if current.state.is_draft {+ FolderRole::Drafts+ } else {+ FolderRole::Inbox+ }+ }_ => return Ok(None),};if destination == FolderRole::Archive && !folders.iter().any(|f| f.role == FolderRole::Archive)@@ -295,3 +301,6 @@ fn provider_action(.ok_or(EmailApiError::Conflict)?;Ok(Some(MessageAction::MoveToFolder(folder.id.clone())))}++#[cfg(test)]+mod test;diff --git a/crates/email/src/domain/mailbox/commands/test.rs b/crates/email/src/domain/mailbox/commands/test.rsnew file mode 100644index 0000000000..371363e5b2--- /dev/null+++ b/crates/email/src/domain/mailbox/commands/test.rs@@ -0,0 +1,35 @@+use super::*;+use email_api_client::domain::models::MailboxState;++#[test]+fn restoring_junk_chooses_drafts_for_drafts_and_inbox_for_received_mail() {+ let folders: Vec<_> = [("drafts", FolderRole::Drafts), ("inbox", FolderRole::Inbox)]+ .into_iter()+ .map(|(id, role)| MailFolder {+ id: ProviderId::try_from(id.to_string()).unwrap(),+ parent_id: None,+ name: id.into(),+ role,+ has_children: false,+ })+ .collect();+ for (is_draft, destination) in [(true, "drafts"), (false, "inbox")] {+ let current = MailboxOrganization {+ state: MailboxState {+ is_draft,+ in_junk: true,+ ..Default::default()+ },+ folder_id: None,+ tags: vec![],+ version: None,+ is_sent: false,+ };+ assert_eq!(+ provider_action(&MailboxAction::Junk(false), ¤t, &folders).unwrap(),+ Some(MessageAction::MoveToFolder(+ ProviderId::try_from(destination.to_string()).unwrap()+ ))+ );+ }+}diff --git a/crates/email/src/domain/models/mailbox_action.rs b/crates/email/src/domain/models/mailbox_action.rsindex 45fc107da8..8779014567 100644--- a/crates/email/src/domain/models/mailbox_action.rs+++ b/crates/email/src/domain/models/mailbox_action.rs@@ -101,10 +101,10 @@ impl MailboxAction {pending.in_junk = Some(false);pending.in_inbox = Some(!value && !m.is_draft);}- Self::Junk(value) if m.in_junk != *value && !m.is_draft => {+ Self::Junk(value) if m.in_junk != *value && (!m.is_draft || !value) => {pending.in_junk = Some(*value);pending.in_trash = Some(false);- pending.in_inbox = Some(!value);+ pending.in_inbox = Some(!value && !m.is_draft);}Self::Trashed(_) | Self::Junk(_) => return None,Self::Category { .. } => (),@@ -225,6 +225,33 @@ mod test {#[cfg(test)]mod restore_test {use super::*;+ #[test]+ fn junk_drafts_can_be_restored_but_clean_drafts_cannot_be_marked_junk() {+ let draft = MailboxActionMessage {+ id: Uuid::now_v7(),+ provider_id: Some("junk-draft".into()),+ is_sent: false,+ is_draft: true,+ is_read: true,+ in_inbox: false,+ in_trash: false,+ in_junk: true,+ is_present: true,+ };+ let targets = MailboxAction::Junk(false).targets(&[draft.clone()]);+ assert_eq!(targets.len(), 1);+ assert_eq!(targets[0].pending.in_junk, Some(false));+ assert_eq!(targets[0].pending.in_inbox, Some(false));+ assert!(+ MailboxAction::Junk(true)+ .targets(&[MailboxActionMessage {+ in_junk: false,+ ..draft+ }])+ .is_empty()+ );+ }+#[test]fn explicit_restore_targets_sent_correspondence_without_erasing_its_provenance() {let sent = MailboxActionMessage {diff --git a/crates/email/src/domain/models/preview.rs b/crates/email/src/domain/models/preview.rsindex 4429ce2f55..0b41991446 100644--- a/crates/email/src/domain/models/preview.rs+++ b/crates/email/src/domain/models/preview.rs@@ -34,6 +34,8 @@ pub enum PreviewViewStandardLabel {Drafts,Starred,All,+ Spam,+ Trash,Important,Other,}diff --git a/crates/email/src/domain/service/thread_labels.rs b/crates/email/src/domain/service/thread_labels.rsindex 9f55816712..7152bdf5b7 100644--- a/crates/email/src/domain/service/thread_labels.rs+++ b/crates/email/src/domain/service/thread_labels.rs@@ -115,7 +115,7 @@ whereanyhow::Error: From<T::Err>,anyhow::Error: From<E::Err>,{- pub(super) async fn change_thread_mailbox_state_impl(+ pub(crate) async fn change_thread_mailbox_state_impl(&self,actor: macro_user_id::user_id::MacroUserIdStr<'static>,thread_id: Uuid,diff --git a/crates/email/src/outbound/email_pg_repo/dynamic.rs b/crates/email/src/outbound/email_pg_repo/dynamic.rsindex 761f27a126..4885eefb72 100644--- a/crates/email/src/outbound/email_pg_repo/dynamic.rs+++ b/crates/email/src/outbound/email_pg_repo/dynamic.rs@@ -2,6 +2,7 @@//! email queries that filter content based on input AST (EmailLiteral).mod filters;+mod folders;mod query;mod resolve;diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs b/crates/email/src/outbound/email_pg_repo/dynamic/filters.rsindex 2ad8f10139..e83be7885d 100644--- a/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs+++ b/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs@@ -435,8 +435,13 @@ fn build_address_message_predicate(})}-/// Exclude physical trash and confirmed absent messages across all providers.-fn build_trash_check(_resolved: &ResolvedFilters) -> SqlFragment {+/// Exclude absent messages, and trash outside its explicit folder.+fn build_trash_check(resolved: &ResolvedFilters) -> SqlFragment {+ if resolved.include_trash {+ return SqlFragment::raw(+ "EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present)",+ );+ }SqlFragment::raw("EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash)",)@@ -924,6 +929,8 @@ pub(super) fn build_view_thread_filter(view: &PreviewView) -> SqlFragment {PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts)| PreviewView::StandardLabel(PreviewViewStandardLabel::Starred)| PreviewView::StandardLabel(PreviewViewStandardLabel::All)+ | PreviewView::StandardLabel(PreviewViewStandardLabel::Spam)+ | PreviewView::StandardLabel(PreviewViewStandardLabel::Trash)| PreviewView::StandardLabel(PreviewViewStandardLabel::Important)| PreviewView::UserLabel(_) => SqlFragment::empty(),PreviewView::StandardLabel(PreviewViewStandardLabel::Other) => {@@ -939,6 +946,12 @@ pub(super) fn build_view_message_filter(view: &PreviewView) -> SqlFragment {PreviewView::StandardLabel(PreviewViewStandardLabel::All) => SqlFragment::raw(" AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND NOT mf.in_junk)",),+ PreviewView::StandardLabel(PreviewViewStandardLabel::Spam) => SqlFragment::raw(+ " AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.in_junk)",+ ),+ PreviewView::StandardLabel(PreviewViewStandardLabel::Trash) => SqlFragment::raw(+ " AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.in_trash)",+ ),PreviewView::StandardLabel(PreviewViewStandardLabel::Sent) => {SqlFragment::raw(" AND m.is_sent = TRUE")}@@ -982,6 +995,9 @@ pub(super) fn build_view_message_filter(view: &PreviewView) -> SqlFragment {/// Returns the appropriate timestamp field to use for sorting based on the viewpub(super) fn get_sort_timestamp_field(view: &PreviewView) -> &'static str {match view {+ PreviewView::StandardLabel(+ PreviewViewStandardLabel::Spam | PreviewViewStandardLabel::Trash,+ ) => "folder.latest_folder_message_ts",PreviewView::StandardLabel(PreviewViewStandardLabel::Sent) => {"t.latest_outbound_message_ts"}diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/folders.rs b/crates/email/src/outbound/email_pg_repo/dynamic/folders.rsnew file mode 100644index 0000000000..34391936c8--- /dev/null+++ b/crates/email/src/outbound/email_pg_repo/dynamic/folders.rs@@ -0,0 +1,82 @@+//! Select sparse provider folder membership before resolving effective mailbox facts.++use crate::domain::models::{PreviewView, PreviewViewStandardLabel};+use sqlx::{Postgres, QueryBuilder};++pub(super) fn is_folder(view: &PreviewView) -> bool {+ matches!(+ view,+ PreviewView::StandardLabel(+ PreviewViewStandardLabel::Spam | PreviewViewStandardLabel::Trash+ )+ )+}++/// Raw provider state and pending positive intent form a superset. The canonical+/// facts view removes pending restores, provider-missing messages, and junk that+/// is also in Trash. No denormalized folder timestamp can go stale during rollout.+pub(super) fn push_folder_threads(+ builder: &mut QueryBuilder<'static, Postgres>,+ view: &PreviewView,+ mut push_scope: impl FnMut(&mut QueryBuilder<'static, Postgres>),+) {+ let (label, attribute, predicate) = match view {+ PreviewView::StandardLabel(PreviewViewStandardLabel::Spam) => {+ ("SPAM", "in_junk", "mf.in_junk AND NOT mf.in_trash")+ }+ PreviewView::StandardLabel(PreviewViewStandardLabel::Trash) => {+ ("TRASH", "in_trash", "mf.in_trash")+ }+ _ => unreachable!("folder candidate selection requires a folder view"),+ };+ builder+ .push(" FROM (SELECT fm.thread_id, MAX(fm.message_ts) AS latest_folder_message_ts FROM (");+ // All interpolated identifiers/JSON literals come from the closed view match.+ // Keep the JSON containment predicate literal so PostgreSQL can use its partial+ // index even in a prepared query. User-controlled scopes remain bind parameters.+ for source in 0..3 {+ if source > 0 {+ builder.push(" UNION ALL ");+ }+ builder.push(+ "SELECT m.id, m.thread_id, COALESCE(m.internal_date_ts, m.created_at) AS message_ts ",+ );+ match source {+ 0 => {+ builder.push(+ r#"FROM email_labels l+ JOIN email_message_labels ml ON ml.label_id = l.id+ JOIN email_messages m ON m.id = ml.message_id+ JOIN email_threads t ON t.id = m.thread_id AND t.link_id = m.link_id+ WHERE l.link_id = t.link_id AND l.provider_label_id = "#,+ );+ builder.push_bind(label);+ }+ 1 => {+ builder.push(format!(+ r#"FROM email_messages m+ JOIN email_threads t ON t.id = m.thread_id AND t.link_id = m.link_id+ WHERE m.mailbox_state @> '{{"{attribute}":true}}'::jsonb"#,+ ));+ }+ _ => {+ builder.push(+ r#"FROM email_pending_mailbox_state p+ JOIN email_messages m ON m.id = p.message_id+ JOIN email_threads t ON t.id = m.thread_id AND t.link_id = m.link_id+ WHERE p.desired = 'true'::jsonb AND p.attribute = "#,+ );+ builder.push_bind(attribute);+ }+ }+ builder.push(" AND ");+ push_scope(builder);+ }+ builder.push(format!(+ r#") fm+ JOIN email_message_mailbox_facts mf ON mf.id = fm.id+ WHERE mf.is_present AND {predicate}+ GROUP BY fm.thread_id) folder+ JOIN email_threads t ON t.id = folder.thread_id "#,+ ));+}diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/query.rs b/crates/email/src/outbound/email_pg_repo/dynamic/query.rsindex 2299f2bb52..401b0ed5d1 100644--- a/crates/email/src/outbound/email_pg_repo/dynamic/query.rs+++ b/crates/email/src/outbound/email_pg_repo/dynamic/query.rs@@ -47,6 +47,7 @@ struct ProjectScope {source_ids: Vec<String>,}+#[derive(Clone, Copy)]enum ThreadCandidateSource {Owned,Shared,@@ -114,6 +115,87 @@ fn push_shared_cte(builder: &mut QueryBuilder<'static, Postgres>, params: &Query);}+fn push_source_scope(+ builder: &mut QueryBuilder<'static, Postgres>,+ params: &QueryParams,+ source: ThreadCandidateSource,+ per_link_fanout: bool,+) {+ match source {+ ThreadCandidateSource::Owned => match params.team_id {+ // Normal per-mailbox query.+ None => {+ if per_link_fanout {+ builder.push("t.link_id = links.link_id");+ } else {+ builder.push("t.link_id = ANY(");+ builder.push_bind(params.link_ids.clone());+ builder.push(")");+ }+ }+ // CRM-scoped query: expand to every primary email_link owned by+ // any member of the team. Non-primary links (connected secondary+ // mailboxes, whose address differs from the owner's macro_id+ // email) are excluded. The receipt has already been validated+ // upstream, so the team_id is trusted here.+ //+ // resolve_filters pre-resolves the team's primary link ids: the+ // ANY probe gives the planner a tight static link set, and the+ // membership subquery revalidates it at execution time so a+ // member or link removed between resolve_filters and this query+ // can't leak threads (same belt-and-suspenders rationale as the+ // crm_enabled EXISTS below). The subquery alone remains as a+ // fallback for resolutions that didn't carry team links.+ Some(team_id) => {+ if let Some(team_links) = params.resolved.team_link_ids() {+ builder.push("t.link_id = ANY(");+ builder.push_bind(team_links.to_vec());+ builder.push(") AND ");+ }+ builder.push(+ r#"t.link_id IN (+ SELECT el.id+ FROM email_links el+ JOIN team_user tu ON tu.user_id = el.macro_id+ WHERE tu.team_id = "#,+ );+ builder.push_bind(team_id);+ builder.push(" AND el.is_primary)");+ }+ },+ ThreadCandidateSource::Shared => {+ builder.push("t.id IN (SELECT thread_id FROM SharedEmailThreads)");+ }+ // All threads in the requested projects, across every inbox — each+ // row gated on the caller's sources having an entity_access grant+ // on that row's project (same check as thread_access.rs Source 3).+ ThreadCandidateSource::Project => {+ let scope = params+ .project_scope+ .as_ref()+ .expect("Project candidate source requires project_scope");+ builder.push("t.project_id = ANY(");+ builder.push_bind(scope.project_ids.clone());+ builder.push(+ r#") AND EXISTS (+ SELECT 1 FROM entity_access pea+ WHERE pea.entity_id::text = t.project_id+ AND pea.entity_type = 'project'+ AND pea.source_id = ANY("#,+ );+ builder.push_bind(scope.source_ids.clone());+ builder.push("))");+ // Shared=Only means "not my own threads" — keep the project+ // widening for teammates' threads but exclude the caller's.+ if matches!(params.shared, SharedEmailFilter::Only) {+ builder.push(" AND NOT (t.link_id = ANY(");+ builder.push_bind(params.link_ids.clone());+ builder.push("))");+ }+ }+ }+}+fn push_thread_candidate_select(builder: &mut QueryBuilder<'static, Postgres>,view: &PreviewView,@@ -126,7 +208,11 @@ fn push_thread_candidate_select(// All Mail displays the latest eligible message date, even when a newer// junk/trash message or a read-state write updates the thread metadata.let updated_at_field = match view {- PreviewView::StandardLabel(PreviewViewStandardLabel::All) => sort_ts_field,+ PreviewView::StandardLabel(+ PreviewViewStandardLabel::All+ | PreviewViewStandardLabel::Spam+ | PreviewViewStandardLabel::Trash,+ ) => sort_ts_field,_ => "t.updated_at",};@@ -223,96 +309,21 @@ fn push_thread_candidate_select(builder.push(") AS is_own_link");}- if defer_uh {- builder.push(- r#"- FROM email_threads t- WHERE- "#,- );+ if super::folders::is_folder(view) {+ super::folders::push_folder_threads(builder, view, |builder| {+ push_source_scope(builder, params, source, per_link_fanout);+ });} else {+ builder.push(" FROM email_threads t ");+ }+ if !defer_uh {builder.push(- r#"- FROM email_threads t- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id- WHERE- "#,+ " LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id ",);}+ builder.push(" WHERE ");- match source {- ThreadCandidateSource::Owned => match params.team_id {- // Normal per-mailbox query.- None => {- if per_link_fanout {- builder.push("t.link_id = links.link_id");- } else {- builder.push("t.link_id = ANY(");- builder.push_bind(params.link_ids.clone());- builder.push(")");- }- }- // CRM-scoped query: expand to every primary email_link owned by- // any member of the team. Non-primary links (connected secondary- // mailboxes, whose address differs from the owner's macro_id- // email) are excluded. The receipt has already been validated- // upstream, so the team_id is trusted here.- //- // resolve_filters pre-resolves the team's primary link ids: the- // ANY probe gives the planner a tight static link set, and the- // membership subquery revalidates it at execution time so a- // member or link removed between resolve_filters and this query- // can't leak threads (same belt-and-suspenders rationale as the- // crm_enabled EXISTS below). The subquery alone remains as a- // fallback for resolutions that didn't carry team links.- Some(team_id) => {- if let Some(team_links) = params.resolved.team_link_ids() {- builder.push("t.link_id = ANY(");- builder.push_bind(team_links.to_vec());- builder.push(") AND ");- }- builder.push(- r#"t.link_id IN (- SELECT el.id- FROM email_links el- JOIN team_user tu ON tu.user_id = el.macro_id- WHERE tu.team_id = "#,- );- builder.push_bind(team_id);- builder.push(" AND el.is_primary)");- }- },- ThreadCandidateSource::Shared => {- builder.push("t.id IN (SELECT thread_id FROM SharedEmailThreads)");- }- // All threads in the requested projects, across every inbox — each- // row gated on the caller's sources having an entity_access grant- // on that row's project (same check as thread_access.rs Source 3).- ThreadCandidateSource::Project => {- let scope = params- .project_scope- .as_ref()- .expect("Project candidate source requires project_scope");- builder.push("t.project_id = ANY(");- builder.push_bind(scope.project_ids.clone());- builder.push(- r#") AND EXISTS (- SELECT 1 FROM entity_access pea- WHERE pea.entity_id::text = t.project_id- AND pea.entity_type = 'project'- AND pea.source_id = ANY("#,- );- builder.push_bind(scope.source_ids.clone());- builder.push("))");- // Shared=Only means "not my own threads" — keep the project- // widening for teammates' threads but exclude the caller's.- if matches!(params.shared, SharedEmailFilter::Only) {- builder.push(" AND NOT (t.link_id = ANY(");- builder.push_bind(params.link_ids.clone());- builder.push("))");- }- }- }+ push_source_scope(builder, params, source, per_link_fanout);// Belt-and-suspenders killswitch check that covers both the Owned and// Shared branches. Without this, a CRM-scoped request with@@ -441,8 +452,12 @@ fn push_thread_candidate_select(fn build_query(view: &PreviewView,email_filter: &Expr<EmailLiteral>,- params: QueryParams,+ mut params: QueryParams,) -> QueryBuilder<'static, Postgres> {+ params.resolved.include_trash = matches!(+ view,+ PreviewView::StandardLabel(PreviewViewStandardLabel::Trash)+ );let sort_ts_field = get_sort_timestamp_field(view);let view_message_filter = build_view_message_filter(view);// When neither ordering nor filtering needs view history, the@@ -669,9 +684,15 @@ fn build_query(builder.push_bind(params.query_limit);+ builder.push(") AS t");+ if super::folders::is_folder(view) {+ // Preserve the folder sort date inside mixed thread/message predicates+ // in the preview LATERAL, after the candidate relation has been limited.+ builder+ .push(" CROSS JOIN LATERAL (SELECT t.created_at AS latest_folder_message_ts) folder ");+ }builder.push(r#"- ) AS t-- Step 2: For each thread, find its latest message matching the filterCROSS JOIN LATERAL (SELECTdiff --git a/crates/email/src/outbound/email_pg_repo/dynamic/resolve.rs b/crates/email/src/outbound/email_pg_repo/dynamic/resolve.rsindex c9d565e2cd..21437b4f11 100644--- a/crates/email/src/outbound/email_pg_repo/dynamic/resolve.rs+++ b/crates/email/src/outbound/email_pg_repo/dynamic/resolve.rs@@ -6,6 +6,8 @@ use uuid::Uuid;/// Cache mailbox-scoped contact identities for address predicates and team scope.pub(super) struct ResolvedFilters {+ /// Only the explicit Trash view may admit present messages in trash.+ pub(super) include_trash: bool,/// Lowercased email address → all contact ids that match across the/// resolved scope (one link, or all team links). Empty Vec means the/// address has no matching contact anywhere in scope.@@ -51,6 +53,7 @@ impl ResolvedFilters {#[cfg(test)]pub(super) fn empty() -> Self {Self {+ include_trash: false,contact_ids: HashMap::new(),team_link_ids: None,}@@ -204,6 +207,7 @@ pub(super) async fn resolve_filters(}Ok(ResolvedFilters {+ include_trash: false,contact_ids,team_link_ids,})diff --git a/crates/email/src/outbound/email_pg_repo/label.rs b/crates/email/src/outbound/email_pg_repo/label.rsindex 37bcab409e..da7a490467 100644--- a/crates/email/src/outbound/email_pg_repo/label.rs+++ b/crates/email/src/outbound/email_pg_repo/label.rs@@ -273,6 +273,15 @@ pub(super) async fn stage_thread_label_change(write_id,).await?;++ // Folder changes immediately alter the canonical All Mail preview, sort,+ // and signal state; they must not wait for the Gmail worker's confirmation.+ if matches!(+ provider_label_id,+ system_labels::SPAM | system_labels::TRASH+ ) {+ super::thread::update_thread_metadata(&mut tx, thread_id, link_id).await?;+ }tx.commit().await?;Ok(Some(StagedLabelChange {diff --git a/crates/email/src/outbound/email_pg_repo/preview.rs b/crates/email/src/outbound/email_pg_repo/preview.rsindex 3f0d657108..533d1737e3 100644--- a/crates/email/src/outbound/email_pg_repo/preview.rs+++ b/crates/email/src/outbound/email_pg_repo/preview.rs@@ -50,7 +50,10 @@ pub(super) async fn previews_for_view_cursor(}(view @ PreviewView::StandardLabel(- PreviewViewStandardLabel::Sent | PreviewViewStandardLabel::All,+ PreviewViewStandardLabel::Sent+ | PreviewViewStandardLabel::All+ | PreviewViewStandardLabel::Spam+ | PreviewViewStandardLabel::Trash,),Either::Left(query),) => {diff --git a/crates/email/src/outbound/email_pg_repo/test.rs b/crates/email/src/outbound/email_pg_repo/test.rsindex f1107bed9a..26a6fa654c 100644--- a/crates/email/src/outbound/email_pg_repo/test.rs+++ b/crates/email/src/outbound/email_pg_repo/test.rs@@ -2,6 +2,7 @@ mod all_mail;mod crm_scope_dynamic_query;mod draft;mod dynamic_query;+mod folders;mod importance_pagination;mod labels;mod link;diff --git a/crates/email/src/outbound/email_pg_repo/test/folders.rs b/crates/email/src/outbound/email_pg_repo/test/folders.rsnew file mode 100644index 0000000000..e0bf91e5f1--- /dev/null+++ b/crates/email/src/outbound/email_pg_repo/test/folders.rs@@ -0,0 +1,324 @@+use super::*;+use macro_user_id::cowlike::CowLike;++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts(+ "email_dynamic_query",+ "email_outlook_threads",+ "email_all_mail",+ "email_folders"+ )+ )+)]+async fn gmail_folder_restore_refreshes_all_mail_before_provider_sync(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ use super::thread_archive::{RecordingEnqueuer, service_with_enqueuer};+ use crate::domain::models::mailbox_action::MailboxAction;++ let enqueuer = RecordingEnqueuer::default();+ let service = service_with_enqueuer(pool.clone(), enqueuer.clone());+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]")?.into_owned();+ let link = uuid::uuid!("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");++ for (thread, message, provider_id, label, folder, action, date) in [+ (+ uuid::uuid!("0b000000-0000-0000-0000-000000000103"),+ uuid::uuid!("0c000000-0000-0000-0000-000000000103"),+ "all-mail-message-1-3",+ "TRASH",+ PreviewViewStandardLabel::Trash,+ MailboxAction::Trashed(false),+ Utc.with_ymd_and_hms(2025, 6, 3, 0, 0, 0).unwrap(),+ ),+ (+ uuid::uuid!("0b000000-0000-0000-0000-000000000104"),+ uuid::uuid!("0c000000-0000-0000-0000-000000000104"),+ "all-mail-message-1-4",+ "SPAM",+ PreviewViewStandardLabel::Spam,+ MailboxAction::Junk(false),+ Utc.with_ymd_and_hms(2025, 6, 4, 0, 0, 0).unwrap(),+ ),+ ] {+ service+ .email_repo+ .insert_message_labels_batch(&[message], "Label_Work", link)+ .await?;+ let mut tx = pool.begin().await?;+ super::super::thread::update_thread_metadata(&mut tx, thread, link).await?;+ tx.commit().await?;+ assert!(+ service+ .email_repo+ .thread_by_id(thread)+ .await?+ .unwrap()+ .latest_non_spam_message_ts+ .is_none()+ );++ // Exercise the semantic action and real staged DB write. Repeating+ // a completed restore must not enqueue another write or add Inbox.+ for _ in 0..2 {+ service+ .change_thread_mailbox_state_impl(owner.clone(), thread, action.clone())+ .await?;+ }++ let restored = service.email_repo.thread_by_id(thread).await?.unwrap();+ assert_eq!(restored.latest_non_spam_message_ts, Some(date));+ assert!(!restored.inbox_visible);+ let labels = service.email_repo.labels_by_message_ids(&[message]).await?;+ assert_eq!(+ labels[&message]+ .iter()+ .map(|l| l.provider_label_id.as_str())+ .collect::<Vec<_>>(),+ ["Label_Work"]+ );++ for view in [folder, PreviewViewStandardLabel::All] {+ let rows = service+ .email_repo+ .previews_for_view_cursor(+ PreviewCursorQuery {+ view: PreviewView::StandardLabel(view),+ link_ids: vec![link],+ limit: 100,+ team_id: None,+ query: Query::new(None, SimpleSortMethod::UpdatedAt, None),+ },+ owner.clone(),+ )+ .await?;+ let row = rows.iter().find(|row| row.id == thread);+ if view == PreviewViewStandardLabel::All {+ assert_eq!(+ row.expect("restored thread belongs in All Mail").sort_ts,+ date+ );+ } else {+ assert!(row.is_none(), "restored thread leaves its folder");+ }+ }++ let writes = enqueuer.0.lock().unwrap();+ let matching: Vec<_> = writes+ .iter()+ .filter(|write| write.1.iter().any(|(id, _)| *id == message))+ .collect();+ assert_eq!(matching.len(), 1);+ assert_eq!(+ *matching[0],+ (+ link,+ vec![(message, provider_id.to_string())],+ vec![],+ vec![label.to_string()]+ )+ );+ }+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts(+ "email_dynamic_query",+ "email_outlook_threads",+ "email_all_mail",+ "email_folders"+ )+ )+)]+async fn provider_folders_match_messages_before_pagination(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());+ let viewer = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ for (link, prefix) in [+ (uuid::uuid!("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"), 100u128),+ (uuid::uuid!("0a000000-0000-0000-0000-000000000001"), 200u128),+ ] {+ let id = |suffix: u128| {+ Uuid::parse_str(&format!("0b000000-0000-0000-0000-{:012}", prefix + suffix)).unwrap()+ };+ for (folder, only, subject) in [+ (PreviewViewStandardLabel::Spam, id(4), "Newer spam"),+ (PreviewViewStandardLabel::Trash, id(3), "Newest trash"),+ ] {+ for filter in [+ None,+ Some(Arc::new(Expr::val(EmailLiteral::CalendarOnly(false)))),+ Some(Arc::new(Expr::val(EmailLiteral::Sender(Email::Complete(+ macro_user_id::email::EmailStr::parse_from_str("[email protected]")?+ .into_owned(),+ ))))),+ ] {+ let first = repo+ .previews_for_view_cursor(+ PreviewCursorQuery {+ view: PreviewView::StandardLabel(folder),+ link_ids: vec![link],+ limit: 1,+ team_id: None,+ query: Query::new(None, SimpleSortMethod::UpdatedAt, filter.clone()),+ },+ viewer.clone(),+ )+ .await?;+ assert_eq!(first.len(), 1);+ assert_eq!(first[0].id, id(2));+ assert_eq!(first[0].name.as_deref(), Some(subject));+ // Read state and newer mail outside this folder must not change its cursor.+ sqlx::query!("UPDATE email_threads SET is_read = NOT is_read, updated_at = now() WHERE id = ANY($1)", &[id(2), only]).execute(&pool).await?;+ sqlx::query!("UPDATE email_messages SET internal_date_ts = now() WHERE thread_id = $1 AND subject = 'Mixed normal mail'", id(2)).execute(&pool).await?;+ let next = repo+ .previews_for_view_cursor(+ PreviewCursorQuery {+ view: PreviewView::StandardLabel(folder),+ link_ids: vec![link],+ limit: 1,+ team_id: None,+ query: Query::new(+ Some(Cursor {+ id: id(2),+ limit: 1,+ val: CursorVal {+ sort_type: SimpleSortMethod::UpdatedAt,+ last_val: first[0].sort_ts,+ },+ filter: filter.clone(),+ }),+ SimpleSortMethod::UpdatedAt,+ filter,+ ),+ },+ viewer.clone(),+ )+ .await?;+ assert_eq!(next.len(), 1);+ assert_eq!(next[0].id, only);+ }+ }+ }+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts(+ "email_dynamic_query",+ "email_outlook_threads",+ "email_all_mail",+ "email_folders"+ )+ )+)]+async fn folder_candidates_respect_pending_moves_and_provider_absence(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link = uuid::uuid!("0a000000-0000-0000-0000-000000000001");+ let command = Uuid::now_v7();+ sqlx::query!("INSERT INTO email_mailbox_commands (id,link_id,generation,actor_id,intent,status) VALUES ($1,$2,1,'macro|[email protected]','{}','pending')", command, link).execute(&pool).await?;+ // A clean message pending a move enters Trash; both raw-trash messages+ // pending restoration leave it, even before provider confirmation.+ for (message, desired) in [(201, true), (203, false), (206, false)] {+ let message = Uuid::parse_str(&format!("0c000000-0000-0000-0000-{message:012}"))?;+ sqlx::query!("INSERT INTO email_pending_mailbox_state (message_id,attribute,command_id,desired) VALUES ($1,'in_trash',$2,$3)", message, command, serde_json::json!(desired)).execute(&pool).await?;+ }+ let repo = EmailPgRepo::new(pool.clone());+ let viewer = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let query = || PreviewCursorQuery {+ view: PreviewView::StandardLabel(PreviewViewStandardLabel::Trash),+ link_ids: vec![link],+ limit: 10,+ team_id: None,+ query: Query::new(None, SimpleSortMethod::UpdatedAt, None),+ };+ let rows = repo+ .previews_for_view_cursor(query(), viewer.clone())+ .await?;+ assert_eq!(+ rows.iter().map(|r| r.id).collect::<Vec<_>>(),+ [uuid::uuid!("0b000000-0000-0000-0000-000000000201")]+ );+ sqlx::query!("UPDATE email_messages SET mailbox_state = mailbox_state || '{\"provider_missing\":true}'::jsonb WHERE id = '0c000000-0000-0000-0000-000000000201'").execute(&pool).await?;+ assert!(+ repo.previews_for_view_cursor(query(), viewer)+ .await?+ .is_empty()+ );+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts(+ "email_dynamic_query",+ "email_outlook_threads",+ "email_all_mail",+ "email_folders"+ )+ )+)]+async fn folder_dates_and_shared_scope_use_the_selected_folder(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let thread = uuid::uuid!("0b000000-0000-0000-0000-000000000202");+ let viewer = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let repo = EmailPgRepo::new(pool.clone());+ let filter = Arc::new(Expr::and(+ Expr::val(EmailLiteral::Shared(item_filters::SharedEmailFilter::Only)),+ Expr::and(+ Expr::val(EmailLiteral::Sender(Email::Domain(+ "example.com".to_owned(),+ ))),+ Expr::val(EmailLiteral::UpdatedAt(DateLiteral::GreaterThan(+ Utc.with_ymd_and_hms(2025, 6, 4, 12, 0, 0).unwrap(),+ ))),+ ),+ ));+ for sort in [+ SimpleSortMethod::UpdatedAt,+ SimpleSortMethod::ViewedAt,+ SimpleSortMethod::ViewedUpdated,+ ] {+ let query = || PreviewCursorQuery {+ view: PreviewView::StandardLabel(PreviewViewStandardLabel::Spam),+ link_ids: vec![],+ limit: 10,+ team_id: None,+ query: Query::new(None, sort, Some(filter.clone())),+ };+ assert!(+ repo.previews_for_view_cursor(query(), viewer.clone())+ .await?+ .is_empty()+ );+ sqlx::query!("INSERT INTO entity_access (entity_id,entity_type,source_id,source_type,access_level) VALUES ($1,'email_thread',$2,'user','view')",thread,viewer.as_ref()).execute(&pool).await?;+ let rows = repo+ .previews_for_view_cursor(query(), viewer.clone())+ .await?;+ assert_eq!(rows.iter().map(|row| row.id).collect::<Vec<_>>(), [thread]);+ assert_eq!(rows[0].name.as_deref(), Some("Newer spam"));+ sqlx::query!(+ "DELETE FROM entity_access WHERE entity_id = $1 AND source_id = $2",+ thread,+ viewer.as_ref()+ )+ .execute(&pool)+ .await?;+ }+ Ok(())+}diff --git a/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs b/crates/email/src/outbound/email_pg_repo/test/thread_archive.rsindex 654469b442..7a585710ab 100644--- a/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs+++ b/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs@@ -48,7 +48,7 @@ async fn archive_publishes_one_user_attributed_event_after_commit(Ok(())}-fn service_with_enqueuer<E: EmailMessageEnqueuer>(+pub(super) fn service_with_enqueuer<E: EmailMessageEnqueuer>(pool: Pool<Postgres>,enqueuer: E,) -> EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>, E, NoOpCrmService, ()>@@ -70,9 +70,9 @@ type LabelWrite = (Uuid, Vec<(Uuid, String)>, Vec<String>, Vec<String>);/// Label writes and, in the same order, the pending write id each carried.#[derive(Clone, Default)]-struct RecordingEnqueuer(- Arc<std::sync::Mutex<Vec<LabelWrite>>>,- Arc<std::sync::Mutex<Vec<Uuid>>>,+pub(super) struct RecordingEnqueuer(+ pub(super) Arc<std::sync::Mutex<Vec<LabelWrite>>>,+ pub(super) Arc<std::sync::Mutex<Vec<Uuid>>>,);impl EmailMessageEnqueuer for RecordingEnqueuer {type Err = anyhow::Error;diff --git a/crates/macro_db_client/AGENTS.md b/crates/macro_db_client/AGENTS.mdindex e5161d71f3..1fb57caeae 100644--- a/crates/macro_db_client/AGENTS.md+++ b/crates/macro_db_client/AGENTS.md@@ -116,3 +116,6 @@ and kind constraints expand without rewriting existing rows and validate separatrefresh token bindings, pending authorizations, issued codes); their queries andexpiry sweep belong to `mcp_auth_proxy`. Rows carry `expires_at` and have noforeign keys; the broker deletes expired rows.++- Spam/Trash candidate indexes cover `email_messages(link_id, id)` only for the corresponding positive `mailbox_state` JSON containment predicate; keep query literals aligned with the partial-index predicates.+- If either concurrent folder-index migration is interrupted, inspect `pg_index.indisvalid` and drop only its invalid index before retrying; `CREATE INDEX IF NOT EXISTS` would silently preserve an unusable index.diff --git a/crates/macro_db_client/migrations/20261029060359_email_messages_junk_membership_index.sql b/crates/macro_db_client/migrations/20261029060359_email_messages_junk_membership_index.sqlnew file mode 100644index 0000000000..2239a6a8d6--- /dev/null+++ b/crates/macro_db_client/migrations/20261029060359_email_messages_junk_membership_index.sql@@ -0,0 +1,5 @@+-- no-transaction+-- Folder candidate selection must not scan every message in an inbox.+CREATE INDEX CONCURRENTLY email_messages_junk_membership+ON email_messages (link_id, id)+WHERE mailbox_state @> '{"in_junk":true}'::jsonb;diff --git a/crates/macro_db_client/migrations/20261029060403_email_messages_trash_membership_index.sql b/crates/macro_db_client/migrations/20261029060403_email_messages_trash_membership_index.sqlnew file mode 100644index 0000000000..b35d7e0ac5--- /dev/null+++ b/crates/macro_db_client/migrations/20261029060403_email_messages_trash_membership_index.sql@@ -0,0 +1,5 @@+-- no-transaction+-- Folder candidate selection must not scan every message in an inbox.+CREATE INDEX CONCURRENTLY email_messages_trash_membership+ON email_messages (link_id, id)+WHERE mailbox_state @> '{"in_trash":true}'::jsonb;diff --git a/crates/models_email/AGENTS.md b/crates/models_email/AGENTS.mdindex d24db92ed9..1c569ade31 100644--- a/crates/models_email/AGENTS.md+++ b/crates/models_email/AGENTS.md@@ -33,6 +33,9 @@ thread/message API types, DB row types, and Gmail API response shapes.Parsed message responses expose the draft generation captured in the same SQL snapshot as their content.+Preview wire names include `spam` and `trash`; provider folder semantics belong to+the email domain and use normalized mailbox facts, not Gmail-only label names.+## Related- Rules: `.agents/rules/rust/architecture.md`diff --git a/crates/models_email/src/email/service/thread.rs b/crates/models_email/src/email/service/thread.rsindex e0d726b36a..968669f026 100644--- a/crates/models_email/src/email/service/thread.rs+++ b/crates/models_email/src/email/service/thread.rs@@ -218,6 +218,8 @@ pub enum PreviewViewStandardLabel {Drafts,Starred,All,+ Spam,+ Trash,Important,Other,}diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 20574be545..6003e63a13 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -364,6 +364,38 @@ the backend schema containing `setEmailThreadArchived` andBrowser WASM and native cache builds must include the regenerated schema metadata;native offline archive support therefore requires a full app build, not just OTA.+### Spam and Trash++The desktop sidebar and mobile tabs include **Spam** and **Trash**. Spam reads+Gmail Spam or Outlook Junk; Trash reads Gmail Trash or Outlook Deleted Items.+Account, alias, and facet filters stay within the selected folder. Mixed threads+show their latest message in that folder, and folder membership is checked before+pagination. These views load server pages; full-text search and offline predicate+filtering are not available for them yet.++Spam and Trash order threads by their latest message in that folder. Reading a thread or receiving a newer message outside the folder does not change that folder cursor. Pending provider moves affect folder membership immediately.++Use **Not spam** on a Spam row or **Restore** on a Trash row. The same+action appears in the selection toolbar for bulk restores, including on mobile.+Outlook restores received mail to Inbox and provider drafts to Drafts. Gmail removes+the Spam or Trash label and preserves the remaining labels; it does not add Inbox.+Gmail restores update the canonical preview and ordering immediately, before the+queued provider write completes.+Outlook uses pending mailbox operations, and the thread's operation notice shows+provider confirmation or failure. Gmail uses the existing queued label-sync path+and does not expose those operation notices. A success toast means the request was+accepted, not that the provider has confirmed it. Read/unread actions and provider+sync events refresh the isolated folder lists. Outlook operation polling runs+while the thread is open; otherwise+folder refresh follows the provider sync event. The unread facet remains+thread-level, so an unread reply outside Spam can make its Spam row unread.+Bulk restores limit concurrent requests. Failed requests remain retryable, and a partial+bulk failure does not undo successful restores. While a restore is pending, switch+folders and select another row; completing the old restore must preserve the new+selection. The same applies to selecting different rows in the original folder.+Restoring an individual row also preserves selections on other rows.+No permanent-delete action is added.+### Cached Mail filteringThe per-query caches for email threads, channels, and native offline document@@ -402,7 +434,7 @@ headers use the selected Mail view's indexed timestamps, not a preview cached franother view. Drafts and Sent display their latest eligible message snapshot, evenwhen a newer normal message is the ALL preview; no message bodies are needed.Sent also requires a canonical outbound timestamp. Trashed messages cannot supply-any preview. All Mail also excludes spam/junk, including its cached preview and+these cached previews. All Mail also excludes spam/junk, including its cached preview andnon-draft baseline after draft edits. Mixed threads show the latest message outsidespam and trash; excluded messages must not consume a page slot. Drafts and Sentkeep their own canonical preview membership. Mail profiles v5/v6 require freshdiff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/PreviewView.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/PreviewView.mdindex cade66520b..2936c0e006 100644--- a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/PreviewView.md+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/PreviewView.md@@ -1,5 +1,5 @@# Type Alias: PreviewView-> **PreviewView** = `"inbox"` \| `"sent"` \| `"drafts"` \| `"starred"` \| `"all"` \| `"important"` \| `"other"` \| `string`+> **PreviewView** = `"inbox"` \| `"sent"` \| `"drafts"` \| `"starred"` \| `"all"` \| `"spam"` \| `"trash"` \| `"important"` \| `"other"` \| `string`View type. Supported values include standard labels and a custom user label user:<label>diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/PreviewViewStandardLabel.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/PreviewViewStandardLabel.mdindex 31f9bf2dc5..73c93fa154 100644--- a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/PreviewViewStandardLabel.md+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/PreviewViewStandardLabel.md@@ -1,3 +1,3 @@# Type Alias: PreviewViewStandardLabel-> **PreviewViewStandardLabel** = `"inbox"` \| `"sent"` \| `"drafts"` \| `"starred"` \| `"all"` \| `"important"` \| `"other"`+> **PreviewViewStandardLabel** = `"inbox"` \| `"sent"` \| `"drafts"` \| `"starred"` \| `"all"` \| `"spam"` \| `"trash"` \| `"important"` \| `"other"`diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.tsindex ab1573863b..b0a6438564 100644--- a/packages/sdk/generated/email/types.gen.ts+++ b/packages/sdk/generated/email/types.gen.ts@@ -1710,9 +1710,9 @@ export type PatchSettingsResponse = {/*** View type. Supported values include standard labels and a custom user label user:<label>*/-export type PreviewView = 'inbox' | 'sent' | 'drafts' | 'starred' | 'all' | 'important' | 'other' | string;+export type PreviewView = 'inbox' | 'sent' | 'drafts' | 'starred' | 'all' | 'spam' | 'trash' | 'important' | 'other' | string;-export type PreviewViewStandardLabel = 'inbox' | 'sent' | 'drafts' | 'starred' | 'all' | 'important' | 'other';+export type PreviewViewStandardLabel = 'inbox' | 'sent' | 'drafts' | 'starred' | 'all' | 'spam' | 'trash' | 'important' | 'other';/*** Payload for the `refresh_email` connection gateway event: identifies thediff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.jsonindex fe30d6a7e6..4671c31a92 100644--- a/packages/sdk/specs/email.json+++ b/packages/sdk/specs/email.json@@ -7142,6 +7142,8 @@"drafts","starred","all",+ "spam",+ "trash","important","other"]@@ -7161,6 +7163,8 @@"drafts","starred","all",+ "spam",+ "trash","important","other"]