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): list Focus newest first under pinned day headers (#9510)
teoba828ac10f8d
diff --git a/apps/web/src/features/email-view/components/EmailControls.tsx b/apps/web/src/features/email-view/components/EmailControls.tsxindex 3191f52c89..af0eae5526 100644--- a/apps/web/src/features/email-view/components/EmailControls.tsx+++ b/apps/web/src/features/email-view/components/EmailControls.tsx@@ -13,20 +13,6 @@ import { useEmailView } from '../email-view-context';import { useEmailFilters } from '../filters/use-email-filters';import { EmailInboxMenu } from './EmailInboxSelector';-const FOCUS_SORT_OPTIONS = EMAIL_FOCUS_SORT_OPTIONS.map((option) => ({- id: option.id,- label: option.label,- content:- option.description === undefined- ? undefined- : () => (- <span class="flex flex-col">- <span>{option.label}</span>- <span class="text-xs text-ink-muted">{option.description}</span>- </span>- ),-}));-export type EmailControlsProps = {/** Controlled filter-menu state, so the header's `f` hotkey can open it. */filterOpen?: boolean;@@ -70,7 +56,7 @@ export function EmailControls(props: EmailControlsProps) {size="icon-md"label="Sort Focus"value={state.focusSort}- options={FOCUS_SORT_OPTIONS}+ options={EMAIL_FOCUS_SORT_OPTIONS}onChange={setFocusSort}/></Show>diff --git a/apps/web/src/features/email-view/components/EmailEmptyState.tsx b/apps/web/src/features/email-view/components/EmailEmptyState.tsxindex 2c81cba503..0ab5182dab 100644--- a/apps/web/src/features/email-view/components/EmailEmptyState.tsx+++ b/apps/web/src/features/email-view/components/EmailEmptyState.tsx@@ -60,8 +60,8 @@ function tabCopy(tab: EmailTab): { title: string; description: string } {description: 'Email you archive will appear here.',})).with('focus', () => ({- title: 'Nothing needs you',- description: `Signal email worth your attention from the last ${FOCUS_WINDOW_DAYS} days appears here.`,+ title: "You're caught up",+ description: `Email worth your attention from the last ${FOCUS_WINDOW_DAYS} days appears here.`,})).with('spam', () => ({title: 'No spam',@@ -81,7 +81,7 @@ function tabCopy(tab: EmailTab): { title: string; description: string } {}export function EmailEmptyState() {- const { state, setFacets, setInboxIds } = useEmailView();+ const { state, setFacets, setInboxIds, setTab } = useEmailView();const emailActive = useEmailLinksStatus();const startAddInbox = useAddInboxFlow();// Scheduled has no search or filters; text typed on another tab stays behind.@@ -155,6 +155,14 @@ export function EmailEmptyState() {graphic={EmptyStateInboxTrayGraphic}title={copy().title}description={copy().description}+ primaryAction={+ state.tab === 'focus'+ ? {+ label: 'See the rest of your inbox',+ onClick: () => setTab('important'),+ }+ : undefined+ }documentationUrl={EMAIL_DOCS_URL}/>)}diff --git a/apps/web/src/features/email-view/components/EmailList.tsx b/apps/web/src/features/email-view/components/EmailList.tsxindex 13fc1d8f84..043546fdc1 100644--- a/apps/web/src/features/email-view/components/EmailList.tsx+++ b/apps/web/src/features/email-view/components/EmailList.tsx@@ -8,6 +8,7 @@ import {type ListKey,useListInteractions,} from '@app/components/list';+import { StickyVirtualizer } from '@app/components/list/StickyVirtualizer';import { CommandState } from '@app/features/command/state';import {resolveEntityActionViewContext,@@ -63,7 +64,7 @@ import {Switch,} from 'solid-js';import type { CacheSnapshot } from 'virtua';-import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';+import type { VirtualizerHandle } from 'virtua/solid';import { canMarkNotDone } from '../../next-soup/actions/can-mark-not-done';import {persistSoupNavigationTouchHighlight,@@ -125,6 +126,9 @@ const savedLayouts = new Map<>();const MAX_SAVED_LAYOUTS = 20;+const isGroupHeaderRow = (row: EmailDataSourceItem) =>+ row.kind === 'group-header';+export function EmailList(props: EmailListProps) {const {state,@@ -209,8 +213,12 @@ export function EmailList(props: EmailListProps) {activeTab: state.tab,});+ // Focus's day headers stay pinned while its chronological list scrolls.+ const pinsDateHeaders = () =>+ state.tab === 'focus' && state.focusSort === 'recent';const [viewport, setViewport] = createSignal<HTMLDivElement>();- createScrollTopFade(viewport);+ // The top-edge fade would wash out a pinned header.+ createScrollTopFade(() => (pinsDateHeaders() ? undefined : viewport()));const [topSpacer, setTopSpacer] = createSignal<HTMLDivElement>();const topSpacerSize = createElementSize(topSpacer);// The virtualizer's item offsets exclude this; its scroll offset includes it.@@ -544,7 +552,13 @@ export function EmailList(props: EmailListProps) {const top = listStartMargin() + handle.getItemOffset(focused);const bottom = top + handle.getItemSize(focused);const viewTop = handle.scrollOffset;- if (top < viewTop || bottom > viewTop + handle.viewportSize) {+ // A pinned header can cover a row within these bounds; the sticky handle+ // allows for it and leaves a row that is really in view alone.+ if (+ pinsDateHeaders() ||+ top < viewTop ||+ bottom > viewTop + handle.viewportSize+ ) {handle.scrollToIndex(focused, { align: 'nearest' });}}@@ -776,12 +790,16 @@ export function EmailList(props: EmailListProps) {{/* A row subtree that suspends (the project crumb's preview query, say)detaches only itself, not the list and its scroll position. */}<Suspense>- <Virtualizer+ <StickyVirtualizerref={registerVirtualizer}cache={initialCache}data={rows()}scrollRef={viewport()}startMargin={listStartMargin()}+ isSticky={+ pinsDateHeaders() ? isGroupHeaderRow : undefined+ }+ stickyInset={listStartMargin()}bufferSize={500}itemSize={44}keepMounted={@@ -1046,7 +1064,7 @@ export function EmailList(props: EmailListProps) {</Match></Switch>)}- </Virtualizer>+ </StickyVirtualizer></Suspense><Show when={isTouchDevice()}><divdiff --git a/apps/web/src/features/email-view/constants.ts b/apps/web/src/features/email-view/constants.tsindex 9ffc69c1a0..40d432628b 100644--- a/apps/web/src/features/email-view/constants.ts+++ b/apps/web/src/features/email-view/constants.ts@@ -72,29 +72,18 @@ export const isEmailInboxTab = (tab: EmailTab) =>(EMAIL_INBOX_TAB_IDS as readonly EmailTab[]).includes(tab);/** How the Focus tab orders its threads. */-export const EMAIL_FOCUS_SORT_IDS = [- 'priority',- 'importance',- 'recent',-] as const;+export const EMAIL_FOCUS_SORT_IDS = ['recent', 'importance'] as const;export type EmailFocusSort = (typeof EMAIL_FOCUS_SORT_IDS)[number];-export const DEFAULT_EMAIL_FOCUS_SORT: EmailFocusSort = 'priority';+export const DEFAULT_EMAIL_FOCUS_SORT: EmailFocusSort = 'recent';-export const EMAIL_FOCUS_SORT_OPTIONS: readonly {+export const EMAIL_FOCUS_SORT_OPTIONS: {id: EmailFocusSort;label: string;- /** A second line in the sort menu, for orders the label can't explain. */- description?: string;}[] = [- {- id: 'priority',- label: 'Priority',- description: 'Importance, halved every 2 days since mail last came in',- },- { id: 'importance', label: 'Importance' },{ id: 'recent', label: 'Most recent' },+ { id: 'importance', label: 'Importance' },];/** Provider folders have separate membership and currently use network pages. */diff --git a/apps/web/src/features/email-view/persistence.test.ts b/apps/web/src/features/email-view/persistence.test.tsindex b701ff2ec2..da78f4d20d 100644--- a/apps/web/src/features/email-view/persistence.test.ts+++ b/apps/web/src/features/email-view/persistence.test.ts@@ -1,5 +1,6 @@import { INBOX_FILTER_ENTRY_KEY } from '@app/features/next-soup/soup-view/inbox-filter-controllers';import type { EntryPersistenceHandle } from '@components/app/split-layout/entry-persistence';+import { createUserScopedStorage } from '@core/util/userScopedStorage';import { describe, expect, it, vi } from 'vitest';import { createEmailViewPersistence } from './persistence';import type { EmailViewState } from './types';@@ -92,16 +93,42 @@ describe('createEmailViewPersistence', () => {const list = Array.isArray(storages) ? storages : [storages];for (const storage of list) {storage.initialize?.(current(), current);- storage.write({ ...current(), tab: 'focus', focusSort: 'recent' });+ storage.write({ ...current(), tab: 'focus', focusSort: 'importance' });}- let state = current();+ let state: EmailViewState = { ...current(), focusSort: 'recent' };for (const storage of list) {const next = storage.restore(state);if (next !== undefined) state = next;}expect(state.tab).toBe('focus');+ expect(state.focusSort).toBe('importance');+ });++ it('lands a saved retired Priority sort on most recent, keeping the rest', () => {+ createUserScopedStorage('macro:email:view-state:v1').write(+ 'priority-sort-user',+ JSON.stringify({ version: 1, tab: 'focus', focusSort: 'priority' })+ );+ const { storages } = createEmailViewPersistence({+ handle: {+ currentEntryState: () => ({}),+ registerEntryStateCaptor: () => () => {},+ },+ userId: () => 'priority-sort-user',+ restoreEntryState: false,+ restorePreferences: false,+ });+ const list = Array.isArray(storages) ? storages : [storages];++ let state = current();+ for (const storage of list) {+ const next = storage.restore(state);+ if (next !== undefined) state = next;+ }+expect(state.focusSort).toBe('recent');+ expect(state.tab).toBe('focus');});});diff --git a/apps/web/src/features/email-view/persistence.ts b/apps/web/src/features/email-view/persistence.tsindex a8308edffb..5529dc7643 100644--- a/apps/web/src/features/email-view/persistence.ts+++ b/apps/web/src/features/email-view/persistence.ts@@ -35,6 +35,8 @@ const aliasFilterSchema = z.optional().catch(undefined);+// An order no longer offered, such as the retired `priority`, restores as the+// default. Touch layouts have no sort menu, so this is their only way off it.const emailFocusSortSchema = z.enum(EMAIL_FOCUS_SORT_IDS).catch(DEFAULT_EMAIL_FOCUS_SORT);diff --git a/apps/web/src/features/email-view/primitives/scroll-anchor.test.ts b/apps/web/src/features/email-view/primitives/scroll-anchor.test.tsindex a41b79cde0..9ad2a2bfd9 100644--- a/apps/web/src/features/email-view/primitives/scroll-anchor.test.ts+++ b/apps/web/src/features/email-view/primitives/scroll-anchor.test.ts@@ -28,16 +28,19 @@ function list(ids: string[]) {},});scroller.getBoundingClientRect = () => ({ top: 0 }) as DOMRect;+ let pinnedHeader: HTMLElement | undefined;const layout = (next: string[]) => {scroller.replaceChildren(...next.map((id, index) => {const row = document.createElement('div');row.id = id;row.setAttribute('role', 'row');+ row.toggleAttribute('data-soup-entity', true);row.getBoundingClientRect = () =>({ top: index * 44 - scrollTop }) as DOMRect;return row;- })+ }),+ ...(pinnedHeader ? [pinnedHeader] : []));};layout(ids);@@ -48,6 +51,14 @@ function list(ids: string[]) {scrollTo: (value: number) => {scrollTop = value;},+ /** A header row stuck to the top of the viewport, whatever scrolls under it. */+ pinHeader: () => {+ pinnedHeader = document.createElement('div');+ pinnedHeader.id = 'pinned-header';+ pinnedHeader.setAttribute('role', 'row');+ pinnedHeader.getBoundingClientRect = () => ({ top: 0 }) as DOMRect;+ scroller.append(pinnedHeader);+ },};}@@ -101,6 +112,19 @@ it('keeps the anchor through the removal of the row it was on', () => {expect(dom.scroller.scrollTop).toBe(440);});+it('anchors on threads, not a date header pinned at the top', () => {+ const ids = Array.from({ length: 20 }, (_, index) => `row-${index}`);+ const { dom, anchor, update } = setup(ids);+ // row-10 has scrolled partly off, so the header is the topmost row on screen.+ dom.scrollTo(450);+ dom.pinHeader();+ anchor.capture();++ update(['new-mail', ...ids]);++ expect(dom.scroller.scrollTop).toBe(450 + 44);+});+it('leaves the list at the top so new mail shows there', () => {const ids = Array.from({ length: 20 }, (_, index) => `row-${index}`);const { dom, anchor, update } = setup(ids);diff --git a/apps/web/src/features/email-view/primitives/scroll-anchor.ts b/apps/web/src/features/email-view/primitives/scroll-anchor.tsindex 84ef76f911..01567f173a 100644--- a/apps/web/src/features/email-view/primitives/scroll-anchor.ts+++ b/apps/web/src/features/email-view/primitives/scroll-anchor.ts@@ -11,8 +11,9 @@ const ANCHOR_CANDIDATES = 3;*/const TOUCH_SCROLL_SETTLE_MS = 150;+// Threads only: a pinned date header stays put whatever moves under it.const rowElements = (scroller: HTMLElement) => [- ...scroller.querySelectorAll<HTMLElement>('[role="row"][id]'),+ ...scroller.querySelectorAll<HTMLElement>('[data-soup-entity][id]'),];/**diff --git a/apps/web/src/features/email-view/queries/email-results.ts b/apps/web/src/features/email-view/queries/email-results.tsindex 1d51edb3a1..8598c450ab 100644--- a/apps/web/src/features/email-view/queries/email-results.ts+++ b/apps/web/src/features/email-view/queries/email-results.ts@@ -1,11 +1,13 @@import {buildGroupedSoupRows,+ type DateBucket,dateBucket,groupSoupEntities,type SoupGroup,} from '@app/features/soup/collection';import type { DateValue } from '@core/util/date';import type { EntityData, WithNotification } from '@entity';+import { differenceInCalendarDays, format, isSameYear } from 'date-fns';/** A row held in place keeps the timestamp it was bucketed by. */type HeldSortTimestamp = (entityId: string) => DateValue | undefined;@@ -45,3 +47,42 @@ export function buildEmailDateRows(rows.shift();return rows;}++/**+ * Focus's day headers: Today, Yesterday, the weekday for the rest of the last+ * week, then the date. A pinned Focus header names the one day under it, where+ * the shared `dateBucket` sections that Signal uses span weeks. English, like+ * the rows' own dates: this list is not translated yet.+ */+export function focusDateBucket(+ value: DateValue | null | undefined,+ now = new Date()+): DateBucket {+ const date = new Date(value ?? Number.NaN);+ if (Number.isNaN(date.getTime())) return { key: 'older', label: 'Older' };++ const daysAgo = differenceInCalendarDays(now, date);+ // A future time (clock skew) reads as today, at the top of the list.+ if (daysAgo <= 0) return { key: 'today', label: 'Today' };+ if (daysAgo === 1) return { key: 'yesterday', label: 'Yesterday' };++ const key = format(date, 'yyyy-MM-dd');+ if (daysAgo < 7) return { key, label: format(date, 'EEEE') };++ const dateFormat = isSameYear(date, now) ? 'MMM d' : 'MMM d, yyyy';+ return { key, label: format(date, dateFormat) };+}++/** Focus's rows under its day headers, Today's included. */+export function buildFocusDateRows(+ entities: WithNotification<EntityData>[],+ now = new Date()+) {+ const groups = groupSoupEntities(entities, {+ getGroupId: (entity) =>+ focusDateBucket(emailSortTimestamp(entity), now).key,+ getGroupLabel: (_groupId, firstEntity) =>+ focusDateBucket(emailSortTimestamp(firstEntity), now).label,+ });+ return buildGroupedSoupRows(groups, { keyByEntity: true });+}diff --git a/apps/web/src/features/email-view/queries/use-focus-email-source.test.ts b/apps/web/src/features/email-view/queries/use-focus-email-source.test.tsindex af7a5a93d3..86b2e1ce41 100644--- a/apps/web/src/features/email-view/queries/use-focus-email-source.test.ts+++ b/apps/web/src/features/email-view/queries/use-focus-email-source.test.ts@@ -2,7 +2,7 @@ import { createTagFacetContext } from '@app/features/soup';import type { EmailEntity, EmailFocus } from '@entity';import { describe, expect, it, vi } from 'vitest';import type { EmailDataSourceInput } from './use-email-query';-import { selectFocusEmails } from './use-focus-email-source';+import { buildFocusRows, selectFocusEmails } from './use-focus-email-source';// Exercise the pure selection without UI barrels or live connections.vi.mock('@queries/email/focus', () => ({ useEmailFocusQuery: vi.fn() }));@@ -17,6 +17,11 @@ vi.mock('@app/features/soup', async () => ({...(await import('@app/features/soup/filters')),...(await import('@app/features/soup/collection/rows')),}));+vi.mock('@app/features/soup/collection', async () => ({+ ...(await import('@app/features/soup/collection/date-buckets')),+ ...(await import('@app/features/soup/collection/rows')),+ ...(await import('@app/features/soup/collection/transforms')),+}));vi.mock('@app/features/soup/entity-notifications', () => ({withEntityNotifications: vi.fn(),}));@@ -62,16 +67,8 @@ function email(};}-// Server order: by priority, so the fresh invoice leads the older report.+// Listed out of date order, so a test can tell a sort from the server's order.const EMAILS = [- email(- 'invoice',- { importance: 70, needsReply: true },- {- sortTs: '2026-10-08T10:00:00Z',- senderName: 'Casey',- }- ),email('report',{ importance: 93 },@@ -80,6 +77,14 @@ const EMAILS = [linkId: 'inbox-b',}),+ email(+ 'invoice',+ { importance: 70, needsReply: true },+ {+ sortTs: '2026-10-08T10:00:00Z',+ senderName: 'Casey',+ }+ ),email('plan',{ importance: 61, needsFollowUp: true },@@ -103,7 +108,7 @@ function select(search: '',inboxIds: undefined,facets: {},- focusSort: 'priority',+ focusSort: 'recent',...input,},context@@ -111,10 +116,6 @@ function select(}describe('selectFocusEmails', () => {- it('keeps the server order by priority', () => {- expect(select({})).toEqual(['invoice', 'report', 'plan']);- });-it('orders by importance on request', () => {expect(select({ focusSort: 'importance' })).toEqual(['report',@@ -124,10 +125,10 @@ describe('selectFocusEmails', () => {});it('breaks importance ties by recency', () => {- const [invoice, report, plan] = EMAILS;+ const [report, invoice, plan] = EMAILS;const tied = [- invoice,report,+ invoice,{ ...plan, focus: { ...plan.focus!, importance: 93 } },];expect(select({ focusSort: 'importance' }, tied)).toEqual([@@ -137,7 +138,7 @@ describe('selectFocusEmails', () => {]);});- it('orders by recency on request', () => {+ it('orders newest first, whatever order the server sent', () => {expect(select({ focusSort: 'recent' })).toEqual(['invoice','plan',@@ -169,27 +170,94 @@ describe('selectFocusEmails', () => {select({ focusSort: 'importance' });select({ focusSort: 'recent' });expect(EMAILS.map((selected) => selected.id)).toEqual([- 'invoice','report',+ 'invoice','plan',]);});it('ignores Status and Done filters, which Focus does not offer', () => {- const [invoice, ...rest] = EMAILS;+ const [report, ...rest] = EMAILS;expect(select({ facets: { read: ['read'], done: ['done'] } }, [- { ...invoice, isRead: true },+ { ...report, isRead: true },...rest,])- ).toEqual(['invoice', 'report', 'plan']);+ ).toEqual(['invoice', 'plan', 'report']);});it('drops threads marked done', () => {- const [invoice, ...rest] = EMAILS;- expect(select({}, [{ ...invoice, done: true }, ...rest])).toEqual([- 'report',+ const [report, ...rest] = EMAILS;+ expect(select({}, [{ ...report, done: true }, ...rest])).toEqual([+ 'invoice','plan',]);});});++describe('buildFocusRows', () => {+ // Thursday, October 15 2026, local time.+ const NOW = new Date(2026, 9, 15, 12);+ const SENT_AT: [string, Date][] = [+ ['this-morning', new Date(2026, 9, 15, 8)],+ ['just-after-midnight', new Date(2026, 9, 15, 0, 5)],+ ['last-night', new Date(2026, 9, 14, 23, 55)],+ ['tuesday', new Date(2026, 9, 13, 9)],+ ['friday', new Date(2026, 9, 9, 9)],+ ['a-week-ago', new Date(2026, 9, 8, 9)],+ ['last-year', new Date(2025, 11, 30, 9)],+ ];+ const EMAILS_BY_DATE = SENT_AT.map(([id, sortTs]) =>+ email(id, {}, { sortTs: sortTs.toISOString() })+ );+ const shape = (rows: ReturnType<typeof buildFocusRows>) =>+ rows.map((row) => {+ if (row.kind === 'group-header') return `# ${row.label}`;+ return row.kind === 'entity' ? row.entity.id : row.kind;+ });++ it('heads a most recent list with Today, Yesterday, weekdays, then dates', () => {+ expect(shape(buildFocusRows(EMAILS_BY_DATE, 'recent', NOW))).toEqual([+ '# Today',+ 'this-morning',+ 'just-after-midnight',+ '# Yesterday',+ 'last-night',+ '# Tuesday',+ 'tuesday',+ '# Friday',+ 'friday',+ '# Oct 8',+ 'a-week-ago',+ '# Dec 30, 2025',+ 'last-year',+ ]);+ });++ it('heads a thread dated in the future with Today, not a second day', () => {+ const skewed = email(+ 'skewed',+ {},+ { sortTs: new Date(2026, 9, 16, 9).toISOString() }+ );+ expect(+ shape(+ buildFocusRows([skewed, ...EMAILS_BY_DATE.slice(0, 1)], 'recent', NOW)+ )+ ).toEqual(['# Today', 'skewed', 'this-morning']);+ });++ it('keeps importance flat, with no day headers', () => {+ expect(shape(buildFocusRows(EMAILS_BY_DATE, 'importance', NOW))).toEqual(+ SENT_AT.map(([id]) => id)+ );+ });++ it('gives a thread the same row id in both orders, so list focus survives a sort change', () => {+ const entityRowIds = (sort: 'recent' | 'importance') =>+ buildFocusRows(EMAILS_BY_DATE, sort, NOW)+ .filter((row) => row.kind === 'entity')+ .map((row) => row.id);+ expect(entityRowIds('recent')).toEqual(entityRowIds('importance'));+ });+});diff --git a/apps/web/src/features/email-view/queries/use-focus-email-source.ts b/apps/web/src/features/email-view/queries/use-focus-email-source.tsindex 7cff8516ed..f66631c6d5 100644--- a/apps/web/src/features/email-view/queries/use-focus-email-source.ts+++ b/apps/web/src/features/email-view/queries/use-focus-email-source.ts@@ -8,14 +8,21 @@ import {import { withEntityNotifications } from '@app/features/soup/entity-notifications';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import type { DateValue } from '@core/util/date';-import { type EmailEntity, isEmailEntity } from '@entity';+import {+ type EmailEntity,+ type EntityData,+ isEmailEntity,+ type WithNotification,+} from '@entity';import { useEmailFocusQuery } from '@queries/email/focus';import { createGraphqlSoupDoneProjection } from '@queries/soup/graphql/done-projection';import { usePendingGraphqlSoupDone } from '@queries/soup/graphql/optimistic-done';import { createMemo } from 'solid-js';import { match } from 'ts-pattern';+import type { EmailFocusSort } from '../constants';import { EMAIL_FACETS, type EmailFacetContext } from '../filters/email-facets';import { useEmailTabAvailability } from '../tab-availability';+import { buildFocusDateRows } from './email-results';import type {EmailDataSource,EmailDataSourceInput,@@ -26,7 +33,7 @@ import type {const timestamp = (value: DateValue | null | undefined) =>value instanceof Date ? value.getTime() : Date.parse(value ?? '') || 0;-// The same recency the other tabs order and group by.+// The latest message in either direction, as `mapEmailFocus` dates each row.const recency = (email: EmailEntity) =>timestamp(email.sortTs ?? email.updatedAt ?? email.createdAt);@@ -44,10 +51,11 @@ function matchesSearch(email: EmailEntity, text: string): boolean {}/**- * Applies the view's inbox scope, filters and search to the Focus list. The- * server returns it by priority; "Importance" and "Most recent" reorder it here.- * Done threads leave at once, as on Signal: the server drops archived- * threads only on the next read. Focus has no Status or Done filters.+ * Applies the view's inbox scope, filters and search to the Focus list, then+ * orders it. The server already sends it newest first, but sorting here keeps+ * rows under their day headers, which go by each row's own date. Done threads+ * leave at once, as on Signal: the server drops archived threads only on the+ * next read. Focus has no Status or Done filters.*/export function selectFocusEmails(emails: readonly EmailEntity[],@@ -72,18 +80,28 @@ export function selectFocusEmails();return (match(input.focusSort)- .with('priority', () => selected).with('importance', () => selected.sort(byImportance)).with('recent', () => selected.sort(byRecency))- // An order this build doesn't know keeps the server's priority order.- .exhaustive(() => selected)+ // An order this build doesn't know reads as the default, most recent.+ .exhaustive(() => selected.sort(byRecency)));}+/** Day headers only mean something on a chronological list. */+export function buildFocusRows(+ emails: WithNotification<EntityData>[],+ focusSort: EmailFocusSort,+ now = new Date()+): EmailDataSourceItem[] {+ return focusSort === 'recent'+ ? buildFocusDateRows(emails, now)+ : buildFlatSoupRows(emails);+}+/**- * The Focus tab: signal threads the email focus worker found worth the- * owner's attention. The whole list arrives in one read, so filtering and- * ordering happen here rather than on the server.+ * The Focus tab: inbox threads the email focus worker found worth the owner's+ * attention. The whole list arrives in one read, so filtering and the chosen+ * order are applied here.*/export function useFocusEmailSource(state: EmailDataSourceInput,@@ -120,10 +138,11 @@ export function useFocusEmailSource(const built = createMemo((): EmailDataSourceItem[] => {if (!ready()) return [];- return buildFlatSoupRows(+ return buildFocusRows(selectFocusEmails(emails(), state, facetContext()).map((email) =>withEntityNotifications(email, notificationSource)- )+ ),+ state.focusSort);});const items = createSoupRowStore(built);diff --git a/apps/web/src/lib/queries/email/focus-mapping.test.ts b/apps/web/src/lib/queries/email/focus-mapping.test.tsnew file mode 100644index 0000000000..12343d35c5--- /dev/null+++ b/apps/web/src/lib/queries/email/focus-mapping.test.ts@@ -0,0 +1,102 @@+import type { EmailFocusQuery } from '@service-storage/graphql/generated/graphql';+import { describe, expect, it, vi } from 'vitest';+import { mapEmailFocus } from './focus';++// Exercise the pure mapping without UI barrels or live connections. Separate+// from focus.test.ts, which mocks this mapping away to test the query binding.+vi.mock('@graphql-cache/solid/create-live-query', () => ({+ createLiveQuery: vi.fn(),+}));+vi.mock('@entity', async () => ({+ ...(await import('@entity/types/entity')),+}));+vi.mock('@core/constant/allBlocks', () => ({+ blockNameToDefaultFile: {},+ itemToSafeName: vi.fn(),+}));+vi.mock('@core/context/channels', () => ({ useChannelsContext: vi.fn() }));+vi.mock('@core/user', () => ({ emailToId: vi.fn() }));+vi.mock('@service-storage/websocket', () => ({+ storageWS: { reconnectIfDisconnected: vi.fn() },+ createWebSocketJob: vi.fn(),+}));+vi.mock('@service-connection/websocket', () => ({+ ws: { addEventListener: vi.fn(), send: vi.fn() },+ state: () => 'closed',+ createConnectionBlockWebsocketEffect: vi.fn(),+ createConnectionWebsocketEffect: vi.fn(),+}));++type FocusThread = EmailFocusQuery['user']['emailFocus'][number];++const thread = (timestamps: Partial<FocusThread>) =>+ ({+ __typename: 'GraphqlSoupEmailThread',+ id: 'thread',+ entityType: 'EMAIL_THREAD',+ frecencyScore: 0,+ isFavorited: false,+ providerId: null,+ ownerId: 'owner',+ inboxVisible: true,+ hasReceivedMail: true,+ emailName: 'Subject',+ snippet: 'The latest message',+ senderEmail: '[email protected]',+ senderName: 'Sender',+ senderPhotoUrl: null,+ isRead: false,+ isDraft: false,+ isImportant: false,+ isSignal: true,+ projectId: null,+ sortTs: '2026-10-05T10:00:00+00:00',+ createdAt: '2026-10-01T00:00:00+00:00',+ updatedAt: '2026-10-09T00:00:00+00:00',+ viewedAt: null,+ latestInboundMessageTs: null,+ latestOutboundMessageTs: null,+ latestNonSpamMessageTs: null,+ reminderReturnedAt: null,+ participants: [],+ attachments: [],+ labels: [],+ properties: [],+ notifications: [],+ focus: { importance: 70, needsReply: false, needsFollowUp: true },+ ...timestamps,+ }) as unknown as FocusThread;++const mapped = (timestamps: Partial<FocusThread>) =>+ mapEmailFocus({+ user: { id: 'owner', emailFocus: [thread(timestamps)] },+ } as EmailFocusQuery)[0];++describe('mapEmailFocus', () => {+ it('dates a thread the owner replied to last by that reply', () => {+ const row = mapped({+ latestInboundMessageTs: '2026-10-05T10:00:00+00:00',+ latestOutboundMessageTs: '2026-10-08T10:00:00+00:00',+ latestNonSpamMessageTs: '2026-10-08T10:00:00+00:00',+ });+ expect(row?.sortTs).toBe('2026-10-08T10:00:00+00:00');+ });++ it('dates a thread someone else wrote to last by that message', () => {+ const row = mapped({+ latestInboundMessageTs: '2026-10-08T10:00:00+00:00',+ latestOutboundMessageTs: '2026-10-05T10:00:00+00:00',+ latestNonSpamMessageTs: '2026-10-08T10:00:00+00:00',+ });+ expect(row?.sortTs).toBe('2026-10-08T10:00:00+00:00');+ });++ it('does not date a thread by a reminder returning it', () => {+ const row = mapped({+ latestInboundMessageTs: '2026-10-05T10:00:00+00:00',+ latestNonSpamMessageTs: '2026-10-05T10:00:00+00:00',+ reminderReturnedAt: '2026-10-08T10:00:00+00:00',+ });+ expect(row?.sortTs).toBe('2026-10-05T10:00:00+00:00');+ });+});diff --git a/apps/web/src/lib/queries/email/focus.ts b/apps/web/src/lib/queries/email/focus.tsindex 74435240d1..ab23c2dfdf 100644--- a/apps/web/src/lib/queries/email/focus.ts+++ b/apps/web/src/lib/queries/email/focus.ts@@ -28,13 +28,15 @@ import { createVisibleRefresh } from '../visible-refresh';export const FOCUS_WINDOW_DAYS = 30;/**- * The viewer's Focus threads as email rows, highest priority first, each- * carrying its classification in `focus`.+ * The viewer's Focus threads as email rows, in the server's newest-first order,+ * each carrying its classification in `focus`.*/export function mapEmailFocus(data: EmailFocusQuery): EmailEntity[] {const threads: EmailEntity[] = [];for (const thread of data.user.emailFocus) {- const item = mapGraphqlSoupItem(thread);+ // Date rows by their latest message in either direction: the default+ // Inbox key would leave out the owner's own replies.+ const item = mapGraphqlSoupItem(thread, { emailView: 'ALL' });if (!item || !isDisplayableSoupItem(item)) continue;const entity = mapApiSoupItemToEntity(item);if (!isEmailEntity(entity) || !thread.focus) continue;diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 568c1e7679..9d82e6c4b9 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -164,7 +164,12 @@ With `enable-email-focus` and `enable-graphql-soup` on, a `Focus` tab leads thedesktop Inbox tabs and the mobile pills. It lists inboxthreads from the last 30 days that the email focus worker(`services/email_focus_worker`) classified as worth attention, including inboxes-linked to the account, newest first by latest message in either direction. Key+linked to the account, newest first by the thread's latest message in either+direction, so a thread the owner replied to last sorts and dates by that reply.+Day headers group the list and stay pinned while it scrolls: Today, Yesterday,+the weekday for the rest of the last week, then the date. These are Focus's own+(`focusDateBucket`); Signal keeps the shared date sections, drops a leading+Today, and does not pin. Keymail stays in whatever its score: mail waiting on the owner's reply, and mail fromsomeone the owner wrote to in the last 90 days, unless it reads as outreach orautomated. A calendar change (a reschedule, update, cancellation or proposed new@@ -182,9 +187,9 @@ importance score with a five-bar meter just before the date, and from 56rem also`Reply needed` and `Follow up` tag pills ahead of it. Narrower rows drop both;without a touch screen the score moves before the subject, and touch screensshow neither. The desktop header's sort dropdown (`Sort Focus`, among the view-options) switches between **Priority**,-**Importance** and **Most recent**; touch layouts have no dropdown and keep the-saved order (Priority by default). The filter menu adds a Focus group (Reply+options) switches between **Most recent**, the default, and **Importance**, which+is flat with no day headers; touch layouts have no dropdown and keep the saved+order. A saved order that no longer exists restores as Most recent. The filter menu adds a Focus group (Replyneeded, Follow up) on this tab only and has no Status or Done group there. Thelist is one `user.emailFocus` GraphQL read filtered on the client. New mailreaches an open Focus tab within seconds: when the worker stores a@@ -195,7 +200,8 @@ passing stores nothing and pushes nothing, so a follow-up coming due or acalendar change whose event ends shows at the tab's next read. MarkDone hides the row at once and archives the thread; Undo brings it back. Theworker classifies only inboxes on its `FOCUS_ENABLED_EMAIL_DOMAINS` allowlist, so-other accounts see the empty state `Nothing needs you`.+other accounts see the empty state `You're caught up`, whose **See the rest of+your inbox** opens Signal.`Archived`, between All mail and Shared in the desktop Library section, listsyour own archived (Mail Done) threads: the