Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): email inbox selector (#6939)
Peter Chinman3ddc66929b70
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex 7794953bb2..edc9bc8f44 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -222,7 +222,17 @@ registerComponent('email-compose', (params) => {.filter(Boolean);const draftID =typeof params.draftID === 'string' ? params.draftID : undefined;- return <EmailCompose draftId={draftID} initialTo={initialTo} />;+ const initialInboxId =+ typeof params.initialInboxId === 'string'+ ? params.initialInboxId+ : undefined;+ return (+ <EmailCompose+ draftId={draftID}+ initialTo={initialTo}+ initialInboxId={initialInboxId}+ />+ );});registerComponent('task-compose', (params) => {usePageViewTracking('task-compose');diff --git a/apps/web/src/features/email-compose/primitives/email-composer.test.ts b/apps/web/src/features/email-compose/primitives/email-composer.test.tsindex 1658d8fd79..e493e09830 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.test.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.test.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { message } from '../../email-message/tests/messages';import { decodeBase64Utf8 } from '../core/decode-base64';import { createComposeContext } from '../tests/capabilities';import { mountEmailComposer } from '../tests/composer';@@ -8,6 +9,105 @@ afterEach(() => vi.useRealTimers());// Real controller and editor, with only feature capabilities replaced.describe('standalone compose controller', () => {+ it.each([+ {+ initialInboxId: undefined,+ expectedId: 'inbox',+ expectedAddress: '[email protected]',+ },+ {+ initialInboxId: 'work',+ expectedId: 'work',+ expectedAddress: '[email protected]',+ },+ ])(+ 'uses $expectedAddress as the initial sender and saves to that inbox',+ async ({ initialInboxId, expectedId, expectedAddress }) => {+ const context = createComposeContext();+ context.accounts.inboxes = () => [+ { id: 'work', email_address: '[email protected]', settings: {} },+ { id: 'inbox', email_address: '[email protected]', settings: {} },+ ];+ const root = mountEmailComposer(context, undefined, { initialInboxId });+ try {+ expect(root.state.context.fromAddress?.()).toBe(expectedAddress);+ root.edit('Save with the selected sender');+ await vi.advanceTimersByTimeAsync(600);+ expect(context.drafts.saveDraft).toHaveBeenCalledWith(+ expect.objectContaining({ inboxId: expectedId })+ );+ } finally {+ root.dispose();+ }+ }+ );++ it('blocks sending when an explicit initial inbox cannot be resolved', async () => {+ const context = createComposeContext();+ const root = mountEmailComposer(context, undefined, {+ initialInboxId: 'removed-inbox',+ });+ try {+ root.edit('Send only from the selected inbox');+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(600);++ expect(root.state.context.fromAddress?.()).toBeUndefined();+ expect(root.state.context.validationError('no_link')).toMatchObject({+ type: 'no_link',+ message: 'Unable to find linked email account',+ });+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ } finally {+ root.dispose();+ }+ });++ it.each([undefined, 'missing-primary'])(+ 'falls back to the first inbox without an explicit selection when primary is %s',+ async (primaryId) => {+ const context = createComposeContext();+ context.accounts.primaryId = () => primaryId;+ const root = mountEmailComposer(context);+ try {+ root.edit('Use the default sender');+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);++ expect(root.state.context.fromAddress?.()).toBe('[email protected]');+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();+ expect(context.delivery.sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({ inboxId: 'inbox' })+ );+ } finally {+ root.dispose();+ }+ }+ );++ it('keeps a draft sender instead of the initial inbox and still allows a sender change', async () => {+ const context = createComposeContext();+ context.accounts.inboxes = () => [+ { id: 'inbox', email_address: '[email protected]', settings: {} },+ { id: 'work', email_address: '[email protected]', settings: {} },+ ];+ const root = mountEmailComposer(context, undefined, {+ draft: message('existing-draft', { is_draft: true, link_id: 'work' }),+ initialInboxId: 'inbox',+ });+ try {+ expect(root.state.context.fromAddress?.()).toBe('[email protected]');+ root.state.context.onSelectInbox?.('inbox');+ await vi.advanceTimersByTimeAsync(0);+ expect(root.state.context.fromAddress?.()).toBe('[email protected]');+ expect(context.drafts.saveDraft).toHaveBeenCalledWith(+ expect.objectContaining({ inboxId: 'inbox' })+ );+ } finally {+ root.dispose();+ }+ });+it('saves a composed draft after debounce and preserves the recipients and HTML', async () => {const context = createComposeContext();const root = mountEmailComposer(context);diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.tsindex 03c2278975..b19be12cfb 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts@@ -99,6 +99,8 @@ export type EmailComposerOptions = {onRecipientsChange?: (recipients: EmailRecipient[]) => void;/** Prefill for the To field (e.g. from an intercepted mailto: link). Ignored when editing an existing draft. */initialTo?: string[];+ /** Initial sending inbox for new messages. Existing drafts retain their sender. */+ initialInboxId?: string;};export function createEmailComposer(props: EmailComposerOptions) {@@ -127,14 +129,20 @@ export function createEmailComposer(props: EmailComposerOptions) {});+ if (!initialDraftId && props.initialInboxId) {+ form.setSelectedInbox(props.initialInboxId);+ }+const primaryInboxId = props.accounts.primaryId;const link = createMemo(() => {const inboxes = props.accounts.inboxes();if (inboxes.length === 0) return undefined;- // Send from the inbox the user picked, else the inbox that owns the draft- // being edited, else the primary inbox — not whichever inbox sorts first.- const targetId =- form.selectedInboxId() ?? props.draft?.link_id ?? primaryInboxId();+ // An explicit sender must resolve before sending from that account.+ const selectedInboxId = form.selectedInboxId();+ if (selectedInboxId !== undefined) {+ return inboxes.find((inbox) => inbox.id === selectedInboxId);+ }+ const targetId = props.draft?.link_id ?? primaryInboxId();return inboxes.find((inbox) => inbox.id === targetId) ?? inboxes[0];});diff --git a/apps/web/src/features/email-compose/tests/composer.ts b/apps/web/src/features/email-compose/tests/composer.tsindex 4e38c97394..3ba90ca06e 100644--- a/apps/web/src/features/email-compose/tests/composer.ts+++ b/apps/web/src/features/email-compose/tests/composer.ts@@ -13,7 +13,7 @@ import { createEmailEditor, setEmailEditorText } from './editor';export function mountEmailComposer(context: EmailComposeContext,host?: EmailComposeHost,- seed?: Pick<EmailComposerOptions, 'draft' | 'draftId'>+ seed?: Pick<EmailComposerOptions, 'draft' | 'draftId' | 'initialInboxId'>) {const root = createRoot((dispose) => ({dispose,diff --git a/apps/web/src/features/email-compose/views/email-compose.tsx b/apps/web/src/features/email-compose/views/email-compose.tsxindex 90eb6330d6..cc07feff6c 100644--- a/apps/web/src/features/email-compose/views/email-compose.tsx+++ b/apps/web/src/features/email-compose/views/email-compose.tsx@@ -29,6 +29,7 @@ export type EmailComposeViewProps = Pick<| 'recipientOptions'| 'onRecipientsChange'| 'initialTo'+ | 'initialInboxId'> & { context: EmailComposeContext };export function EmailComposeView(props: EmailComposeViewProps) {const composeContext = props.context;@@ -50,6 +51,7 @@ export function EmailComposeView(props: EmailComposeViewProps) {recipientOptions: props.recipientOptions,onRecipientsChange: props.onRecipientsChange,initialTo: props.initialTo,+ initialInboxId: props.initialInboxId,});const {editor,diff --git a/apps/web/src/features/email-view/components/EmailHeader.tsx b/apps/web/src/features/email-view/components/EmailHeader.tsxindex 5980c5c2f6..d3817bd0a9 100644--- a/apps/web/src/features/email-view/components/EmailHeader.tsx+++ b/apps/web/src/features/email-view/components/EmailHeader.tsx@@ -5,13 +5,14 @@ import {ViewShell,} from '@app/components/view-shell';import { SidebarCreateButton } from '@app/components/view-shell/SidebarCreateButton';+import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { createSignal, Show } from 'solid-js';import { composeEmail } from '../compose-email';import { EMAIL_TABS } from '../constants';import { useEmailView } from '../email-view-context';import { EmailControls } from './EmailControls';-import { EmailInboxMenu } from './EmailInboxSelector';+import { EmailInboxFilter, EmailInboxMenu } from './EmailInboxSelector';export type EmailHeaderProps = {/** Restores list focus when Escape leaves the search field. */@@ -47,13 +48,17 @@ export function EmailViewBreadcrumbItem() {export function EmailTopBar() {return (<ViewShell.TopBar>- <ViewBreadcrumbs.Outlet class="flex-1" aria-label="Email location" />+ <div class="flex min-w-0 flex-1 items-baseline gap-2">+ <ViewBreadcrumbs.Outlet aria-label="Email location" />+ <EmailInboxFilter class="@max-[720px]/view-shell:hidden" />+ </div></ViewShell.TopBar>);}export function EmailHeader(props: EmailHeaderProps) {const panel = useSplitPanelOrThrow();+ const { openWithSplit } = useSplitLayout();const { state, setState } = useEmailView();const [filterOpen, setFilterOpen] = createSignal(false);let searchInput: HTMLInputElement | undefined;@@ -85,14 +90,18 @@ export function EmailHeader(props: EmailHeaderProps) {return (<div class="flex min-w-0 flex-col">- <div class="mb-4 hidden h-8 min-w-0 items-center gap-2 @max-[720px]/view-shell:flex">- <h1 class="min-w-0 truncate text-xl font-semibold tracking-[-0.03em] text-ink">+ <div class="mb-4 hidden min-h-8 min-w-0 flex-wrap items-baseline gap-2 @max-[720px]/view-shell:flex">+ <h1 class="min-w-0 shrink-0 truncate text-xl font-semibold tracking-[-0.03em] text-ink">{selectedTabLabel()}</h1>- <div class="ml-auto flex shrink-0 items-center gap-2">+ <EmailInboxFilter class="@max-[480px]/view-shell:order-3 @max-[480px]/view-shell:w-full" />+ <div class="ml-auto flex shrink-0 items-center self-center gap-2"><EmailInboxMenu /><div class="shrink-0">- <SidebarCreateButton label="New" onCreate={() => composeEmail()} />+ <SidebarCreateButton+ label="New"+ onCreate={() => composeEmail(openWithSplit, state.inboxIds)}+ /></div></div></div>diff --git a/apps/web/src/features/email-view/components/EmailInboxSelector.tsx b/apps/web/src/features/email-view/components/EmailInboxSelector.tsxindex 7acb60f140..078bb2c51e 100644--- a/apps/web/src/features/email-view/components/EmailInboxSelector.tsx+++ b/apps/web/src/features/email-view/components/EmailInboxSelector.tsx@@ -4,6 +4,7 @@ import { inboxIconProps } from '@core/component/inboxIcon';import { UserIcon, type UserIconSize } from '@core/component/UserIcon';import { enableMultiInbox } from '@core/constant/featureFlags';import { useAddInboxFlow } from '@core/email-link';+import CaretDownIcon from '@phosphor/caret-down.svg';import CheckIcon from '@phosphor/check.svg';import PlusIcon from '@phosphor/plus.svg';import TrayIcon from '@phosphor/tray.svg';@@ -19,8 +20,7 @@ type InboxOption = { id: string; label: string; photoUrl?: string };/*** Single-select over the user's linked inboxes: one inbox, or all of them.* `undefined` in view state means all; a chosen inbox is stored as `[id]`.- * A stale multi-id selection persisted by the old picker still filters the- * list, and every included inbox reads as selected until the user picks one.+ * Legacy multi-id selections are normalized to their first inbox on restore.*/function useInboxSelection() {const { state, setInboxIds } = useEmailView();@@ -39,7 +39,9 @@ function useInboxSelection() {);const isAll = () => state.inboxIds === undefined;- const isSelected = (id: string) => state.inboxIds?.includes(id) ?? false;+ const hasMultipleInboxes = () => options().length > 1;+ const isSelected = (id: string) =>+ options().length === 1 || (state.inboxIds?.includes(id) ?? false);const selectedId = () => {const ids = state.inboxIds;return ids?.length === 1 ? ids[0] : undefined;@@ -53,8 +55,9 @@ function useInboxSelection() {return {options,- /** Shown whenever the flag is on or the user already has several inboxes. */- visible: () => multiInboxFlag().enabled || options().length > 1,+ /** Keep the connected account visible even when there is no choice to make. */+ visible: () => multiInboxFlag().enabled || options().length > 0,+ hasMultipleInboxes,canAddInbox: () => multiInboxFlag().enabled,addInbox: () => void addInbox(),isAll,@@ -91,8 +94,8 @@ function InboxAvatar(props: {}/**- * The inbox list at the top of the Email sidebar: `All inboxes` (with a- * `Connect another account` button beside it) followed by one row per inbox.+ * The inbox list at the top of the Email sidebar: `All inboxes` followed by+ * one row per inbox, with a separate action to connect another account.* Clicking a row selects that inbox alone; there is no multi-select.*/export function EmailInboxList(props: { class?: string }) {@@ -100,46 +103,125 @@ export function EmailInboxList(props: { class?: string }) {return (<Show when={selection.visible()}>- <ViewSidebar.Nav aria-label="Inboxes" class={props.class}>- <div class="flex min-w-0 items-center gap-1 pr-(--sidebar-action-inset)">- <ViewSidebar.Item- active={selection.isAll()}- aria-current={selection.isAll() ? 'true' : undefined}- class="min-w-0 flex-1"- {...pressHandlers(selection.selectAll)}- >- <ViewSidebar.Icon>- <TrayIcon class="size-4" />- </ViewSidebar.Icon>- <span class="truncate">All inboxes</span>- </ViewSidebar.Item>- <Show when={selection.canAddInbox()}>- <ViewSidebar.Control- type="button"- label="Connect another account"- {...pressHandlers(selection.addInbox)}- >- <PlusIcon class="size-4" />- </ViewSidebar.Control>- </Show>- </div>- <For each={selection.options()}>- {(option) => (+ <div+ class={cn(+ 'flex shrink-0 flex-col gap-(--sidebar-row-gap)',+ props.class+ )}+ >+ <ViewSidebar.Nav+ aria-label="Inboxes"+ class="max-h-[calc(4*var(--sidebar-row-height)+3*var(--sidebar-row-gap))] overflow-y-auto overscroll-none touch:max-h-[calc(11rem+3*var(--sidebar-row-gap))]"+ >+ <Show when={selection.hasMultipleInboxes()}><ViewSidebar.Item- active={selection.isSelected(option.id)}- aria-current={- selection.isSelected(option.id) ? 'true' : undefined- }- {...pressHandlers(() => selection.select(option.id))}+ active={selection.isAll()}+ aria-current={selection.isAll() ? 'true' : undefined}+ {...pressHandlers(selection.selectAll)}><ViewSidebar.Icon>- <InboxAvatar option={option} size="sm" class="size-5" />+ <Show+ when={selection.isAll()}+ fallback={<TrayIcon class="size-4" />}+ >+ <CheckIcon class="size-4 text-accent" />+ </Show></ViewSidebar.Icon>- <span class="truncate">{option.label}</span>+ <span class="truncate">All inboxes</span></ViewSidebar.Item>+ </Show>+ <For each={selection.options()}>+ {(option) => (+ <ViewSidebar.Item+ active={selection.isSelected(option.id)}+ aria-current={+ selection.isSelected(option.id) ? 'true' : undefined+ }+ {...pressHandlers(() => selection.select(option.id))}+ >+ <ViewSidebar.Icon>+ <Show+ when={selection.isSelected(option.id)}+ fallback={+ <InboxAvatar option={option} size="sm" class="size-5" />+ }+ >+ <CheckIcon class="size-4 text-accent" />+ </Show>+ </ViewSidebar.Icon>+ <span class="truncate">{option.label}</span>+ </ViewSidebar.Item>+ )}+ </For>+ </ViewSidebar.Nav>+ <Show when={selection.canAddInbox()}>+ <ViewSidebar.Item {...pressHandlers(selection.addInbox)}>+ <ViewSidebar.Icon>+ <PlusIcon class="size-4" />+ </ViewSidebar.Icon>+ <span class="truncate">Connect another account</span>+ </ViewSidebar.Item>+ </Show>+ </div>+ </Show>+ );+}++/** Visible account scope beside the list title; clearing restores all inboxes. */+export function EmailInboxFilter(props: { class?: string }) {+ const selection = useInboxSelection();++ return (+ <Show when={selection.hasMultipleInboxes() && selection.selectedOption()}>+ {(selected) => (+ <div+ class={cn(+ 'flex min-w-0 items-baseline gap-1 text-xs text-ink-muted',+ props.class)}- </For>- </ViewSidebar.Nav>+ >+ <span class="shrink-0">from</span>+ <Dropdown placement="bottom-start">+ <Dropdown.Trigger+ variant="ghost"+ size="sm"+ aria-label={`Switch inbox: ${selected().label}`}+ class="max-w-[min(16rem,30cqw)] text-sm font-semibold tracking-[-0.03em] text-ink @max-[720px]/view-shell:h-8 @max-[480px]/view-shell:max-w-[min(16rem,60cqw)]"+ >+ <span class="truncate">{selected().label}</span>+ <CaretDownIcon aria-hidden="true" class="size-3" />+ </Dropdown.Trigger>+ <Dropdown.Content class="min-w-56">+ <Dropdown.Group>+ <Dropdown.RadioGroup+ value={selected().id}+ onChange={(value) => {+ if (value === ALL_INBOXES_ID) selection.selectAll();+ else selection.select(value);+ }}+ >+ <InboxRadioItem+ value={ALL_INBOXES_ID}+ icon={<TrayIcon class="size-4" />}+ >+ All inboxes+ </InboxRadioItem>+ <For each={selection.options()}>+ {(option) => (+ <InboxRadioItem+ value={option.id}+ icon={<InboxAvatar option={option} size="sm" />}+ >+ {option.label}+ </InboxRadioItem>+ )}+ </For>+ </Dropdown.RadioGroup>+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ </div>+ )}</Show>);}@@ -162,7 +244,7 @@ export function EmailInboxMenu(props: { class?: string }) {};return (- <Show when={selection.visible()}>+ <Show when={selection.hasMultipleInboxes()}><Dropdown placement="bottom-end"><Dropdown.Triggervariant="ghost"@@ -249,7 +331,7 @@ export function EmailInboxDrawerSection(props: { value: string }) {const selection = useInboxSelection();return (- <Show when={selection.visible()}>+ <Show when={selection.hasMultipleInboxes()}><MobileFilterDrawer.Sectionvalue={props.value}label="Inbox"diff --git a/apps/web/src/features/email-view/components/EmailSidebar.tsx b/apps/web/src/features/email-view/components/EmailSidebar.tsxindex c20385da7b..f3e689f253 100644--- a/apps/web/src/features/email-view/components/EmailSidebar.tsx+++ b/apps/web/src/features/email-view/components/EmailSidebar.tsx@@ -1,6 +1,8 @@import { useViewTabHotkeys, ViewSidebar } from '@app/components/view-shell';-import { SidebarCreateHeader } from '@app/components/view-shell/SidebarCreateButton';+import { SidebarCreateButton } from '@app/components/view-shell/SidebarCreateButton';+import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { isTouchDevice } from '@core/mobile/isTouchDevice';import CalendarBlankIcon from '@phosphor/calendar-blank.svg';import ClockIcon from '@phosphor/clock.svg';import EnvelopeIcon from '@phosphor/envelope.svg';@@ -11,7 +13,7 @@ import SignalIcon from '@phosphor/wave-sine.svg';import NoiseIcon from '@phosphor/waveform.svg';import { SidebarTagsSection } from '@property/tags/SidebarTagsSection';import { pressHandlers } from '@ui';-import { type Component, For } from 'solid-js';+import { type Component, For, Show } from 'solid-js';import { Dynamic } from 'solid-js/web';import { composeEmail } from '../compose-email';import { EMAIL_TAB_IDS, EMAIL_TABS, type EmailTabItem } from '../constants';@@ -61,6 +63,7 @@ export function EmailNavigation(props: { onNavigate?: () => void }) {export function EmailSidebar() {const panel = useSplitPanelOrThrow();+ const { openWithSplit } = useSplitLayout();const {state,setTab,@@ -79,15 +82,23 @@ export function EmailSidebar() {return (<ViewSidebar.Root aria-label="Email navigation">- <SidebarCreateHeader- title="Email"- label="New email"- onCreate={() => composeEmail()}- />+ <Show when={!isTouchDevice()}>+ <ViewSidebar.Header>+ <div class="flex min-w-0 items-center gap-1">+ <ViewSidebar.CloseButton class="shrink-0" />+ <ViewSidebar.Title>Email</ViewSidebar.Title>+ </div>+ </ViewSidebar.Header>+ </Show><ViewSidebar.Content><EmailInboxList />+ <SidebarCreateButton+ label="New email"+ onCreate={() => composeEmail(openWithSplit, state.inboxIds)}+ />+<EmailNavigation /><SidebarTagsSectiondiff --git a/apps/web/src/features/email-view/compose-email.ts b/apps/web/src/features/email-view/compose-email.tsindex 006ca19d1d..2489fce508 100644--- a/apps/web/src/features/email-view/compose-email.ts+++ b/apps/web/src/features/email-view/compose-email.ts@@ -1,9 +1,22 @@-import { runCreateAction } from '@app/features/command/Launcher';+import { EMAIL_COMPOSE_TO_INPUT_ID } from '@app/features/email-compose/core/constants';+import type { useSplitLayout } from '@components/app/split-layout/layout';+import { triggerFocusInput } from '@core/directive/focusInput';-/**- * Opens a new email compose from the Email view, the same way the legacy- * mail toolbar's create button does (in the split, focusing the To field).- */-export function composeEmail() {- runCreateAction('email', { source: 'email_view' });+/** Opens a new email from the current inbox scope, focusing the To field. */+export function composeEmail(+ openWithSplit: ReturnType<typeof useSplitLayout>['openWithSplit'],+ inboxIds?: string[]+) {+ triggerFocusInput(() => document.getElementById(EMAIL_COMPOSE_TO_INPUT_ID));+ openWithSplit(+ {+ type: 'component',+ id: 'email-compose',+ params: {+ initialInboxId: inboxIds?.length === 1 ? inboxIds[0] : undefined,+ },+ preserveParams: true,+ },+ { preferNewSplit: false }+ );}diff --git a/apps/web/src/features/email-view/email-view-context.test.tsx b/apps/web/src/features/email-view/email-view-context.test.tsxnew file mode 100644index 0000000000..9ef8059e23--- /dev/null+++ b/apps/web/src/features/email-view/email-view-context.test.tsx@@ -0,0 +1,131 @@+import { cleanup, render } from '@solidjs/testing-library';+import { createStore } from 'solid-js/store';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ type EmailViewContext,+ EmailViewProvider,+ useEmailView,+} from './email-view-context';++const mocks = vi.hoisted(() => ({+ navigate: vi.fn(),+ useRouteParams: vi.fn(),+ useEmailLinksQuery: vi.fn(),+}));++vi.mock('@app/components/list', () => ({+ createListController: () => ({}),+ listOwnedSlotName: (name: string) => name,+}));+vi.mock('@app/components/view-shell', () => ({}));+vi.mock('@app/features/next-soup/soup-view/inbox-filter-controllers', () => ({+ registerInboxFilterSplit: () => () => {},+}));+vi.mock(+ '@app/features/soup',+ async () => import('../soup/filters/facets/selection')+);+vi.mock('@app/features/soup/collection/list-navigation-source', () => ({+ registerListNavigationSource: () => {},+}));+vi.mock('@app/lib/persistence', () => ({+ makePersistedState: <T,>(store: T) => store,+}));+vi.mock('@app/lib/split-router', () => ({+ useNavigate: () => mocks.navigate,+ useRouteParams: () => mocks.useRouteParams(),+ createSearchParams: () => [{ tab: 'important' }],+}));+vi.mock('@components/app/createPreviewSelectionGuard', () => ({+ createPreviewSelectionGuard: () =>+ Object.assign(() => true, { canSelect: () => true }),+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({ handle: { id: 'mail-panel' } }),+ withSplitPanelOwner: (_slot: string, create: () => unknown) => create(),+}));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user' }));+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));+vi.mock('@property/tags/tag-sets-context', () => ({+ useTagSets: () => () => [],+ useTagSetsReady: () => () => true,+}));+vi.mock('@queries/email/link', () => ({+ useEmailLinksQuery: () => mocks.useEmailLinksQuery(),+}));+vi.mock('./persistence', () => ({ createEmailViewPersistence: () => ({}) }));+vi.mock('./queries/use-email-query', () => ({+ useEmailDataSource: () => ({ items: () => [] }),+}));+vi.mock('./route', () => ({+ emailSplitRoute: { id: 'view-mail' },+ emailThreadRoute: { id: 'mail-thread' },+}));+vi.mock('./email-route', () => ({+ emailTabSearch: { namespace: 'mail' },+ emailDetailSearch: { namespace: 'email-detail' },+ emailTabSearchCodec: { serialize: (value: unknown) => value },+}));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++function mount() {+ const [linksQuery, setLinksQuery] = createStore({+ isSuccess: false,+ data: { links: [] as { id: string }[] },+ });+ const [params, setParams] = createStore<{ threadId?: string }>({+ threadId: 'open-thread',+ });+ mocks.useEmailLinksQuery.mockReturnValue(linksQuery);+ mocks.useRouteParams.mockReturnValue(params);+ mocks.navigate.mockImplementation(+ (target: { params: { threadId?: string } }) =>+ setParams('threadId', target.params.threadId)+ );+ let view!: EmailViewContext;+ function ReadContext() {+ view = useEmailView();+ return null;+ }+ render(() => (+ <EmailViewProvider initialState={{ inboxIds: ['saved-inbox'] }}>+ <ReadContext />+ </EmailViewProvider>+ ));+ return { view, setLinksQuery };+}++describe('email view inbox reconciliation', () => {+ it.each([{ links: [] }, { links: [{ id: 'remaining-inbox' }] }])(+ 'preserves the thread when loaded accounts invalidate the saved scope: %j',+ ({ links }) => {+ const { view, setLinksQuery } = mount();+ expect(view.state.inboxIds).toEqual(['saved-inbox']);+ expect(view.selectedThread()?.id).toBe('open-thread');++ setLinksQuery({ isSuccess: true, data: { links } });++ expect(view.state.inboxIds).toBeUndefined();+ expect(view.selectedThread()?.id).toBe('open-thread');+ expect(mocks.navigate).not.toHaveBeenCalled();+ }+ );++ it('still closes the thread when the user explicitly selects All inboxes', () => {+ const { view, setLinksQuery } = mount();+ setLinksQuery({+ isSuccess: true,+ data: { links: [{ id: 'saved-inbox' }] },+ });++ view.setInboxIds(undefined);++ expect(view.state.inboxIds).toBeUndefined();+ expect(view.selectedThread()).toBeUndefined();+ expect(mocks.navigate).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/features/email-view/email-view-context.tsx b/apps/web/src/features/email-view/email-view-context.tsxindex 6b137b2e29..13a4c29e62 100644--- a/apps/web/src/features/email-view/email-view-context.tsx+++ b/apps/web/src/features/email-view/email-view-context.tsx@@ -24,6 +24,7 @@ import { createAssertedContextProvider } from '@core/context/createContext';import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { useTagSets, useTagSetsReady } from '@property/tags/tag-sets-context';+import { useEmailLinksQuery } from '@queries/email/link';import type { ContextProviderProps } from '@solid-primitives/context';import {type Accessor,@@ -45,7 +46,9 @@ import {emailTabSearch,emailTabSearchCodec,} from './email-route';+import { normalizeInboxSelection } from './inbox-selection';import { createEmailViewPersistence } from './persistence';+import { createInboxSelectionReconciliation } from './primitives/inbox-selection-reconciliation';import {type EmailDataSource,type EmailDataSourceItem,@@ -123,8 +126,7 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<createStore<EmailViewState>({tab: initial.tab ?? DEFAULT_EMAIL_TAB,search: initial.search ?? '',- inboxIds:- initial.inboxIds === undefined ? undefined : [...initial.inboxIds],+ inboxIds: normalizeInboxSelection(initial.inboxIds),facets: normalizeFacetSelection(initial.facets),collapsedSidebarSectionIds: [...(initial.collapsedSidebarSectionIds ?? []),@@ -311,9 +313,19 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<const setInboxIds = (ids: string[] | undefined) => {closeThread();- setState('inboxIds', ids === undefined ? undefined : [...ids]);+ setState('inboxIds', normalizeInboxSelection(ids));};+ // This belongs to the view lifecycle, even while every inbox picker is unmounted.+ const linksQuery = useEmailLinksQuery();+ createInboxSelectionReconciliation({+ selectedIds: () => state.inboxIds,+ loadedLinks: () =>+ linksQuery.isSuccess ? linksQuery.data.links : undefined,+ // Widening stale scope to all inboxes should preserve the current thread.+ clearSelection: () => setState('inboxIds', undefined),+ });+const setFacets = (facets: EmailViewState['facets']) => {closeThread();setState('facets', reconcile(normalizeFacetSelection(facets)));diff --git a/apps/web/src/features/email-view/inbox-selection.test.ts b/apps/web/src/features/email-view/inbox-selection.test.tsnew file mode 100644index 0000000000..4339127909--- /dev/null+++ b/apps/web/src/features/email-view/inbox-selection.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';+import { normalizeInboxSelection } from './inbox-selection';++describe('inbox selection migration', () => {+ it('chooses the first saved inbox without changing the input', () => {+ const saved = ['inbox-b', 'inbox-a'];+ expect(normalizeInboxSelection(saved)).toEqual(['inbox-b']);+ expect(saved).toEqual(['inbox-b', 'inbox-a']);+ });++ it('preserves a single selected inbox', () => {+ expect(normalizeInboxSelection(['inbox-a'])).toEqual(['inbox-a']);+ });++ it('restores All inboxes for empty or cleared selections', () => {+ expect(normalizeInboxSelection([])).toBeUndefined();+ expect(normalizeInboxSelection(undefined)).toBeUndefined();+ });+});diff --git a/apps/web/src/features/email-view/inbox-selection.ts b/apps/web/src/features/email-view/inbox-selection.tsnew file mode 100644index 0000000000..61ac1dbe1a--- /dev/null+++ b/apps/web/src/features/email-view/inbox-selection.ts@@ -0,0 +1,6 @@+/** Restore legacy multi-selections as one inbox; an empty selection means all. */+export function normalizeInboxSelection(+ ids: readonly string[] | undefined+): string[] | undefined {+ return ids?.length ? ids.slice(0, 1) : undefined;+}diff --git a/apps/web/src/features/email-view/persistence.ts b/apps/web/src/features/email-view/persistence.tsindex be1dc11872..cadfe6981d 100644--- a/apps/web/src/features/email-view/persistence.ts+++ b/apps/web/src/features/email-view/persistence.ts@@ -12,6 +12,7 @@ import {import { createUserScopedStorage } from '@core/util/userScopedStorage';import type { Accessor } from 'solid-js';import { z } from 'zod';+import { normalizeInboxSelection } from './inbox-selection';import type { EmailViewState } from './types';const EMAIL_ENTRY_STATE_KEY = 'email.view';@@ -52,7 +53,11 @@ const emailEntryStateSchema = emailEntryStateSchemaWithDefaults.catch(// The legacy mail view stores the raw `string[] | undefined` under its key;// anything else restores as "every inbox".-const inboxIdsEntrySchema = z.array(z.string()).optional().catch(undefined);+const inboxIdsEntrySchema = z+ .array(z.string())+ .optional()+ .catch(undefined)+ .transform(normalizeInboxSelection);const emailListStateSchemaWithDefaults = z.object({version: z.literal(1).default(1),@@ -127,7 +132,7 @@ function selectLocalState(state: EmailViewState): EmailLocalState {return {version: 1,tab: state.tab,- ...(state.inboxIds === undefined ? {} : { inboxIds: [...state.inboxIds] }),+ inboxIds: normalizeInboxSelection(state.inboxIds),facets: normalizeFacetSelection(state.facets),};}diff --git a/apps/web/src/features/email-view/primitives/inbox-selection-reconciliation.test.ts b/apps/web/src/features/email-view/primitives/inbox-selection-reconciliation.test.tsnew file mode 100644index 0000000000..04678f3c0f--- /dev/null+++ b/apps/web/src/features/email-view/primitives/inbox-selection-reconciliation.test.ts@@ -0,0 +1,77 @@+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import { createInboxSelectionReconciliation } from './inbox-selection-reconciliation';++// No picker or drawer is mounted: reconciliation belongs to the view's lifetime.+function mount(selected: string[] | undefined = ['saved-inbox']) {+ return createRoot((dispose) => {+ const [selectedIds, setSelectedIds] = createSignal<string[] | undefined>(+ selected+ );+ const [loadedLinks, setLoadedLinks] = createSignal<{ id: string }[]>();+ const clearSelection = vi.fn(() => setSelectedIds(undefined));+ createInboxSelectionReconciliation({+ selectedIds,+ loadedLinks,+ clearSelection,+ });+ return {+ dispose,+ selectedIds,+ setSelectedIds,+ setLoadedLinks,+ clearSelection,+ };+ });+}++describe('inbox reconciliation without mounted pickers', () => {+ it.each([{ links: [] }, { links: [{ id: 'remaining-inbox' }] }])(+ 'clears a removed saved inbox after links load, including when no accounts remain: %j',+ ({ links }) => {+ const view = mount();+ try {+ expect(view.selectedIds()).toEqual(['saved-inbox']);+ expect(view.clearSelection).not.toHaveBeenCalled();+ view.setLoadedLinks(links);+ expect(view.selectedIds()).toBeUndefined();+ expect(view.clearSelection).toHaveBeenCalledOnce();+ } finally {+ view.dispose();+ }+ }+ );++ it('retains a valid selection through unavailable results and clears it when a later successful result removes it', () => {+ const view = mount();+ try {+ view.setLoadedLinks([{ id: 'saved-inbox' }]);+ expect(view.clearSelection).not.toHaveBeenCalled();+ // Pending and failed queries both expose no successfully loaded links.+ view.setLoadedLinks(undefined);+ expect(view.selectedIds()).toEqual(['saved-inbox']);+ expect(view.clearSelection).not.toHaveBeenCalled();+ view.setLoadedLinks([{ id: 'remaining-inbox' }]);+ expect(view.selectedIds()).toBeUndefined();+ expect(view.clearSelection).toHaveBeenCalledOnce();+ view.setLoadedLinks([{ id: 'remaining-inbox' }]);+ expect(view.clearSelection).toHaveBeenCalledOnce();+ } finally {+ view.dispose();+ }+ });++ it('also reconciles subsequent selections without opening a picker', () => {+ const view = mount();+ try {+ view.setLoadedLinks([{ id: 'saved-inbox' }]);+ view.setSelectedIds(undefined);+ expect(view.clearSelection).not.toHaveBeenCalled();+ view.setSelectedIds(['removed-inbox']);+ expect(view.selectedIds()).toBeUndefined();+ expect(view.clearSelection).toHaveBeenCalledOnce();+ } finally {+ view.dispose();+ }+ });+});diff --git a/apps/web/src/features/email-view/primitives/inbox-selection-reconciliation.ts b/apps/web/src/features/email-view/primitives/inbox-selection-reconciliation.tsnew file mode 100644index 0000000000..50e137c387--- /dev/null+++ b/apps/web/src/features/email-view/primitives/inbox-selection-reconciliation.ts@@ -0,0 +1,18 @@+import { type Accessor, createEffect, untrack } from 'solid-js';++/** Reconcile saved scope only against successfully loaded accounts, independently of UI. */+export function createInboxSelectionReconciliation(options: {+ selectedIds: Accessor<readonly string[] | undefined>;+ loadedLinks: Accessor<readonly { id: string }[] | undefined>;+ clearSelection: () => void;+}) {+ createEffect(() => {+ const links = options.loadedLinks();+ if (links === undefined) return;+ if (+ options.selectedIds()?.some((id) => !links.some((link) => link.id === id))+ ) {+ untrack(options.clearSelection);+ }+ });+}diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 8bf5b583a2..c93514101b 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -316,6 +316,12 @@ while selected tag sets are pending. Background refreshes retain the current lisrapidly alternate Signal, Noise, and Sent, then change inboxes; a delayed cache ornetwork read must not leave the old rows visible or expose their Load more action.+If a saved inbox selection references an unlinked account, successfully loading+linked accounts resets the filter to All inboxes while preserving an open or+restored thread. Check this with a stale saved scope and a thread route, including+when no linked accounts remain. Explicitly choosing another inbox or All inboxes+still closes the thread.+The new views reuse the legacy filter option rows and searchable submenus.Their triggers are icon-only buttons matching the surrounding view controls;Clear/Reset filters and the mobile Clear all action use destructive text styling.@@ -567,9 +573,33 @@ glass bottom sheet for status, done, attachment, calendar and tag filters, plussection when the user can pick one: `All inboxes` or a single address, never several.`Clear all` resets those filters and the inbox selection. Desktop keeps its sidebar,search field, filter menu and preview control. The sidebar lists the inboxes above the-tabs as plain rows; clicking one shows only that inbox, and the `+` beside-`All inboxes` (`Connect another account`) starts the add-inbox flow. Sidebar rows,-`New`, and the panel's back, forward and close controls act on primary-button+`New email` button and tabs as plain rows; clicking one shows only that inbox.+`Connect another account` starts the add-inbox flow from its own row below the+scrolling list. `New email` prefills From with the selected inbox, or the primary+inbox when All inboxes is selected; reopening a draft keeps its saved sender.+If an explicitly selected sending inbox is unavailable, Send reports+`Unable to find linked email account` without delivering through another+account. With no explicit selection, an unavailable primary still falls back to+the first linked inbox.+Sidebar rows, including `All inboxes`, replace their icon with an accent-colored checkmark when+selected. With exactly one connected inbox, only its address appears as the selected+row, followed by `Connect another account`; there is no `All inboxes` row, title+inbox dropdown, or inbox section in the mobile filter drawer. The inbox section shows up to four rows (including `All inboxes`), then+scrolls independently without overscroll so the email tabs stay in place. With many+accounts, scroll to the last inbox and check that selecting it updates the header filter.+Selecting one inbox also shows `from [email address]` beside the list title.+The address is a borderless ghost dropdown with the title's font weight and a+consistent 14px font size at all widths; `from` is 12px. Both align to the title's baseline, without+a tooltip or a separate clear button.+Its single-select menu includes `All inboxes`, which clears the account selection+and removes the filter. Saved selections from the old multi-select picker restore+the first saved inbox; an empty saved selection restores All inboxes. Once linked+accounts load successfully, a selected inbox that no longer exists resets to All+inboxes. This runs for the whole email view, including on touch devices before+the filter drawer opens. New email uses the originating email-view split even if another split+is active. Verify that+sidebar and menu selection stay in sync and that clearing preserves the current tab and other filters.+Sidebar rows, `New`, and the panel's back, forward and close controls act on primary-buttonmousedown, so the selection changes before the click completes; a normal clickstill works. The sidebar ends with a collapsible `Tags` section (every personal andteam tag, plus a `New tag` button): clicking a tag opens the `All` tab filtered to