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): keep cached mail usable after offline launches (#8478)
Peter Chinman109b6d100f11
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 0b30228df0..2cf5e72870 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -112,6 +112,7 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.- Reconcile mobile full-text rows by entity ID so appending a page preserves DOM rows and scroll position; restore after responsive row measurement and disable browser scroll anchoring so layout changes cannot override the saved history offset.- Reserve the safe area plus the category row above mobile Search, and only the safe area above Channels; their hidden split headers must not add another blank strip.- Follow [mobile layout and chrome](../../.agents/rules/web/mobile.md#layout-and-chrome) for full-frame views and record tabs; verify their first controls below the navigation with a nonzero safe area on phones and tablets.+- Keep split chrome portal targets reactive so cached views can mount before their header, and clear a retiring header's targets only while it still owns them.- Show only the Recent conversation feed in mobile Channels, without view tabs or a persisted mobile tab selection.- Mount the mobile search input before focusing it inside the dock tap; keep navigation in that handler so focus does not trigger a second navigation or lose iOS keyboard activation.- Preserve focused chrome editors during deferred split insertion/removal autofocus; explicit return-focus commands may still focus the pane.diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsxindex d2d10b05a2..ec02a6aaa7 100644--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx@@ -27,6 +27,7 @@ import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';import { Button, cn } from '@ui';import {createMemo,+ onCleanup,type ParentProps,type Setter,Show,@@ -497,6 +498,11 @@ export function SplitHeader(props: {contentClass="h-full flex items-center gap-0.5 pl-2 touch:pl-0 touch:gap-2 touch:max-w-full"contentRef={(element) => {panel.layoutRefs.headerLeft = element;+ onCleanup(() => {+ if (panel.layoutRefs.headerLeft === element) {+ panel.layoutRefs.headerLeft = undefined;+ }+ });}}/>@@ -505,6 +511,11 @@ export function SplitHeader(props: {class="contents"ref={(ref) => {panel.layoutRefs.headerRight = ref;+ onCleanup(() => {+ if (panel.layoutRefs.headerRight === ref) {+ panel.layoutRefs.headerRight = undefined;+ }+ });}}/><SoupNavigationButtons />diff --git a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx b/apps/web/src/components/app/split-layout/components/SplitPanel.tsxindex ed9714ffde..9a63c2ee7e 100644--- a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx@@ -18,6 +18,7 @@ import CloseIcon from '@phosphor/x.svg';import { createElementSize } from '@solid-primitives/resize-observer';import { Button, cn, Panel } from '@ui';import { createEffect, createSignal, Show, Suspense } from 'solid-js';+import { createMutable } from 'solid-js/store';import { Dynamic } from 'solid-js/web';import { splitBackInterceptor } from '../back-interceptor';import {@@ -62,7 +63,7 @@ export function SplitPanel(props: SplitPanelProps) {const panelSize = createElementSize(panelRef);let pointerTarget: Element | undefined;- const layoutRefs: SplitPanelContextType['layoutRefs'] = {};+ const layoutRefs = createMutable<SplitPanelContextType['layoutRefs']>({});const headerCollapseController = createPriorityCollapseController();const toolbarCollapseController = createPriorityCollapseController();const ownedSlots = createOwnedSlots();diff --git a/apps/web/src/components/app/split-layout/tests/SplitPanel-header-targets.test.tsx b/apps/web/src/components/app/split-layout/tests/SplitPanel-header-targets.test.tsxnew file mode 100644index 0000000000..cc0f0e5f54--- /dev/null+++ b/apps/web/src/components/app/split-layout/tests/SplitPanel-header-targets.test.tsx@@ -0,0 +1,240 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ within,+} from '@solidjs/testing-library';+import { createSignal, type ParentProps, useContext } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { SplitHeaderLeft, SplitHeaderRight } from '../components/SplitHeader';+import { SplitPanel } from '../components/SplitPanel';+import { SplitPanelContext, type SplitPanelContextType } from '../context';+import type { SplitHandle, SplitId, SplitState } from '../layoutManager';++// Keep the production panel, header, portal contributions, and target refs.+// Collection data, routing, and unrelated chrome are outside this lifecycle test.+vi.mock('@app/features/access-requests/context/visit', () => ({+ AccessRequestVisitProvider: (props: ParentProps) => props.children,+}));+vi.mock('@app/features/next-soup/create-soup-state', () => ({+ createSoupState: () => ({}),+}));+vi.mock('@app/features/next-soup/soup-context', () => ({+ SoupContextProvider: (props: ParentProps) => props.children,+ useSoup: () => ({ rows: () => [], focus: { index: () => 0 } }),+}));+vi.mock('@app/features/next-soup/soup-view/soup-view-context', () => ({+ SoupViewContextProvider: (props: ParentProps) => props.children,+}));+vi.mock('@app/features/next-soup/utils', () => ({+ openEntityInSplitFromUnifiedList: vi.fn(),+}));+vi.mock('@app/lib/split-router', () => ({+ SplitRouter: {+ Outlet: (props: { fallback: ParentProps['children'] }) => props.fallback,+ },+}));+vi.mock('@app/signal/splitLayout', () => ({+ globalSplitManager: () => undefined,+}));+vi.mock('@components/app/GlobalAppState', () => ({+ useGlobalNotificationSource: () => undefined,+}));+vi.mock('@components/app/mobile/MobileEdgeFade', () => ({+ MobileTopEdgeFade: () => null,+}));+vi.mock('@components/app/mobile/MobilePageActionRow', () => ({+ MobilePageActionRow: () => null,+}));+vi.mock('@components/app/split-panel', () => ({+ SplitPanelControllerProvider: (props: ParentProps) => props.children,+}));+vi.mock('@core/hotkey/hotkeys', () => ({+ useHotkeyDOMScope: () => [() => {}, 'test-split'],+}));+vi.mock('@core/constant/allBlocks', () => ({+ fileTypeToBlockName: () => 'md',+}));+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => true }));+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => true }));+vi.mock('@core/mobile/isNativeMobilePlatform', () => ({+ isNativeMobilePlatform: () => true,+}));+vi.mock('@core/mobile/safeAreaInsets', () => ({ getSafeAreaInset: () => 0 }));+vi.mock('@thisbeyond/solid-dnd', () => ({+ createDroppable: () => () => {},+ useDragDropContext: () => undefined,+}));+vi.mock('@entity', () => ({ isEntityDragEvent: () => false }));+vi.mock('@app/components/view-shell', () => ({ ViewBreadcrumbs: {} }));+vi.mock('@ui', () => {+ const Container = (props: ParentProps) => <div>{props.children}</div>;+ return {+ Panel: Object.assign(Container, {+ Header: Container,+ Toolbar: Container,+ Body: Container,+ }),+ Button: Container,+ Layer: Container,+ cn: () => '',+ };+});+vi.mock('../layout', () => ({+ useSplitLayout: () => ({ getSplitCount: () => 1, insertSplit: vi.fn() }),+}));+vi.mock('../registerSplitHotkeys', () => ({ registerSplitHotkeys: () => {} }));+vi.mock('../utils/createSplitAutofocus', () => ({+ createSplitAutofocus: () => {},+}));+vi.mock('../components/SplitHeaderContextMenu', () => ({+ SplitHeaderContextMenu: (props: ParentProps) => props.children,+}));++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++it('mounts header contributions when chrome appears and follows its replacement without remounting the view', () => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ const [composable, setComposable] = createSignal(true);+ const id = 'header-target-test' as SplitId;+ const content = { type: 'component', id: 'mail' } as const;+ let mountedViews = 0;+ let panel: SplitPanelContextType | undefined;+ const split: SplitState = {+ id,+ content,+ referredFrom: null,+ lastNavigationCause: 'fresh',+ mount: {+ kind: 'component',+ name: 'mail',+ meta: {+ get splitPanelLayout() {+ return composable() ? 'composable' : undefined;+ },+ },+ updateMeta: () => {},+ element: () => {+ mountedViews += 1;+ panel = useContext(SplitPanelContext);+ return (+ <>+ <button+ type="button"+ onClick={() => setComposable((value) => !value)}+ >+ Toggle header+ </button>+ <input aria-label="Retained view" />+ <SplitHeaderLeft>+ <button type="button">Unread</button>+ </SplitHeaderLeft>+ <SplitHeaderRight>+ <button type="button">Compose</button>+ </SplitHeaderRight>+ </>+ );+ },+ },+ };+ const handle: SplitHandle = {+ id,+ content: () => content,+ unregisterContentChangeListener: () => {},+ registerContentChangeListener: () => {},+ replace: () => {},+ adoptContentId: () => {},+ removeFromHistory: () => {},+ toggleSpotlight: () => {},+ setDisplayName: () => {},+ canGoForward: () => false,+ isSpotLight: () => false,+ isPopover: () => false,+ displayName: () => 'Mail',+ canGoBack: () => false,+ isActive: () => true,+ isFirst: () => true,+ goForward: () => {},+ isLast: () => true,+ activate: () => {},+ goBack: () => {},+ goBackTo: () => false,+ close: () => {},+ reset: () => {},+ previousContent: () => null,+ history: () => [content],+ meta: () =>+ split.mount.kind === 'component' ? split.mount.meta : undefined,+ updateMeta: () => {},+ referredFrom: () => null,+ lastNavigationCause: () => 'fresh',+ registerEntryStateCaptor: () => () => {},+ captureEntryState: () => {},+ currentEntryState: () => undefined,+ updateCurrentEntry: () => {},+ };+ const { container } = render(() => (+ <SplitPanel+ setPanelRef={() => {}}+ handle={handle}+ split={split}+ active+ index={0}+ />+ ));+ const retainedView = screen.getByRole('textbox', { name: 'Retained view' });+ const toggle = screen.getByRole('button', { name: 'Toggle header' });+ expect(container.querySelector('[data-split-header]')).toBeNull();+ expect(screen.queryByRole('button', { name: 'Unread' })).toBeNull();++ fireEvent.click(toggle);+ const firstHeader = container.querySelector<HTMLElement>(+ '[data-split-header]'+ );+ expect(firstHeader).not.toBeNull();+ if (!firstHeader) throw new Error('Expected the first header to mount');+ expect(+ within(firstHeader).getByRole('button', { name: 'Unread' })+ ).toBeTruthy();+ expect(+ within(firstHeader).getByRole('button', { name: 'Compose' })+ ).toBeTruthy();++ fireEvent.click(toggle);+ expect(firstHeader.isConnected).toBe(false);+ expect(panel?.layoutRefs.headerLeft).toBeUndefined();+ expect(panel?.layoutRefs.headerRight).toBeUndefined();+ expect(screen.queryByRole('button', { name: 'Unread' })).toBeNull();++ fireEvent.click(toggle);+ const secondHeader = container.querySelector<HTMLElement>(+ '[data-split-header]'+ );+ expect(secondHeader).not.toBe(firstHeader);+ if (!secondHeader)+ throw new Error('Expected the replacement header to mount');+ expect(+ within(secondHeader).getByRole('button', { name: 'Unread' })+ ).toBeTruthy();+ expect(+ within(secondHeader).getByRole('button', { name: 'Compose' })+ ).toBeTruthy();+ expect(+ within(firstHeader).queryByRole('button', { name: 'Unread' })+ ).toBeNull();+ expect(screen.getByRole('textbox', { name: 'Retained view' })).toBe(+ retainedView+ );+ expect(mountedViews).toBe(1);+});diff --git a/apps/web/src/features/email-thread/email-thread-operations.test.tsx b/apps/web/src/features/email-thread/email-thread-operations.test.tsxindex e34d6f7adc..2b3a9cef97 100644--- a/apps/web/src/features/email-thread/email-thread-operations.test.tsx+++ b/apps/web/src/features/email-thread/email-thread-operations.test.tsx@@ -1,14 +1,29 @@import type { MailboxOperation } from '@service-email/generated/schemas';import { cleanup, render, screen } from '@solidjs/testing-library';+import { onlineManager } from '@tanstack/query-core';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { type Ok, ok } from 'neverthrow';+import { Suspense } from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';-import { MailboxOperationsNotice } from './email-thread-operations';+import {+ EmailThreadOperations,+ MailboxOperationsNotice,+} from './email-thread-operations';++const threadOperations = vi.hoisted(() => vi.fn());// The notice is independent of request/cache state; no provider calls in these tests.vi.mock('@queries/email/cache-cleanup', () => ({refreshEmailThreadCache: vi.fn(),}));-vi.mock('@service-email/client', () => ({ emailClient: {} }));-afterEach(cleanup);+vi.mock('@service-email/client', () => ({+ emailClient: { threadOperations },+}));+afterEach(() => {+ cleanup();+ onlineManager.setOnline(true);+ vi.clearAllMocks();+});const operation = (state: MailboxOperation['state'],action: MailboxOperation['action'] = {@@ -37,6 +52,48 @@ it('removes the pending notice once the provider confirms', () => {render(() => <MailboxOperationsNotice operations={[operation('applied')]} />);expect(screen.queryByText(/mailbox confirmation/)).toBeNull();});++it.each(['fetching', 'paused', 'disabled'] as const)(+ 'keeps a cached thread visible while mailbox status is %s',+ async (status) => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const request = Promise.withResolvers<Ok<MailboxOperation[], unknown>>();+ const started = Promise.withResolvers<void>();+ threadOperations.mockImplementation(() => {+ started.resolve();+ return request.promise;+ });+ onlineManager.setOnline(status !== 'paused');+ render(() => (+ <QueryClientProvider client={client}>+ <Suspense fallback={<div>Loading thread</div>}>+ <p>Cached email body</p>+ <EmailThreadOperations+ threadId="cached-thread"+ enabled={status !== 'disabled'}+ announceRead={false}+ />+ </Suspense>+ </QueryClientProvider>+ ));++ if (status === 'fetching') await started.promise;+ expect(screen.queryByText('Loading thread')).toBeNull();+ const body = screen.getByText('Cached email body');++ if (status !== 'disabled') {+ onlineManager.setOnline(true);+ await started.promise;+ request.resolve(ok([operation('pending')]));+ await client.refetchQueries();+ expect(screen.getByText(/Waiting for mailbox confirmation/)).toBeTruthy();+ expect(screen.getByText('Cached email body')).toBe(body);+ }+ client.clear();+ }+);it('does not announce the mark-as-read that opening a thread queues', () => {const read = { kind: 'read', value: true } as const;render(() => (diff --git a/apps/web/src/features/email-thread/email-thread-operations.tsx b/apps/web/src/features/email-thread/email-thread-operations.tsxindex e9638a81e1..4548290786 100644--- a/apps/web/src/features/email-thread/email-thread-operations.tsx+++ b/apps/web/src/features/email-thread/email-thread-operations.tsx@@ -1,3 +1,4 @@+import { queryReadyGate } from '@queries/gate';import type {MailboxAction,MailboxOperation,@@ -72,9 +73,11 @@ export function EmailThreadOperations(props: {() => props.threadId,() => props.enabled);+ // Provider confirmation is supplemental; a cold REST lookup must not+ // suspend the thread body already available from the GraphQL cache.return (<MailboxOperationsNotice- operations={query.data ?? []}+ operations={queryReadyGate(query) ? query.data : []}announceRead={props.announceRead}/>);diff --git a/apps/web/src/lib/core/context/emailLinks.test.tsx b/apps/web/src/lib/core/context/emailLinks.test.tsxindex ba1897c832..5d51597b38 100644--- a/apps/web/src/lib/core/context/emailLinks.test.tsx+++ b/apps/web/src/lib/core/context/emailLinks.test.tsx@@ -3,9 +3,15 @@*/import type { Link } from '@service-email/generated/schemas';-import { render, screen } from '@solidjs/testing-library';-import { createSignal } from 'solid-js';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render, screen } from '@solidjs/testing-library';+import { onlineManager } from '@tanstack/query-core';+import {+ QueryClient,+ QueryClientProvider,+ useQuery,+} from '@tanstack/solid-query';+import { createSignal, Suspense } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { EmailLinksContextProvider, useEmailLinksContext } from './emailLinks';const mocks = vi.hoisted(() => ({@@ -36,7 +42,52 @@ beforeEach(() => {mocks.useIsAuthenticated.mockReset();});+afterEach(() => {+ cleanup();+ onlineManager.setOnline(true);+});+describe('EmailLinksContext', () => {+ it.each(['fetching', 'paused'] as const)(+ 'renders cached mail while inbox identity metadata is %s',+ async (status) => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const request = Promise.withResolvers<{ links: Link[] }>();+ const started = Promise.withResolvers<void>();+ const fetchLinks = vi.fn(() => {+ started.resolve();+ return request.promise;+ });+ mocks.useIsAuthenticated.mockReturnValue(() => true);+ mocks.useEmailLinksQuery.mockImplementation(() =>+ useQuery(() => ({ queryKey: ['links'], queryFn: fetchLinks }))+ );+ onlineManager.setOnline(status !== 'paused');+ render(() => (+ <QueryClientProvider client={client}>+ <EmailLinksContextProvider>+ <Suspense fallback={<span>Hidden mail</span>}>+ <Consumer label="cached row" />+ </Suspense>+ </EmailLinksContextProvider>+ </QueryClientProvider>+ ));++ if (status === 'fetching') await started.promise;+ expect(screen.queryByText('Hidden mail')).toBeNull();+ const row = screen.getByText('cached row:0:false');+ onlineManager.setOnline(true);+ await started.promise;+ request.resolve({ links: [] });+ await client.refetchQueries();+ expect(client.getQueryState(['links'])?.status).toBe('success');+ expect(screen.getByText('cached row:0:false')).toBe(row);+ client.clear();+ }+ );+it('shares reactive identity metadata across consumers', () => {const [authenticated, setAuthenticated] = createSignal(true);const [data] = createSignal({diff --git a/apps/web/src/lib/core/context/emailLinks.ts b/apps/web/src/lib/core/context/emailLinks.tsindex f855945240..933b287c0f 100644--- a/apps/web/src/lib/core/context/emailLinks.ts+++ b/apps/web/src/lib/core/context/emailLinks.ts@@ -1,4 +1,5 @@import { useEmailLinksQuery } from '@queries/email/link';+import { queryReadyGate } from '@queries/gate';import type { Link } from '@service-email/generated/schemas';import { type Accessor, createMemo } from 'solid-js';import { macroIdToEmail, tryMacroId } from '../user/macroId';@@ -24,9 +25,11 @@ export const [EmailLinksContextProvider, useEmailLinksContext] =const isAuthenticated = useIsAuthenticated();const linksQuery = useEmailLinksQuery(() => isAuthenticated() === true);+ // Inbox attribution is optional. Its REST request must not suspend+ // cached email rows or avatars during a cold offline launch.const links = (): Link[] =>- isAuthenticated() === true- ? (linksQuery.data?.links ?? EMPTY_LINKS)+ isAuthenticated() === true && queryReadyGate(linksQuery)+ ? linksQuery.data.links: EMPTY_LINKS;const secondaryInboxEmails = createMemo(() => {diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex e93a1a40a6..49636db739 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -116,6 +116,15 @@ 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.+For native offline reads, let the GraphQL email backfill finish, block dev-service+traffic, terminate the app, and relaunch it. Open Mail and a backfilled thread:+cached rows and message bodies must remain visible while REST inbox identity and+mailbox-operation requests are pending or paused. Restore connectivity and check+that supplemental metadata appears without replacing the rows or thread body.+On the first mobile Mail visit, its filter button and Signal/Noise pills must+also appear. Navigate Home → Mail → a thread → Mail and verify those controls+survive header replacement, including with the network still blocked.+Opening an email shows loading while its local draft identity and thread dataresolve. Verify a cold open and switching directly between threads with delayedcache reads: neither should flash "Sorry, an unexpected error has occurred" or