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(search): restore mobile results on back navigation (#8279)
Peter Chinmanb113a7e619f3
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 0c71a809a5..36e2e9ec91 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -85,9 +85,10 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.- Disable GraphQL cache sessions and clear login hints on confirmed auth 401s,even with retained user data; preserve session state on transient failures.- Mobile dock search owns transient category/mode state in `features/command/mobile`; reuse the shared entity source and explicit full-text adapter rather than overlaying the dock query on view tabs or saved facets. See `docs/agent-guide/search.md` at the repository root.+- Keep mobile search sessions, result order, loaded rows, and scroll state with their Search history entry; preserve order before opening a result so viewedAt updates cannot move it on Back. Refresh row data in place and append later pages. Scope saved rows and scroll measurements to their account and reset result adapters/scrollers on account changes. Query/category changes rerank; a fresh dock search supplies a new session ID in Search's route state, including when reusing a native pane.- Keep Quick Access cache availability reactive to the GraphQL rollout flag; it can arrive after the provider mounts, and email has no legacy source fallback.- Virtualize mobile name results like desktop Command Menu; local Quick Access sources are unbounded, and mounting them all stalls iOS keyboard focus during layout. Load additional search pages near the scroll end instead of reserving a paging bar.-- Reconcile mobile full-text rows by entity ID so appending a page preserves DOM rows and scroll position.+- 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 only the safe-area inset above mobile Search and Channels; their hidden split headers must not leave a blank strip or extend the top fade.- 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.diff --git a/apps/web/src/components/app/mobile/use-mobile-nav.ts b/apps/web/src/components/app/mobile/use-mobile-nav.tsindex daffbb1367..2393e46fb0 100644--- a/apps/web/src/components/app/mobile/use-mobile-nav.ts+++ b/apps/web/src/components/app/mobile/use-mobile-nav.ts@@ -1,5 +1,6 @@import type { ListView } from '@app/constants/list-views';import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';+import type { MobileSearchRouteState } from '@app/features/command/mobile/mobile-search-route-state';import {reviewsTabSearch,reviewsTabSearchCodec,@@ -87,7 +88,9 @@ export function useMobileNavNavigate(): (id: MobileDockNavId) => void {}const content = mobileNavContent(id);if (isNativeMobilePlatform()) {- replaceAllSplits(content);+ const routeState: MobileSearchRouteState | undefined =+ id === 'search' ? { sessionId: crypto.randomUUID() } : undefined;+ replaceAllSplits(content, { routeState });return;}const fgContent = globalSplitManager()?.activeSplit()?.content();diff --git a/apps/web/src/components/app/split-layout/layout.ts b/apps/web/src/components/app/split-layout/layout.tsindex a965be6964..cd6ffaeeab 100644--- a/apps/web/src/components/app/split-layout/layout.ts+++ b/apps/web/src/components/app/split-layout/layout.ts@@ -11,6 +11,7 @@ import type {OpenWithSplitOptions,PopoverSplitOptions,ReferredFrom,+ ReplaceAllSplitsOptions,SplitContent,} from './layoutManager';@@ -114,7 +115,7 @@ export function useSplitLayout() {function replaceAllSplits(content: SplitContent,- options?: { referredFrom?: ReferredFrom }+ options?: ReplaceAllSplitsOptions) {const splitManager = globalSplitManager();if (!splitManager) {diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.tsindex 1684b219a8..e7b6ea3342 100644--- a/apps/web/src/components/app/split-layout/layoutManager.ts+++ b/apps/web/src/components/app/split-layout/layoutManager.ts@@ -176,6 +176,12 @@ export type ReferredFrom =| 'fork'| null;+export type ReplaceAllSplitsOptions = {+ referredFrom?: ReferredFrom;+ /** Router state validated by the destination route, separate from runtime EntryState. */+ routeState?: unknown;+};+export type SplitState = {id: SplitId;content: SplitContent; // mirror of the pane's current router entry@@ -360,7 +366,7 @@ export type SplitManager = {/** Replace all splits with a single split containing the given content. */replaceAllSplits: (content: SplitContent,- options?: { referredFrom?: ReferredFrom }+ options?: ReplaceAllSplitsOptions) => SplitHandle | undefined;/** Check if a split exists by its split id */@@ -1677,7 +1683,7 @@ export function createSplitLayout(/** Shows `content` as the only split, in one navigation; a split already showing it stays. */function replaceAllSplits(content: SplitContent,- options: { referredFrom?: ReferredFrom } = {}+ options: ReplaceAllSplitsOptions = {}): SplitHandle | undefined {if (!canOpenContent(content, getSplitByContent(content.type, content.id)?.id)@@ -1688,10 +1694,13 @@ export function createSplitLayout(const result = router.navigate({ location: toLocation(content) },- entryOptionsOf(content, {- referredFrom: options.referredFrom ?? null,- activate: true,- })+ {+ ...entryOptionsOf(content, {+ referredFrom: options.referredFrom ?? null,+ activate: true,+ }),+ ...(options.routeState !== undefined && { state: options.routeState }),+ });const showAlone = (outcome: NavigationResult) => {if (outcome.status !== 'committed') return;diff --git a/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts b/apps/web/src/components/app/split-layout/tests/stacked-panes.test.tsindex 0d6669620c..d4e5c2fe44 100644--- a/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts+++ b/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts@@ -1,10 +1,14 @@+import { createMobileSearchEntry } from '@app/features/command/mobile/create-mobile-search-entry';+import { SearchState } from '@app/features/command/mobile/mobileSearchState';import {createMemoryHistory,createMemoryPaneStore,createSplitRouter,type Entry,+ SplitRouter,type SplitRoutes,} from '@app/lib/split-router';+import { firstChangedDepth } from '@app/lib/split-router/routes/queries';import { paneRoute } from '@app/routes/app-route';import {appRoute,@@ -13,12 +17,19 @@ import {homeSplitRoute,notFoundRoute,reviewsSplitRoute,+ searchRoute,settingsRoute,} from '@app/routes/routes';import type { BlockOrchestrator } from '@core/orchestrator';-import { createRoot } from 'solid-js';+import { cleanup, render } from '@solidjs/testing-library';+import { createComponent, createRoot } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';-import { createSplitLayout, type SplitContent } from '../layoutManager';+import { SplitPanelContext, type SplitPanelContextType } from '../context';+import {+ createSplitLayout,+ type SplitContent,+ type SplitHandle,+} from '../layoutManager';import { createMobilePaneStack } from '../mobile/createMobilePaneStack';import { createAppPanePolicy } from '../split-router/app-pane-policy';import {@@ -63,6 +74,7 @@ const routes: SplitRoutes = {settingsRoute,{ ...driveSplitRoute, children: [driveTabRoute] },reviewsSplitRoute,+ searchRoute,notFoundRoute,],},@@ -83,7 +95,27 @@ function createMockOrchestrator(): BlockOrchestrator {let dispose: (() => void) | undefined;-function setup(url: string) {+function mountSearchEntry(+ router: ReturnType<typeof createSplitRouter>,+ handle: SplitHandle+) {+ return render(() =>+ createComponent(SplitRouter.Root, {+ router,+ get children() {+ return createComponent(SplitPanelContext.Provider, {+ value: { handle } as SplitPanelContextType,+ get children() {+ createMobileSearchEntry();+ return null;+ },+ });+ },+ })+ );+}++function setup(url: string, stacked = true) {const history = createMemoryHistory(url);return createRoot((disposeRoot) => {@@ -99,14 +131,14 @@ function setup(url: string) {defaultLocation: () => ({route: paneRoute({ id: 'view-home', params: {} }),}),- stacked: () => true,+ stacked: () => stacked,}),});manager = createSplitLayout(createMockOrchestrator(), {router,toLocation: (content) => resolveContentLocation(router.routes, content),toContent: splitContentFromLocation,- stacked: () => true,+ stacked: () => stacked,});const stack = createMobilePaneStack(manager);const shown = () =>@@ -118,11 +150,137 @@ function setup(url: string) {}afterEach(() => {+ cleanup();+ SearchState.close();dispose?.();dispose = undefined;});describe('stacked panes', () => {+ it('restores search after a second entity evicts its mounted pane', () => {+ const { manager, stack, router } = setup('/search');+ const handle = manager.activeSplit()!;+ const mountSearch = () => mountSearchEntry(router, handle);+ SearchState.open();+ const view = mountSearch();+ SearchState.setQuery('original search');+ SearchState.setCategory('email');+ SearchState.searchFullText();+ manager.openWithSplit(settings);+ manager.openWithSplit(documents);+ view.unmount();+ stack.completeGoBack();+ // Search is the behind pane again, before the next Back reveals it.+ mountSearch();+ expect(SearchState.isOpen()).toBe(false);+ stack.completeGoBack();+ expect(SearchState.isOpen()).toBe(true);+ expect(SearchState.query()).toBe('original search');+ expect(SearchState.category()).toBe('email');+ expect(SearchState.mode()).toBe('full-text');+ });++ it('starts a fresh search entry when dock navigation reuses a covered native pane', () => {+ const { manager, router, history } = setup('/search');+ const handle = manager.activeSplit()!;+ const mountSearch = () => mountSearchEntry(router, handle);+ SearchState.open();+ const view = mountSearch();+ SearchState.setQuery('old query');+ SearchState.setCategory('email');+ SearchState.searchFullText();+ const pane = router.panes()[0]!;+ const previous = router.entry(pane)!;+ manager.openWithSplit(settings);+ SearchState.open();+ const pending = SearchState.session();+ manager.replaceAllSplits(+ { type: 'component', id: 'search' },+ { routeState: { sessionId: 'new-search' } }+ );+ expect(manager.activeSplit()?.id).toBe(handle.id);+ expect(router.entry(pane)?.id).not.toBe(previous.id);+ expect(router.entry(pane)?.state).toEqual({ sessionId: 'new-search' });+ expect(SearchState.session()).toBe(pending);+ // The outlet must recreate Search for the new entry in this same pane.+ expect(firstChangedDepth(router.routes, previous, router.entry(pane))).toBe(+ 1+ );+ view.unmount();+ const fresh = mountSearch();+ expect(SearchState.isOpen()).toBe(true);+ expect(SearchState.query()).toBe('');+ expect(SearchState.category()).toBe('all');+ expect(SearchState.mode()).toBe('name');+ history.back();+ fresh.unmount();+ // The previous URL still owns its original Search entry and query.+ expect(router.entry(pane)?.id).toBe(previous.id);+ const restored = mountSearch();+ manager.getSplit(manager.splits().at(-1)!.id)?.close();+ expect(SearchState.query()).toBe('old query');+ expect(SearchState.category()).toBe('email');+ expect(SearchState.mode()).toBe('full-text');+ restored.unmount();+ });++ it('reuses a Search visit only when its route session is unchanged', () => {+ const { manager, router } = setup('/search');+ const content: SplitContent = { type: 'component', id: 'search' };+ manager.replaceAllSplits(content, {+ routeState: { sessionId: 'first-search' },+ });+ const pane = router.panes()[0]!;+ const first = router.entry(pane)!;+ expect(first.state).toEqual({ sessionId: 'first-search' });++ manager.replaceAllSplits(content, {+ routeState: { sessionId: 'first-search' },+ });+ expect(router.entry(pane)?.id).toBe(first.id);++ manager.replaceAllSplits(content, {+ routeState: { sessionId: 'second-search' },+ });+ expect(router.entry(pane)?.id).not.toBe(first.id);+ expect(router.entry(pane)?.state).toEqual({ sessionId: 'second-search' });+ });++ it.each([true, false])(+ 'preserves the search session in real pane history (stacked: %s)',+ (stacked) => {+ const { manager, stack, shown, router } = setup('/search', stacked);+ const handle = manager.activeSplit()!;+ const mountSearch = () => mountSearchEntry(router, handle);+ SearchState.open();+ const view = mountSearch();+ SearchState.setQuery('teo update');+ SearchState.setCategory('email');+ SearchState.searchFullText();+ manager.openWithSplit(settings);+ if (stacked) {+ expect(SearchState.isOpen()).toBe(false);+ expect(shown()).toEqual(['search', 'settings']);+ stack.completeGoBack();+ } else {+ expect(shown()).toEqual(['settings']);+ view.unmount();+ expect(SearchState.isOpen()).toBe(false);+ // A newer dock search must not become this entry's saved state.+ SearchState.open();+ SearchState.setQuery('other search');+ SearchState.close();+ handle.goBack();+ mountSearch();+ }+ expect(shown()).toEqual(['search']);+ expect(SearchState.isOpen()).toBe(true);+ expect(SearchState.query()).toBe('teo update');+ expect(SearchState.category()).toBe('email');+ expect(SearchState.mode()).toBe('full-text');+ }+ );+it('opens content in a new pane in front, and going back closes it', () => {const { manager, stack, shown, active } = setup('/home');const forward = vi.fn();diff --git a/apps/web/src/features/command/mobile/MobileSearchInput.tsx b/apps/web/src/features/command/mobile/MobileSearchInput.tsxindex fb66da605e..e6f7ce944d 100644--- a/apps/web/src/features/command/mobile/MobileSearchInput.tsx+++ b/apps/web/src/features/command/mobile/MobileSearchInput.tsx@@ -5,7 +5,6 @@ import {import { hapticImpact } from '@core/mobile/haptics';import { usePreserveFocusOnButtonTaps } from '@core/mobile/usePreserveFocusOnButtonTaps';import XIcon from '@phosphor/x.svg';-import { createEffect, on } from 'solid-js';import { SearchState } from './mobileSearchState';// The input lives in app chrome, outside result/category boundaries, and stays@@ -22,16 +21,7 @@ export function MobileSearchInput() {// notably the category pills, so switching categories keeps the keyboard up.usePreserveFocusOnButtonTaps(() => containerRef);- // Navigation outside Search ends the session even when another surface- // opens the result (for example a link inside a full-text snippet).- createEffect(- on(foregroundView, (view, prevView) => {- if (!SearchState.isOpen()) return;- if (prevView === 'search' && view !== 'search') SearchState.close();- })- );-- // The X is how search mode ends (besides opening a result): close() resets+ // The X explicitly ends search: close() resets// the query and unmounts the search row with its input (dropping the// keyboard). The Search view only exists for searching, so exiting from it// returns to the default view.@@ -55,7 +45,7 @@ export function MobileSearchInput() {placeholder="Search…"value={SearchState.query()}// Blurring never ends the session — the keyboard drops but search- // mode stays until the X is pressed (or a result opens).+ // mode stays until the X is pressed or navigation covers this entry.onInput={(e) => SearchState.setQuery(e.currentTarget.value)}onKeyDown={(e) => {// Enter (the keyboard's Search key) drops the keyboard; the view isdiff --git a/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx b/apps/web/src/features/command/mobile/MobileSearchResults.test.tsxindex c63e0226ff..167242a520 100644--- a/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx+++ b/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx@@ -1,3 +1,4 @@+import type { EntryState } from '@components/app/split-layout/layoutManager';import type { EntityData, SearchLocation } from '@entity';import {cleanup,@@ -5,8 +6,10 @@ import {render,screen,waitFor,+ within,} from '@solidjs/testing-library';-import { type Accessor, createSignal } from 'solid-js';+import { CombinedError } from '@urql/core';+import { type Accessor, createSignal, onMount, Show } from 'solid-js';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import type { EntitySearchItem } from '../queries/entity-search';import { MobileSearchInput } from './MobileSearchInput';@@ -14,19 +17,36 @@ import { MobileSearchResults } from './MobileSearchResults';import { SearchState } from './mobileSearchState';const mocks = vi.hoisted(() => ({+ accountId: (() => 'owner') as Accessor<string>,+ authenticated: (() => true) as Accessor<boolean>,fullText: vi.fn(),fullTextItems: [] as EntityData[],fullTextData: (() => []) as Accessor<EntityData[]>,fullTextLoading: (() => false) as Accessor<boolean>,fullTextSettling: (() => false) as Accessor<boolean>,open: vi.fn(),+ onOpen: () => {},directMessage: vi.fn(),failure: vi.fn(),loadMore: vi.fn(),hasMore: true,loadingMore: false,+ viewportHeight: 400,+ deferLayout: false,+ measureLayout: () => {},fetchNextPage: vi.fn(),items: (() => []) as Accessor<EntitySearchItem[]>,+ loadingEntities: (() => false) as Accessor<boolean>,+ refreshError: (() => false) as Accessor<boolean>,+ fullTextError: (() => undefined) as Accessor<Error | undefined>,+ active: (() => true) as Accessor<boolean>,+ setActive: (_active: boolean) => {},+ entryState: undefined as EntryState | undefined,+ captors: new Map<string, () => unknown>(),+}));+vi.mock('@app/lib/split-router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),+ useSplitRouter: () => ({ entry: () => ({ id: 'search-entry' }) }),}));vi.mock('@app/lib/analytics/posthog', () => ({useFeatureFlag: () => () => ({ enabled: true }),@@ -41,13 +61,32 @@ vi.mock('@components/app/split-layout/layout', () => ({useSplitLayout: () => ({ openWithSplit: mocks.open }),}));vi.mock('@components/app/split-layout/layoutUtils', () => ({- useSplitPanelOrThrow: () => ({ handle: {} }),+ useSplitPanelOrThrow: () => ({+ handle: {+ isActive: () => mocks.active(),+ currentEntryState: () => mocks.entryState,+ content: () => ({ state: mocks.entryState }),+ captureEntryState: () => {+ mocks.entryState = Object.fromEntries(+ [...mocks.captors].map(([key, read]) => [key, read()])+ );+ },+ registerEntryStateCaptor: (key: string, getter: () => unknown) => {+ mocks.captors.set(key, getter);+ return () => mocks.captors.delete(key);+ },+ },+ }),}));vi.mock('@components/app/mobile/use-mobile-nav', () => ({useForegroundMobileView: () => () => 'search',useMobileNavNavigate: () => vi.fn(),}));vi.mock('@core/mobile/haptics', () => ({ hapticImpact: vi.fn() }));+vi.mock('@core/context/user', () => ({+ useUserId: () => mocks.accountId,+ useIsAuthenticated: () => mocks.authenticated,+}));vi.mock('@core/component/LexicalMarkdown/component/core/StaticMarkdown',() => ({@@ -76,8 +115,16 @@ vi.mock('@entity', () => ({ListEntityMetadataQueryProvider: (props: {children: import('solid-js').JSX.Element;}) => props.children,- ListLayoutProvider: (props: { children: import('solid-js').JSX.Element }) =>- props.children,+ ListLayoutProvider: (props: {+ children: import('solid-js').JSX.Element;+ onMeasured?: () => void;+ }) => {+ mocks.measureLayout = () => props.onMeasured?.();+ onMount(() => {+ if (!mocks.deferLayout) mocks.measureLayout();+ });+ return props.children;+ },ListEntity: (props: {entity: EntityData;onContentHitClick: (event: MouseEvent, location: SearchLocation) => void;@@ -99,7 +146,10 @@ vi.mock('../queries/entity-search', () => ({useEntitySearch: () => ({items: () => mocks.items(),rankItems: (items: EntitySearchItem[]) => items,- isLoadingEntities: () => false,+ isLoadingEntities: () => mocks.loadingEntities(),+ isSettling: () => mocks.loadingEntities(),+ hasError: () => mocks.refreshError(),+ hasAuthoritativeError: () => false,pagination: {hasMore: () => mocks.hasMore,isLoadingMore: () => mocks.loadingMore,@@ -114,7 +164,7 @@ vi.mock('../queries/mobile-full-text-search', () => ({data: () => mocks.fullTextData(),isLoading: () => mocks.fullTextLoading(),isSettling: () => mocks.fullTextSettling(),- error: () => undefined,+ error: () => mocks.fullTextError(),hasNextPage: () => mocks.hasMore,isFetchingNextPage: () => mocks.loadingMore,fetchNextPage: mocks.fetchNextPage,@@ -122,6 +172,20 @@ vi.mock('../queries/mobile-full-text-search', () => ({},}));beforeEach(() => {+ mocks.accountId = () => 'owner';+ mocks.authenticated = () => true;+ const [active, setActive] = createSignal(true);+ mocks.active = active;+ mocks.setActive = setActive;+ mocks.entryState = undefined;+ mocks.captors.clear();+ mocks.open.mockImplementation(() => {+ mocks.onOpen();+ mocks.entryState = Object.fromEntries(+ [...mocks.captors].map(([key, read]) => [key, read()])+ );+ setActive(false);+ });vi.spyOn(HTMLElement.prototype, 'offsetParent', 'get').mockReturnValue(document.body);@@ -134,7 +198,14 @@ beforeEach(() => {[{target,- contentRect: new DOMRect(0, 0, 400, 400),+ contentRect: new DOMRect(+ 0,+ 0,+ 400,+ target.getAttribute('role') === 'region'+ ? mocks.viewportHeight+ : 400+ ),borderBoxSize: [],contentBoxSize: [],devicePixelContentBoxSize: [],@@ -148,8 +219,14 @@ beforeEach(() => {});mocks.hasMore = true;+ mocks.onOpen = () => {};+ mocks.viewportHeight = 400;+ mocks.deferLayout = false;mocks.loadingMore = false;mocks.items = () => [];+ mocks.loadingEntities = () => false;+ mocks.refreshError = () => false;+ mocks.fullTextError = () => undefined;mocks.fullTextItems = [];mocks.fullTextData = () => mocks.fullTextItems;mocks.fullTextLoading = () => false;@@ -192,7 +269,7 @@ it('offers full text above empty results, only mounts it explicitly, and keeps texpect(screen.getByPlaceholderText('Search…')).toBe(input);});-it('omits full text for Projects and ends the session on result opening', async () => {+it('omits full text for Projects and hides search on result opening', async () => {const [items, setItems] = createSignal<EntitySearchItem[]>([]);mocks.items = items;render(() => <MobileSearchResults />);@@ -220,7 +297,7 @@ it('omits full text for Projects and ends the session on result opening', asyncexpect(SearchState.category()).toBe('all');});-it('preserves the search after a failed person lookup and closes after a successful retry', async () => {+it('preserves the search after a failed person lookup and on return from a successful retry', async () => {mocks.items = () => [{id: 'macro|[email protected]',@@ -261,11 +338,14 @@ it('preserves the search after a failed person lookup and closes after a success));expect(SearchState.isOpen()).toBe(false);- expect(SearchState.query()).toBe('');- expect(SearchState.category()).toBe('all');+ mocks.setActive(true);+ expect(SearchState.isOpen()).toBe(true);+ expect(SearchState.query()).toBe('teo');+ expect(SearchState.category()).toBe('people');+ expect(screen.getByRole('button', { name: 'Teo' })).toBeTruthy();});-it('opens the selected full-text message and resets the session', () => {+it('opens the selected full-text message and hides the search chrome', () => {const email: EntityData = {id: 'thread',type: 'email',@@ -287,12 +367,12 @@ it('opens the selected full-text message and resets the session', () => {screen.getByRole('button', { name: 'Weekly update snippet' }));expect(mocks.open).toHaveBeenCalledWith(email, {- splitHandle: {},+ splitHandle: expect.objectContaining({ isActive: expect.any(Function) }),location: { type: 'email', messageId: 'matching-message' },});expect(SearchState.isOpen()).toBe(false);- expect(SearchState.query()).toBe('');- expect(SearchState.category()).toBe('all');+ expect(SearchState.query()).toBe('teo');+ expect(SearchState.category()).toBe('email');});it('bounds mounted recent rows while keeping the first result usable', () => {@@ -313,6 +393,485 @@ it('bounds mounted recent rows while keeping the first result usable', () => {expect(SearchState.isOpen()).toBe(false);});+it('restores full-text order, query, category, mode and scroll after measuring remounted rows', async () => {+ const email: EntityData = {+ id: 'thread',+ type: 'email',+ name: 'Weekly update',+ ownerId: 'owner',+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-02T00:00:00Z',+ isRead: true,+ isDraft: false,+ isImportant: false,+ done: false,+ };+ const other = { ...email, id: 'other', name: 'Earlier update' };+ const [items, setItems] = createSignal<EntityData[]>([other, email]);+ mocks.onOpen = () => setItems([email, other]);+ const [settling, setSettling] = createSignal(false);+ mocks.fullTextData = items;+ mocks.fullTextSettling = settling;+ mocks.hasMore = false;+ SearchState.setQuery('teo');+ SearchState.setCategory('email');+ SearchState.searchFullText();+ const view = render(() => <MobileSearchResults />);+ const list = screen.getByRole('region', { name: 'Search results' });+ fireEvent.scroll(list, { target: { scrollTop: 1280 } });+ fireEvent.click(+ screen.getByRole('button', { name: 'Weekly update snippet' })+ );+ mocks.setActive(true);+ expect(+ within(list)+ .getAllByRole('button')+ .map((row) => row.textContent)+ ).toEqual(['Earlier update snippet', 'Weekly update snippet']);+ const entry = mocks.entryState;+ view.unmount();++ // A separate dock session must not overwrite this history entry.+ SearchState.open();+ SearchState.setQuery('another query');+ SearchState.setCategory('tasks');+ SearchState.close();+ expect(mocks.entryState).toBe(entry);+ mocks.setActive(true);+ setSettling(true);+ setItems([]);+ mocks.deferLayout = true;+ render(() => (+ <>+ <MobileSearchInput />+ <MobileSearchResults />+ </>+ ));+ const input = screen.getByPlaceholderText('Search…');+ expect(input).toHaveProperty('value', 'teo');+ expect(document.activeElement).not.toBe(input);+ expect(SearchState.category()).toBe('email');+ expect(SearchState.mode()).toBe('full-text');+ expect(screen.queryByText('Searching…')).toBeNull();+ expect(+ screen.getByRole('button', { name: 'Weekly update snippet' })+ ).toBeTruthy();+ expect(screen.getByRole('region', { name: 'Search results' }).scrollTop).toBe(+ 0+ );+ mocks.measureLayout();+ await waitFor(() =>+ expect(+ screen.getByRole('region', { name: 'Search results' }).scrollTop+ ).toBe(1280)+ );+ setItems([email, other]);+ setSettling(false);+ expect(+ within(screen.getByRole('region', { name: 'Search results' }))+ .getAllByRole('button')+ .map((row) => row.textContent)+ ).toEqual(['Earlier update snippet', 'Weekly update snippet']);+ expect(screen.getByRole('region', { name: 'Search results' }).scrollTop).toBe(+ 1280+ );+ expect(+ screen.getByRole('button', { name: 'Weekly update snippet' })+ ).toBeTruthy();+});++it('reveals the same scrolled results when native Back uncovers search', () => {+ mocks.fullTextItems = [+ {+ id: 'thread',+ type: 'email',+ name: 'Weekly update',+ ownerId: 'owner',+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-02T00:00:00Z',+ isRead: true,+ isDraft: false,+ isImportant: false,+ done: false,+ },+ ];+ mocks.hasMore = false;+ SearchState.setQuery('teo');+ SearchState.setCategory('email');+ SearchState.searchFullText();+ render(() => (+ <>+ <Show when={SearchState.isOpen()}>+ <MobileSearchInput />+ </Show>+ <MobileSearchResults />+ </>+ ));+ const list = screen.getByRole('region', { name: 'Search results' });+ fireEvent.scroll(list, { target: { scrollTop: 940 } });+ fireEvent.click(+ screen.getByRole('button', { name: 'Weekly update snippet' })+ );+ expect(screen.queryByPlaceholderText('Search…')).toBeNull();+ mocks.setActive(true);+ expect(screen.getByRole('region', { name: 'Search results' })).toBe(list);+ expect(list.scrollTop).toBe(940);+ const input = screen.getByPlaceholderText('Search…');+ expect(input).toHaveProperty('value', 'teo');+ expect(document.activeElement).not.toBe(input);+});++it('restores the name list order and scroll after opening promotes a result by recency', async () => {+ mocks.hasMore = false;+ const originalItems: EntitySearchItem[] = Array.from(+ { length: 100 },+ (_, index) => ({+ id: `project-${index}`,+ kind: 'initiative',+ bucket: 'initiative',+ name: `Project ${index}`,+ searchText: `Project ${index}`,+ sortTimestamp: 0,+ timestamps: {},+ })+ );+ const [items, setItems] = createSignal(originalItems);+ mocks.items = items;+ mocks.onOpen = () =>+ setItems([+ originalItems[2],+ ...originalItems.filter((item) => item.id !== 'project-2'),+ ]);+ SearchState.setQuery('Project');+ SearchState.setCategory('projects');+ const view = render(() => <MobileSearchResults />);+ fireEvent.scroll(screen.getByRole('region', { name: 'Search results' }), {+ target: { scrollTop: 800 },+ });+ const visibleResults = screen+ .getAllByRole('button')+ .map((row) => row.textContent);+ fireEvent.click(screen.getByRole('button', { name: 'Project 2' }));+ expect(screen.getAllByRole('button').map((row) => row.textContent)).toEqual(+ visibleResults+ );+ // Native Back can uncover the same mounted list before any remount.+ mocks.setActive(true);+ expect(screen.getAllByRole('button').map((row) => row.textContent)).toEqual(+ visibleResults+ );+ view.unmount();+ mocks.setActive(true);+ render(() => <MobileSearchResults />);+ expect(SearchState.query()).toBe('Project');+ expect(SearchState.category()).toBe('projects');+ await waitFor(() =>+ expect(+ screen.getByRole('region', { name: 'Search results' }).scrollTop+ ).toBe(800)+ );+ fireEvent.scroll(screen.getByRole('region', { name: 'Search results' }));+ expect(screen.getAllByRole('button').map((row) => row.textContent)).toEqual(+ visibleResults+ );+});++it('restores loaded name pages and scroll before refresh resolves, without a loading footer', async () => {+ const savedItems: EntitySearchItem[] = Array.from(+ { length: 100 },+ (_, index) => ({+ id: `project-${index}`,+ kind: 'initiative',+ bucket: 'initiative',+ name: `Project ${index}`,+ searchText: `Project ${index}`,+ sortTimestamp: 0,+ timestamps: {},+ })+ );+ const [items, setItems] = createSignal(savedItems);+ const [loading, setLoading] = createSignal(false);+ mocks.items = items;+ mocks.loadingEntities = loading;+ SearchState.setQuery('Project');+ SearchState.setCategory('projects');+ const view = render(() => <MobileSearchResults />);+ fireEvent.scroll(screen.getByRole('region', { name: 'Search results' }), {+ target: { scrollTop: 800 },+ });+ fireEvent.click(screen.getAllByRole('button')[0]);+ view.unmount();++ setLoading(true);+ setItems([]);+ mocks.setActive(true);+ render(() => <MobileSearchResults />);+ expect(screen.queryByText('Loading…')).toBeNull();+ expect(screen.getAllByRole('button').length).toBeGreaterThan(0);+ await waitFor(() =>+ expect(+ screen.getByRole('region', { name: 'Search results' }).scrollTop+ ).toBe(800)+ );++ // Browsers emit this for the programmatic restoration; JSDOM does not.+ fireEvent.scroll(screen.getByRole('region', { name: 'Search results' }));+ // A first page must not replace the larger window this entry already loaded.+ setItems(savedItems.slice(0, 1));+ setLoading(false);+ expect(screen.queryByText('Loading…')).toBeNull();+ expect(screen.getByRole('button', { name: 'Project 2' })).toBeTruthy();+ await waitFor(() => expect(mocks.loadMore).toHaveBeenCalledOnce());+ expect(screen.getByRole('region', { name: 'Search results' }).scrollTop).toBe(+ 800+ );+ setItems(+ savedItems.map((item) => ({+ ...item,+ searchText: `${item.searchText} refreshed`,+ }))+ );+ expect(+ screen.getByRole('button', { name: 'Project 2 refreshed' })+ ).toBeTruthy();+ expect(screen.getByRole('region', { name: 'Search results' }).scrollTop).toBe(+ 800+ );+});++it('does not show a loading footer for available name results during a background lookup', () => {+ mocks.items = () => [+ {+ id: 'project',+ kind: 'initiative',+ bucket: 'initiative',+ name: 'Project',+ searchText: 'Project',+ sortTimestamp: 0,+ timestamps: {},+ },+ ];+ mocks.loadingEntities = () => true;+ render(() => <MobileSearchResults />);+ expect(screen.getByRole('button', { name: 'Project' })).toBeTruthy();+ expect(screen.queryByText('Loading…')).toBeNull();+});++it.each(['name', 'full-text'] as const)(+ 'keeps user scrolling after restoring %s results and resets it for another account',+ async (mode) => {+ const [accountId, setAccountId] = createSignal('owner');+ const [authenticated, setAuthenticated] = createSignal(true);+ mocks.accountId = accountId;+ mocks.authenticated = authenticated;+ const [nameItems, setNameItems] = createSignal<EntitySearchItem[]>([+ {+ id: 'first',+ kind: 'initiative',+ bucket: 'initiative',+ name: 'First',+ searchText: 'First',+ sortTimestamp: 0,+ timestamps: {},+ },+ {+ id: 'second',+ kind: 'initiative',+ bucket: 'initiative',+ name: 'Second',+ searchText: 'Second',+ sortTimestamp: 0,+ timestamps: {},+ },+ ]);+ const [fullTextItems, setFullTextItems] = createSignal<EntityData[]>([+ {+ id: 'first',+ type: 'email',+ name: 'First',+ ownerId: 'owner',+ isRead: true,+ isDraft: false,+ isImportant: false,+ done: false,+ },+ {+ id: 'second',+ type: 'email',+ name: 'Second',+ ownerId: 'owner',+ isRead: true,+ isDraft: false,+ isImportant: false,+ done: false,+ },+ ]);+ mocks.items = nameItems;+ mocks.fullTextData = fullTextItems;+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(800);+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(+ () => mocks.viewportHeight+ );+ SearchState.setQuery('First');+ if (mode === 'full-text') SearchState.searchFullText();+ const view = render(() => <MobileSearchResults />);+ fireEvent.scroll(screen.getByRole('region', { name: 'Search results' }), {+ target: { scrollTop: 300 },+ });+ fireEvent.click(+ screen.getByRole('button', {+ name: mode === 'name' ? 'First' : 'First snippet',+ })+ );+ view.unmount();+ // A taller viewport cannot reach the previously saved offset yet.+ mocks.viewportHeight = 600;+ mocks.setActive(true);+ render(() => <MobileSearchResults />);+ const list = screen.getByRole('region', { name: 'Search results' });+ await waitFor(() => expect(list.scrollTop).toBe(300));+ // Simulate the browser clamping the initial offset to the new scroll range.+ fireEvent.scroll(list, { target: { scrollTop: 200 } });+ fireEvent.scroll(list, { target: { scrollTop: 100 } });+ setNameItems([+ { ...nameItems()[0], searchText: 'Updated first' },+ nameItems()[1],+ { ...nameItems()[0], id: 'third', searchText: 'Third' },+ ]);+ setFullTextItems([+ { ...fullTextItems()[0], name: 'Updated first' },+ fullTextItems()[1],+ { ...fullTextItems()[0], id: 'third', name: 'Third' },+ ]);+ await waitFor(() =>+ expect(+ screen.getByRole('button', {+ name: mode === 'name' ? 'Updated first' : 'Updated first snippet',+ })+ ).toBeTruthy()+ );+ expect(list.scrollTop).toBe(100);+ fireEvent.click(+ screen.getByRole('button', {+ name: mode === 'name' ? 'Updated first' : 'Updated first snippet',+ })+ );+ const scroll =+ mocks.entryState?.[+ mode === 'name'+ ? 'mobileSearch.nameScroll'+ : 'mobileSearch.fullTextScroll'+ ];+ expect(scroll).toMatchObject({ offset: 100 });+ mocks.setActive(true);+ setAccountId('another-account');+ const nextList = screen.getByRole('region', { name: 'Search results' });+ expect(nextList).not.toBe(list);+ expect(nextList.scrollTop).toBe(0);+ cleanup();+ render(() => <MobileSearchResults />);+ expect(+ screen.getByRole('region', { name: 'Search results' }).scrollTop+ ).toBe(0);+ setAuthenticated(false);+ expect(screen.queryByRole('region', { name: 'Search results' })).toBeNull();+ }+);++it('keeps restored name results after a failed refresh but accepts a successful empty result', () => {+ const [items, setItems] = createSignal<EntitySearchItem[]>([+ {+ id: 'project',+ kind: 'initiative',+ bucket: 'initiative',+ name: 'Project',+ searchText: 'Project',+ sortTimestamp: 0,+ timestamps: {},+ },+ ]);+ const [loading, setLoading] = createSignal(false);+ const [failed, setFailed] = createSignal(false);+ mocks.items = items;+ mocks.loadingEntities = loading;+ mocks.refreshError = failed;+ mocks.hasMore = false;+ SearchState.setQuery('Project');+ SearchState.setCategory('projects');+ const view = render(() => <MobileSearchResults />);+ fireEvent.click(screen.getByRole('button', { name: 'Project' }));+ view.unmount();+ setLoading(true);+ setItems([]);+ mocks.setActive(true);+ render(() => <MobileSearchResults />);+ setFailed(true);+ setLoading(false);+ expect(screen.getByRole('button', { name: 'Project' })).toBeTruthy();+ expect(screen.queryByText('Loading…')).toBeNull();+ expect(mocks.loadMore).not.toHaveBeenCalled();+ setLoading(true);+ setFailed(false);+ setLoading(false);+ expect(screen.queryByRole('button', { name: 'Project' })).toBeNull();+ expect(screen.getByText('No results')).toBeTruthy();+});++it('discards saved full-text rows on access loss even when an old cursor remains', () => {+ const [items, setItems] = createSignal<EntityData[]>([+ {+ id: 'thread',+ type: 'email',+ name: 'Weekly update',+ ownerId: 'owner',+ isRead: true,+ isDraft: false,+ isImportant: false,+ done: false,+ },+ ]);+ mocks.fullTextData = items;+ const [error, setError] = createSignal<Error>();+ mocks.fullTextError = error;+ SearchState.setQuery('teo');+ SearchState.searchFullText();+ render(() => <MobileSearchResults />);+ expect(+ screen.getByRole('button', { name: 'Weekly update snippet' })+ ).toBeTruthy();+ setError(new Error('Network unavailable'));+ expect(+ screen.getByRole('button', { name: 'Weekly update snippet' })+ ).toBeTruthy();+ setError(+ new CombinedError({+ graphQLErrors: [+ { message: 'Forbidden', extensions: { code: 'FORBIDDEN' } },+ ],+ })+ );+ // The real service source removes rows after an authoritative failure.+ setItems([]);+ expect(+ screen.queryByRole('button', { name: 'Weekly update snippet' })+ ).toBeNull();+ expect(mocks.fetchNextPage).not.toHaveBeenCalled();+});++it('keeps a covered native search entry independent of a new dock session', () => {+ SearchState.setQuery('original');+ SearchState.setCategory('email');+ render(() => <MobileSearchResults />);+ mocks.setActive(false);+ expect(SearchState.isOpen()).toBe(false);+ SearchState.open();+ SearchState.setQuery('new search');+ SearchState.setCategory('tasks');+ mocks.setActive(true);+ expect(SearchState.query()).toBe('original');+ expect(SearchState.category()).toBe('email');+});+it('loads another name page near the end without a persistent paging bar', async () => {mocks.items = () =>Array.from({ length: 100 }, (_, index) => ({diff --git a/apps/web/src/features/command/mobile/MobileSearchResults.tsx b/apps/web/src/features/command/mobile/MobileSearchResults.tsxindex fba038f232..9c18f40add 100644--- a/apps/web/src/features/command/mobile/MobileSearchResults.tsx+++ b/apps/web/src/features/command/mobile/MobileSearchResults.tsx@@ -2,11 +2,14 @@ import { useCrmContactDiscovery } from '@app/features/crm/record-adapter';import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';import { projectRouteId } from '@app/features/projects/core/route';import { createSoupRowStore } from '@app/features/soup/collection/row-store';+import { useEntryState } from '@components/app/split-layout/entry-state';import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { toast } from '@core/component/Toast/Toast';+import { useIsAuthenticated, useUserId } from '@core/context/user';import { fireAndForget } from '@core/util/fireAndForget';+import { isTransientRequestError } from '@core/util/request-error';import {type EntityData,ListEntity,@@ -18,7 +21,16 @@ import { Telemetry } from '@macro-inc/observability';import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';import { useDatabaseDiscoverySync } from '@queries/storage/databases';import { Button, CommandMenuListItem } from '@ui';-import { createMemo, createSignal, For, Show, Suspense } from 'solid-js';+import {+ createEffect,+ createMemo,+ createSignal,+ For,+ on,+ Show,+ Suspense,+ untrack,+} from 'solid-js';import { type VirtualizerHandle, VList } from 'virtua/solid';import { ItemDisplay } from '../CommandItem';import {@@ -27,35 +39,77 @@ import {useEntitySearch,} from '../queries/entity-search';import { createMobileFullTextSearch } from '../queries/mobile-full-text-search';+import { createMobileSearchEntry } from './create-mobile-search-entry';import { createSearchPagination } from './create-search-pagination';-import { SearchState } from './mobileSearchState';+import { createSearchResultWindow } from './create-search-result-window';+import type { MobileSearchSession } from './mobileSearchState';import { useMobileSearchCategory } from './use-mobile-search-category';-function MobileNameResults() {- let virtualizer: VirtualizerHandle | undefined;+type SearchScrollState = {+ accountId: string;+ query: string;+ category: EntitySearchCategory;+ offset: number;+ cache?: VirtualizerHandle['cache'];+};++function MobileNameResults(props: {+ session: MobileSearchSession;+ accountId: string;+}) {+ const state = props.session;+ const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();const [container, setContainer] = createSignal<HTMLDivElement>();- const category = useMobileSearchCategory();- const source = useEntitySearch(SearchState.query, category, {- enabled: SearchState.isOpen,+ const category = useMobileSearchCategory(state.category);+ const [scroll, setScroll] = useEntryState<SearchScrollState | undefined>(+ 'mobileSearch.nameScroll',+ { default: undefined }+ );+ const initialScroll = untrack(() => scroll());+ let restore =+ initialScroll?.accountId === props.accountId &&+ initialScroll.query === state.query() &&+ initialScroll.category === category()+ ? initialScroll+ : undefined;+ const source = useEntitySearch(state.query, category, {+ enabled: () => true,contactDiscovery: useCrmContactDiscovery,});- useDatabaseDiscoverySync(SearchState.isOpen);- const items = createMemo(() =>- source.rankItems(source.items(), SearchState.query())+ useDatabaseDiscoverySync(() => true);+ const incoming = createMemo(() =>+ source.rankItems(source.items(), state.query()));+ const results = createSearchResultWindow({+ key: 'mobileSearch.nameResults',+ accountId: () => props.accountId,+ query: state.query,+ category,+ items: incoming,+ pending: () =>+ source.isSettling() ||+ source.pagination.isLoadingMore() ||+ source.hasError(),+ discard: source.hasAuthoritativeError,+ hasMore: source.pagination.hasMore,+ });+ const items = results.items;const loadMoreNearEnd = createSearchPagination({- items,+ items: incoming,container,- remaining: () =>- items().length === 0+ remaining: () => {+ const handle = virtualizer();+ return results.needsMore() || items().length === 0? 0- : virtualizer- ? virtualizer.scrollSize -- virtualizer.scrollOffset -- virtualizer.viewportSize- : undefined,+ : handle+ ? handle.scrollSize - handle.scrollOffset - handle.viewportSize+ : undefined;+ },hasMore: source.pagination.hasMore,- busy: () => source.isLoadingEntities() || source.pagination.isLoadingMore(),+ busy: () =>+ source.isSettling() ||+ source.pagination.isLoadingMore() ||+ source.hasError(),loadMore: source.pagination.loadMore,});const { openWithSplit } = useSplitLayout();@@ -66,7 +120,6 @@ function MobileNameResults() {span.setAttr('entity.id', item.id);span.setAttr('entity.type', item.bucket);if (item.kind === 'initiative') {- SearchState.close();openWithSplit({type: 'component',id: projectRouteId({ id: item.id, section: 'overview' }),@@ -75,20 +128,45 @@ function MobileNameResults() {const result = await directMessage.mutateAsync({recipient_id: item.id,});- SearchState.close();openWithSplit({ type: 'channel', id: result.channel_id },{ reopen: 'latest' });} else {- SearchState.close();await openEntityInSplitFromUnifiedList(item.data, {splitHandle: panel.handle,});}});};+ createEffect(+ on([items, virtualizer, source.hasAuthoritativeError], () => {+ if (source.hasAuthoritativeError()) restore = undefined;+ const handle = virtualizer();+ if (!restore || !handle || items().length === 0) return;+ if (restore.query !== state.query() || restore.category !== category()) {+ restore = undefined;+ return;+ }+ handle.scrollTo(restore.offset);+ // The saved window is already mounted; later pages must not move the user.+ restore = undefined;+ })+ );+ const onScroll = () => {+ const handle = virtualizer();+ if (handle && !restore)+ setScroll({+ accountId: props.accountId,+ query: state.query(),+ category: category(),+ offset: handle.scrollOffset,+ cache: handle.cache,+ });+ loadMoreNearEnd();+ };const select = async (item: EntitySearchItem) => {+ results.preserveOrder();try {await open(item);} catch {@@ -100,32 +178,28 @@ function MobileNameResults() {ref={setContainer}class="flex h-full min-h-0 flex-col px-3 mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)">- <Show when={SearchState.query().trim() && category() !== 'projects'}>+ <Show when={state.query().trim() && category() !== 'projects'}><divdata-keep-keyboardonPointerDown={(event) => event.preventDefault()}onMouseDown={(event) => event.preventDefault()}>- <CommandMenuListItem- class="min-h-11"- onClick={SearchState.searchFullText}- >+ <CommandMenuListItem class="min-h-11" onClick={state.searchFullText}><span class="truncate">- Search full text for “{SearchState.query().trim()}”+ Search full text for “{state.query().trim()}”</span></CommandMenuListItem></div></Show><Show when={items().length > 0}><VList- ref={(handle) => {- virtualizer = handle;- }}+ ref={setVirtualizer}data={items()}+ cache={restore?.cache}role="region"aria-label="Search results"class="min-h-0 flex-1 overscroll-none"- onScroll={loadMoreNearEnd}+ onScroll={onScroll}>{(item) => (<CommandMenuListItem@@ -137,7 +211,7 @@ function MobileNameResults() {)}</VList></Show>- <Show when={source.isLoadingEntities()}>+ <Show when={source.isLoadingEntities() && items().length === 0}><p role="status" class="p-3 text-ink-muted">Loading…</p>@@ -149,33 +223,75 @@ function MobileNameResults() {);}-function MobileFullTextResults() {- const category = useMobileSearchCategory();- const search = createMobileFullTextSearch(SearchState.query, category);+function MobileFullTextResults(props: {+ session: MobileSearchSession;+ accountId: string;+}) {+ const state = props.session;+ const category = useMobileSearchCategory(state.category);+ const search = createMobileFullTextSearch(state.query, category);+ const hasAuthoritativeError = () =>+ !!search.error() && !isTransientRequestError(search.error());const panel = useSplitPanelOrThrow();const [container, setContainer] = createSignal<HTMLDivElement>();- // A same-query refresh must not collapse the scroller between pages.- const results = createMemo<{- query: string;- category: EntitySearchCategory;- items: EntityData[];- }>((previous) => {- const query = SearchState.query().trim();- const scope = category();- const items = search.data();- if (search.isSettling()) {- if (previous?.query === query && previous.category === scope)- return previous;- return { query, category: scope, items: [] };- }- return { query, category: scope, items };+ const [layoutReady, setLayoutReady] = createSignal(false);+ const [scroll, setScroll] = useEntryState<SearchScrollState | undefined>(+ 'mobileSearch.fullTextScroll',+ { default: undefined }+ );+ const initialScroll = untrack(() => scroll());+ let restore =+ initialScroll?.accountId === props.accountId ? initialScroll : undefined;+ const incoming = createMemo(() => (search.isSettling() ? [] : search.data()));+ const results = createSearchResultWindow({+ key: 'mobileSearch.fullTextResults',+ accountId: () => props.accountId,+ query: state.query,+ category,+ items: incoming,+ pending: () =>+ search.isSettling() || search.isFetchingNextPage() || !!search.error(),+ discard: hasAuthoritativeError,+ hasMore: search.hasNextPage,});// Page selection rematerializes entities; retain row identity as pages append.- const rows = createSoupRowStore(() => results().items);+ const rows = createSoupRowStore(results.items);+ let restoreQueued = false;+ createEffect(+ on([results.items, container, layoutReady, hasAuthoritativeError], () => {+ if (hasAuthoritativeError()) restore = undefined;+ const list = container();+ if (+ !restore ||+ !list ||+ !layoutReady() ||+ !results.items().length ||+ restoreQueued+ )+ return;+ restoreQueued = true;+ // ResizeObserver selects narrow/wide rows; let that DOM update commit+ // before assigning an offset that the temporary wide layout could clamp.+ queueMicrotask(() => {+ restoreQueued = false;+ if (!restore || !list.isConnected || list !== container()) return;+ if (+ restore.query !== state.query() ||+ restore.category !== category()+ ) {+ restore = undefined;+ return;+ }+ list.scrollTop = restore.offset;+ restore = undefined;+ });+ })+ );const loadMoreNearEnd = createSearchPagination({- items: () => results().items,+ items: incoming,container,remaining: () => {+ if (results.needsMore()) return 0;const list = container();return list? list.scrollHeight - list.scrollTop - list.clientHeight@@ -187,12 +303,12 @@ function MobileFullTextResults() {loadMore: search.fetchNextPage,});const open = async (entity: EntityData, location?: SearchLocation) => {+ results.preserveOrder();try {await Telemetry.span('mobile.search.open', async (span) => {span.setAttr('entity.id', entity.id);span.setAttr('entity.type', entity.type);span.setAttr('search.content_hit', !!location);- SearchState.close();await openEntityInSplitFromUnifiedList(entity, {splitHandle: panel.handle,location,@@ -207,11 +323,23 @@ function MobileFullTextResults() {ref={setContainer}role="region"aria-label="Search results"- onScroll={loadMoreNearEnd}- class="soup-list h-full overflow-y-auto overscroll-none mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)"+ onScroll={(event) => {+ if (!restore)+ setScroll({+ accountId: props.accountId,+ query: state.query(),+ category: category(),+ offset: event.currentTarget.scrollTop,+ });+ loadMoreNearEnd();+ }}+ class="soup-list h-full overflow-y-auto overscroll-none [overflow-anchor:none] mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)"><ListEntityMetadataQueryProvider>- <ListLayoutProvider ref={container}>+ <ListLayoutProvider+ ref={container}+ onMeasured={() => setLayoutReady(true)}+ ><StaticMarkdownContext><For each={rows()}>{(entity) => (@@ -230,7 +358,7 @@ function MobileFullTextResults() {</StaticMarkdownContext></ListLayoutProvider></ListEntityMetadataQueryProvider>- <Show when={search.isSettling() && results().items.length === 0}>+ <Show when={search.isSettling() && results.items().length === 0}><p role="status" class="p-3 text-ink-muted">Searching…</p>@@ -249,7 +377,7 @@ function MobileFullTextResults() {when={!search.isSettling() &&!search.error() &&- results().items.length === 0+ results.items().length === 0}><p class="p-3 text-ink-muted">No results</p>@@ -260,14 +388,21 @@ function MobileFullTextResults() {/** The dock owns the input; only the result subtree changes search modes. */export function MobileSearchResults() {+ const session = createMobileSearchEntry();+ const accountId = useUserId();+ const authenticated = useIsAuthenticated();return (- <Suspense fallback={<p role="status">Loading…</p>}>- <Show- when={SearchState.mode() === 'full-text'}- fallback={<MobileNameResults />}- >- <MobileFullTextResults />- </Show>- </Suspense>+ <Show when={authenticated() === true ? accountId() : undefined} keyed>+ {(id) => (+ <Suspense fallback={<p role="status">Loading…</p>}>+ <Show+ when={session.mode() === 'full-text'}+ fallback={<MobileNameResults session={session} accountId={id} />}+ >+ <MobileFullTextResults session={session} accountId={id} />+ </Show>+ </Suspense>+ )}+ </Show>);}diff --git a/apps/web/src/features/command/mobile/create-mobile-search-entry.ts b/apps/web/src/features/command/mobile/create-mobile-search-entry.tsnew file mode 100644index 0000000000..7085ae17bd--- /dev/null+++ b/apps/web/src/features/command/mobile/create-mobile-search-entry.ts@@ -0,0 +1,50 @@+import { type PaneId, useSplitRouter } from '@app/lib/split-router';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { createEffect, on, onCleanup, untrack } from 'solid-js';+import {+ createMobileSearchSession,+ type MobileSearchSnapshot,+ SearchState,+} from './mobileSearchState';++/** Bind chrome to this entry only while it is foregrounded, without focusing it. */+export function createMobileSearchEntry() {+ const { handle } = useSplitPanelOrThrow();+ const router = useSplitRouter();+ const currentEntry = () => router.entry(handle.id as string as PaneId);+ const entryId = untrack(() => currentEntry()?.id);+ const stored = untrack(+ () => handle.currentEntryState()?.['mobileSearch.session']+ ) as MobileSearchSnapshot | undefined;+ const session = stored+ ? createMobileSearchSession(stored)+ : untrack(() =>+ SearchState.isOpen()+ ? SearchState.session()+ : createMobileSearchSession()+ );+ const dispose = handle.registerEntryStateCaptor(+ 'mobileSearch.session',+ session.snapshot+ );+ createEffect(+ on([handle.isActive, () => currentEntry()?.id], ([active, currentId]) => {+ // Pane activation can precede outlet teardown during history changes.+ // A departing view must never bind or capture into the arriving entry.+ if (currentId !== entryId) return;+ if (active) {+ SearchState.resume(session);+ } else {+ // Native stacks only mount the front two panes. Capture before a+ // later entity can push this covered Search out of those slots.+ handle.captureEntryState();+ SearchState.suspend(session);+ }+ })+ );+ onCleanup(() => {+ dispose();+ SearchState.suspend(session);+ });+ return session;+}diff --git a/apps/web/src/features/command/mobile/create-search-result-window.test.ts b/apps/web/src/features/command/mobile/create-search-result-window.test.tsnew file mode 100644index 0000000000..20c361500f--- /dev/null+++ b/apps/web/src/features/command/mobile/create-search-result-window.test.ts@@ -0,0 +1,239 @@+import type { EntryState } from '@components/app/split-layout/layoutManager';+import { batch, createRoot, createSignal } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { EntitySearchCategory } from '../queries/entity-search';+import { createSearchResultWindow } from './create-search-result-window';++const history = vi.hoisted(() => ({+ state: undefined as EntryState | undefined,+ captors: new Map<string, () => unknown>(),+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({+ handle: {+ currentEntryState: () => history.state,+ registerEntryStateCaptor: (key: string, read: () => unknown) => {+ history.captors.set(key, read);+ return () => history.captors.delete(key);+ },+ },+ }),+}));++type Row = { id: string; name: string };+const original: Row[] = [+ { id: 'a', name: 'First' },+ { id: 'b', name: 'Second' },+ { id: 'c', name: 'Third' },+];+const cleanups: (() => void)[] = [];+beforeEach(() => {+ history.state = undefined;+ history.captors.clear();+});+afterEach(() => {+ for (const dispose of cleanups.splice(0)) dispose();+});++function setup(+ items: Row[],+ initial: { accountId?: string; hasMore?: boolean; pending?: boolean } = {}+) {+ return createRoot((dispose) => {+ cleanups.push(dispose);+ const [accountId, setAccountId] = createSignal(+ initial.accountId ?? 'alice'+ );+ const [query, setQuery] = createSignal('notes');+ const [category, setCategory] = createSignal<EntitySearchCategory>('all');+ const [incoming, setItems] = createSignal(items);+ const [pending, setPending] = createSignal(initial.pending ?? false);+ const [hasMore, setHasMore] = createSignal(initial.hasMore ?? false);+ const [discard, setDiscard] = createSignal(false);+ const results = createSearchResultWindow({+ key: 'results',+ accountId,+ query,+ category,+ items: incoming,+ pending,+ hasMore,+ discard,+ });+ return {+ results,+ dispose,+ setAccountId,+ setQuery,+ setCategory,+ setItems,+ setPending,+ setHasMore,+ setDiscard,+ };+ });+}++it('ranks live until opening, then updates rows in place and appends later results', () => {+ const { results, setItems } = setup(original);+ setItems([original[2], original[1], original[0]]);+ expect(results.items().map((row) => row.id)).toEqual(['c', 'b', 'a']);+ results.preserveOrder();+ const updated = { id: 'c', name: 'Third, recently opened' };+ setItems([original[0], original[1], updated]);+ expect(results.items()).toEqual([updated, original[1], original[0]]);+ const added = { id: 'd', name: 'Next page' };+ setItems([added, original[0], original[1], updated]);+ expect(results.items()).toEqual([updated, original[1], original[0], added]);+ setItems([added, original[0], updated]);+ expect(results.items()).toEqual([updated, original[0], added]);+});++it('restores saved order while rebuilding a shorter first page and paging further', () => {+ const first = setup(original);+ first.results.preserveOrder();+ history.state = Object.fromEntries(+ [...history.captors].map(([key, read]) => [key, read()])+ );+ first.dispose();+ const { results, setItems } = setup([original[2]], { hasMore: true });+ expect(results.items()).toEqual(original);+ expect(results.needsMore()).toBe(true);+ const updated = { id: 'c', name: 'Recently opened' };+ setItems([updated, original[0], original[1]]);+ expect(results.items()).toEqual([original[0], original[1], updated]);+ expect(results.needsMore()).toBe(false);+ const added = { id: 'd', name: 'Later result' };+ setItems([updated, added, original[0], original[1]]);+ expect(results.items()).toEqual([original[0], original[1], updated, added]);+});++it('keeps saved rows that move beyond the refreshed page without scanning every page', () => {+ const { results, setItems, setHasMore } = setup(original, { hasMore: true });+ results.preserveOrder();+ const added = { id: 'd', name: 'New recent result' };+ setItems([added, original[2], original[0]]);+ expect(results.items()).toEqual([...original, added]);+ // The previously loaded size is rebuilt. Further pages follow user scrolling.+ expect(results.needsMore()).toBe(false);+ const updated = { id: 'c', name: 'Updated third' };+ setItems([added, updated, original[0]]);+ expect(results.items()).toEqual([original[0], original[1], updated, added]);+ setItems([added, updated, original[0], original[1]]);+ expect(results.items()).toEqual([original[0], original[1], updated, added]);+ setItems([added, updated, original[0]]);+ setHasMore(false);+ expect(results.items()).toEqual([original[0], updated, added]);+});++it('preserves the mounted list when history is captured outside a result opener', () => {+ const { results, setItems } = setup(original);+ history.state = Object.fromEntries(+ [...history.captors].map(([key, read]) => [key, read()])+ );+ setItems([original[2], original[0], original[1]]);+ expect(results.items()).toEqual(original);+});++it('restores the source refill size without counting retained rows as extra loaded pages', () => {+ const first = setup(original, { hasMore: true });+ first.results.preserveOrder();+ const added = { id: 'd', name: 'New recent result' };+ first.setItems([added, original[2], original[0]]);+ expect(first.results.items()).toEqual([...original, added]);+ history.state = Object.fromEntries(+ [...history.captors].map(([key, read]) => [key, read()])+ );+ first.dispose();+ const second = setup([added, original[2], original[0]], { hasMore: true });+ expect(second.results.items()).toEqual([...original, added]);+ expect(second.results.needsMore()).toBe(false);+ const next = { id: 'e', name: 'Next page' };+ second.setItems([added, original[2], original[0], next]);+ expect(second.results.items()).toEqual([...original, added, next]);+ expect(second.results.needsMore()).toBe(false);+});++it('ranks new queries and categories afresh, including revisiting an earlier query', () => {+ const { results, setItems, setQuery, setCategory } = setup(original);+ results.preserveOrder();+ setItems([original[2], original[1], original[0]]);+ expect(results.items()).toEqual(original);+ setQuery('different');+ expect(results.items().map((row) => row.id)).toEqual(['c', 'b', 'a']);+ setItems(original);+ expect(results.items()).toEqual(original);+ batch(() => {+ setCategory('email');+ setItems([original[2], original[0], original[1]]);+ });+ expect(results.items().map((row) => row.id)).toEqual(['c', 'a', 'b']);+ batch(() => {+ setQuery('notes');+ setCategory('all');+ setItems([original[1], original[0], original[2]]);+ });+ expect(results.items().map((row) => row.id)).toEqual(['b', 'a', 'c']);+ setItems(original);+ expect(results.items()).toEqual(original);+});++it('discards saved rows on authoritative failure and accepts successful empty results', () => {+ const { results, setItems, setPending, setHasMore, setDiscard } =+ setup(original);+ results.preserveOrder();+ batch(() => {+ setPending(true);+ setHasMore(true);+ setItems([original[2]]);+ });+ expect(results.items()).toEqual(original);+ setDiscard(true);+ expect(results.items()).toEqual([original[2]]);+ batch(() => {+ setDiscard(false);+ setPending(false);+ setHasMore(false);+ setItems([]);+ });+ expect(results.items()).toEqual([]);+});++it('drops the previous account window while the next account is loading', () => {+ const { results, setAccountId, setItems, setPending, setHasMore } =+ setup(original);+ results.preserveOrder();+ batch(() => {+ setAccountId('bob');+ setPending(true);+ setHasMore(true);+ setItems([]);+ });+ expect(results.items()).toEqual([]);+ expect(results.needsMore()).toBe(false);+ batch(() => {+ setItems([original[2], original[0]]);+ setPending(false);+ });+ expect(results.items()).toEqual([original[2], original[0]]);+});++it('ignores another account snapshot when remounting a history entry', () => {+ const first = setup(original);+ history.state = Object.fromEntries(+ [...history.captors].map(([key, read]) => [key, read()])+ );+ first.dispose();+ const { results, setItems, setPending } = setup([], {+ accountId: 'bob',+ hasMore: true,+ pending: true,+ });+ expect(results.items()).toEqual([]);+ expect(results.needsMore()).toBe(false);+ batch(() => {+ setItems([original[2], original[0]]);+ setPending(false);+ });+ expect(results.items()).toEqual([original[2], original[0]]);+});diff --git a/apps/web/src/features/command/mobile/create-search-result-window.ts b/apps/web/src/features/command/mobile/create-search-result-window.tsnew file mode 100644index 0000000000..611b8c168f--- /dev/null+++ b/apps/web/src/features/command/mobile/create-search-result-window.ts@@ -0,0 +1,116 @@+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import {+ type Accessor,+ createMemo,+ createSignal,+ onCleanup,+ untrack,+} from 'solid-js';+import type { EntitySearchCategory } from '../queries/entity-search';++type SearchResultWindow<T> = {+ accountId: string;+ query: string;+ category: EntitySearchCategory;+ items: T[];+ /** Live rows already loaded; retained rows may also belong to later pages. */+ sourceSize: number;+};++/** Restore loaded rows in their saved order while sources refresh and page. */+export function createSearchResultWindow<T extends { id: string }>(options: {+ key: string;+ accountId: Accessor<string>;+ query: Accessor<string>;+ category: Accessor<EntitySearchCategory>;+ items: Accessor<T[]>;+ pending: Accessor<boolean>;+ discard: Accessor<boolean>;+ hasMore: Accessor<boolean>;+}) {+ const { handle } = useSplitPanelOrThrow();+ const stored = untrack(() => handle.currentEntryState()?.[options.key]) as+ | SearchResultWindow<T>+ | undefined;+ const scope = createMemo(() => ({+ accountId: options.accountId(),+ query: options.query(),+ category: options.category(),+ }));+ const [preservedScope, setPreservedScope] = createSignal(+ untrack(() => {+ const initial = scope();+ return stored?.accountId === initial.accountId &&+ stored.query === initial.query &&+ stored.category === initial.category+ ? initial+ : undefined;+ })+ );+ const window = createMemo<SearchResultWindow<T>>(+ (previous) => {+ const currentScope = scope();+ const { accountId, query, category } = currentScope;+ const items = options.items();+ const next = {+ accountId,+ query,+ category,+ items,+ sourceSize: items.length,+ };+ if (options.discard()) return next;+ if (+ previous?.accountId === accountId &&+ previous.query === query &&+ previous.category === category+ ) {+ if (+ previous.items.length > 0 &&+ (options.pending() ||+ (items.length < previous.sourceSize && options.hasMore()))+ )+ return previous;+ if (preservedScope() === currentScope) {+ const remaining = new Map(items.map((item) => [item.id, item]));+ const ordered = previous.items.flatMap((item) => {+ const updated = remaining.get(item.id);+ // An absent saved row can still belong to a later source page.+ if (!updated) return options.hasMore() ? [item] : [];+ remaining.delete(item.id);+ return [updated];+ });+ return {+ ...next,+ items: [...ordered, ...remaining.values()],+ };+ }+ }+ return next;+ },+ stored ?? {+ accountId: untrack(options.accountId),+ query: untrack(options.query),+ category: untrack(options.category),+ items: [],+ sourceSize: 0,+ }+ );+ const preserveOrder = () => setPreservedScope(scope());+ onCleanup(+ handle.registerEntryStateCaptor(options.key, () => {+ preserveOrder();+ return window();+ })+ );+ return {+ items: () => window().items,+ // Freeze before opening can update viewedAt and re-rank the live source.+ preserveOrder,+ needsMore: () =>+ !options.pending() &&+ !options.discard() &&+ options.hasMore() &&+ options.items().length < window().sourceSize,+ };+}diff --git a/apps/web/src/features/command/mobile/mobile-search-route-state.ts b/apps/web/src/features/command/mobile/mobile-search-route-state.tsnew file mode 100644index 0000000000..1e8c415c25--- /dev/null+++ b/apps/web/src/features/command/mobile/mobile-search-route-state.ts@@ -0,0 +1,10 @@+import { z } from 'zod';++/** A dock search starts a new visit without changing the Search URL. */+export const mobileSearchRouteStateSchema = z.object({+ sessionId: z.string().min(1),+});++export type MobileSearchRouteState = z.infer<+ typeof mobileSearchRouteStateSchema+>;diff --git a/apps/web/src/features/command/mobile/mobileSearchState.ts b/apps/web/src/features/command/mobile/mobileSearchState.tsindex 6085b917ed..6cbe2d7467 100644--- a/apps/web/src/features/command/mobile/mobileSearchState.ts+++ b/apps/web/src/features/command/mobile/mobileSearchState.ts@@ -3,16 +3,13 @@ import { Telemetry } from '@macro-inc/observability';import { type Accessor, batch, createSignal } from 'solid-js';import type { EntitySearchCategory } from '../queries/entity-search';-interface IMobileSearchState {- /**- * Whether a search session is active — from the dock's search button until- * the input's X is pressed (or a result opens). Blurring the input only- * drops the keyboard; it never ends the session.- */- isOpen: Accessor<boolean>;- open: () => void;- close: () => void;+export type MobileSearchSnapshot = {+ query: string;+ category: EntitySearchCategory;+ mode: 'name' | 'full-text';+};+export interface MobileSearchSession {category: Accessor<EntitySearchCategory>;setCategory: (category: EntitySearchCategory) => void;mode: Accessor<'name' | 'full-text'>;@@ -21,15 +18,20 @@ interface IMobileSearchState {/** query (the dock input's live value) */query: Accessor<string>;setQuery: (value: string) => void;+ snapshot: () => MobileSearchSnapshot;}-export function createMobileSearchState(): IMobileSearchState {- const [isOpen, setIsOpen] = createControlledOpenSignal(false, {- id: 'command',- });- const [query, writeQuery] = createSignal('');- const [category, writeCategory] = createSignal<EntitySearchCategory>('all');- const [mode, setMode] = createSignal<'name' | 'full-text'>('name');+/** Query state belongs to a Search history entry, including while it is covered. */+export function createMobileSearchSession(+ initial?: MobileSearchSnapshot+): MobileSearchSession {+ const [query, writeQuery] = createSignal(initial?.query ?? '');+ const [category, writeCategory] = createSignal<EntitySearchCategory>(+ initial?.category ?? 'all'+ );+ const [mode, setMode] = createSignal<'name' | 'full-text'>(+ initial?.mode ?? 'name'+ );const setQuery = (value: string) =>batch(() => {writeQuery(value);@@ -52,46 +54,58 @@ export function createMobileSearchState(): IMobileSearchState {}};- function open() {- if (isOpen()) return;- batch(() => {- writeQuery('');- writeCategory('all');- setMode('name');- setIsOpen(true);- });- }-- /**- * Ends and resets the session. Passes `shouldReturnFocus: false` — the- * dock mounts and focuses the input when opening; restoring focus during- * teardown could re-raise the keyboard.- */- function close() {- batch(() => {- setIsOpen(false, false);- writeQuery('');- writeCategory('all');- setMode('name');- });- }-return {- isOpen,- open,- close,-query,setQuery,category,setCategory,mode,searchFullText,+ snapshot: () => ({ query: query(), category: category(), mode: mode() }),+ };+}++export function createMobileSearchState() {+ const [isOpen, setIsOpen] = createControlledOpenSignal(false, {+ id: 'command',+ });+ const [session, setSession] = createSignal(createMobileSearchSession());+ return {+ isOpen,+ session,+ open: () => {+ if (isOpen()) return;+ batch(() => {+ setSession(createMobileSearchSession());+ setIsOpen(true);+ });+ },+ close: () => {+ batch(() => {+ setIsOpen(false, false);+ setSession(createMobileSearchSession());+ });+ },+ resume: (value: MobileSearchSession) => {+ batch(() => {+ setSession(value);+ setIsOpen(true);+ });+ },+ suspend: (value: MobileSearchSession) => {+ if (session() === value) setIsOpen(false, false);+ },+ query: () => session().query(),+ setQuery: (value: string) => session().setQuery(value),+ category: () => session().category(),+ setCategory: (value: EntitySearchCategory) => session().setCategory(value),+ mode: () => session().mode(),+ searchFullText: () => session().searchFullText(),};}/**- * Global mobile search session singleton — the dock input whose query feeds- * the Search route's transient entity and full-text search.+ * App chrome controls the foreground Search entry. Opening from the dock+ * creates a session before mounting/focusing its input in the tap handler.*/export const SearchState = createMobileSearchState();diff --git a/apps/web/src/features/command/mobile/use-mobile-search-category.ts b/apps/web/src/features/command/mobile/use-mobile-search-category.tsindex 010813edae..1f2aa5cd32 100644--- a/apps/web/src/features/command/mobile/use-mobile-search-category.ts+++ b/apps/web/src/features/command/mobile/use-mobile-search-category.ts@@ -1,11 +1,13 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableProjects } from '@core/constant/featureFlags';+import type { Accessor } from 'solid-js';+import type { EntitySearchCategory } from '../queries/entity-search';import { SearchState } from './mobileSearchState';-export function useMobileSearchCategory() {+export function useMobileSearchCategory(+ category: Accessor<EntitySearchCategory> = SearchState.category+) {const projects = useFeatureFlag(enableProjects);return () =>- SearchState.category() === 'projects' && !projects().enabled- ? 'all'- : SearchState.category();+ category() === 'projects' && !projects().enabled ? 'all' : category();}diff --git a/apps/web/src/features/command/project-items.ts b/apps/web/src/features/command/project-items.tsindex a537e4e54e..172994f625 100644--- a/apps/web/src/features/command/project-items.ts+++ b/apps/web/src/features/command/project-items.ts@@ -60,6 +60,7 @@ export function useProjectCommandItems(})) ?? []): [],isLoading: () => enabled() && query.loading(),+ error: () => (enabled() ? query.error() : undefined),hasMore: () => enabled() && query.hasMore(),isLoadingMore: () => enabled() && query.loadingMore(),loadMore: async () => {diff --git a/apps/web/src/features/command/queries/entity-search.ts b/apps/web/src/features/command/queries/entity-search.tsindex 2b0d6a636d..43b0290d40 100644--- a/apps/web/src/features/command/queries/entity-search.ts+++ b/apps/web/src/features/command/queries/entity-search.ts@@ -5,6 +5,7 @@ import {} from '@core/context/quickAccess';import { exclude } from '@core/context/quickAccess/types';import { useUserId } from '@core/context/user';+import { isTransientRequestError } from '@core/util/request-error';import { type Accessor, createMemo } from 'solid-js';import { contactCommandItems } from '../contact-items';import {@@ -139,6 +140,22 @@ export function useEntitySearch(withDiscovery,rankItems,projectsEnabled: projects.enabled,+ isSettling: () =>+ !!activeList()?.isLoading() ||+ projects.isLoading() ||+ (contactsActive() && (contacts?.isLoading() ?? false)),+ hasError: () =>+ !!activeList()?.error() ||+ !!projects.error() ||+ (contactsActive() && !!contacts?.error()),+ hasAuthoritativeError: () => {+ const projectError = projects.error();+ const contactError = contactsActive() ? contacts?.error() : undefined;+ return !!(+ (projectError && !isTransientRequestError(projectError)) ||+ (contactError && !isTransientRequestError(contactError))+ );+ },isLoadingEntities: () =>(!!activeList()?.isLoading() && activeList()?.items().length === 0) ||projects.isLoading() ||diff --git a/apps/web/src/features/command/queries/mobile-full-text-search.test.ts b/apps/web/src/features/command/queries/mobile-full-text-search.test.tsindex a546f11e3b..68cced9864 100644--- a/apps/web/src/features/command/queries/mobile-full-text-search.test.ts+++ b/apps/web/src/features/command/queries/mobile-full-text-search.test.ts@@ -7,14 +7,45 @@ import { createMobileFullTextSearch } from './mobile-full-text-search';const capture = vi.hoisted(() => ({options: undefined as CreateSearchStateOptions | undefined,+ pending: false,+ serviceEnabled: true,}));vi.mock('@app/features/soup/search', () => ({createSearchState: (options: CreateSearchStateOptions) => {capture.options = options;- return {};+ return {+ isSettling: () => false,+ searchQuery: {+ get isPending() {+ return capture.pending;+ },+ get isEnabled() {+ return capture.serviceEnabled && (options.enabled?.() ?? true);+ },+ },+ };},}));+it('keeps an enabled initial query settling before it starts fetching', () => {+ createRoot((dispose) => {+ const [query, setQuery] = createSignal('teo');+ const search = createMobileFullTextSearch(query, () => 'all');+ capture.pending = true;+ expect(search.isSettling()).toBe(true);+ capture.pending = false;+ expect(search.isSettling()).toBe(false);+ capture.pending = true;+ capture.serviceEnabled = false;+ expect(search.isSettling()).toBe(false);+ capture.serviceEnabled = true;+ setQuery('');+ expect(search.isSettling()).toBe(false);+ capture.pending = false;+ dispose();+ });+});+it('maps Email and People without mailbox facets and gates Projects/empty queries', () => {createRoot((dispose) => {const [category, setCategory] = createSignal<EntitySearchCategory>('email');diff --git a/apps/web/src/features/command/queries/mobile-full-text-search.ts b/apps/web/src/features/command/queries/mobile-full-text-search.tsindex eac9d3c649..fae421fde7 100644--- a/apps/web/src/features/command/queries/mobile-full-text-search.ts+++ b/apps/web/src/features/command/queries/mobile-full-text-search.ts@@ -11,7 +11,7 @@ export function createMobileFullTextSearch(text: Accessor<string>,category: Accessor<EntitySearchCategory>) {- return createSearchState({+ const search = createSearchState({text,disableLocalSearch: () => true,enabled: () => category() !== 'projects' && !!text().trim(),@@ -25,4 +25,10 @@ export function createMobileFullTextSearch(search),});+ return {+ ...search,+ isSettling: () =>+ search.isSettling() ||+ (search.searchQuery.isEnabled && search.searchQuery.isPending),+ };}diff --git a/apps/web/src/features/command/useCommandItems.contacts.test.ts b/apps/web/src/features/command/useCommandItems.contacts.test.tsindex d90ab2fff6..7ea178c930 100644--- a/apps/web/src/features/command/useCommandItems.contacts.test.ts+++ b/apps/web/src/features/command/useCommandItems.contacts.test.ts@@ -43,6 +43,7 @@ vi.mock('@core/context/quickAccess', () => ({hasMore: () => false,isLoading: () => false,isLoadingMore: () => false,+ error: () => undefined,loadMore: async () => {},} satisfies QuickAccessList;},@@ -146,6 +147,7 @@ function setup(initialCategory: CategoryFilter = 'dms') {isLoading: loading,hasMore,isLoadingMore: () => false,+ error: () => undefined,loadMore: discovery.loadMore,};},diff --git a/apps/web/src/features/command/useCommandItems.test.ts b/apps/web/src/features/command/useCommandItems.test.tsindex 499bbcbc74..09ab083be6 100644--- a/apps/web/src/features/command/useCommandItems.test.ts+++ b/apps/web/src/features/command/useCommandItems.test.ts@@ -92,6 +92,7 @@ function setup() {totalCount: () => items().length,hasMore: () => false,isLoadingMore: () => false,+ error: () => undefined,loadMore: async () => {},};const result = useCommandItems(() => '', category, {diff --git a/apps/web/src/features/command/useCommandItems.ts b/apps/web/src/features/command/useCommandItems.tsindex 90587eba7b..92f4f3e4b4 100644--- a/apps/web/src/features/command/useCommandItems.ts+++ b/apps/web/src/features/command/useCommandItems.ts@@ -83,6 +83,7 @@ export type PaginationControls = {export type CommandContactSource = PaginationControls & {contacts: Accessor<CrmContactEntity[]>;isLoading: Accessor<boolean>;+ error: Accessor<Error | undefined>;};function isCommandItem(item: CommandMenuItem): item is CommandItem {diff --git a/apps/web/src/features/entity/composed/list-entity/shared.tsx b/apps/web/src/features/entity/composed/list-entity/shared.tsxindex 91f4fc53bd..89ec9e924a 100644--- a/apps/web/src/features/entity/composed/list-entity/shared.tsx+++ b/apps/web/src/features/entity/composed/list-entity/shared.tsx@@ -129,6 +129,8 @@ const ListLayoutContext = createContext<ListLayoutContextValue>();export function ListLayoutProvider(props: {ref: Accessor<HTMLElement | undefined>;narrowLayout?: NarrowLayoutVariant;+ /** Responsive rows have a nonzero width and their layout can be restored. */+ onMeasured?: () => void;children: JSX.Element;}) {const [isWide, setIsWide] = createSignal(true);@@ -137,7 +139,9 @@ export function ListLayoutProvider(props: {const el = props.ref();if (!el) return;const observer = new ResizeObserver((entries) => {- setIsWide((entries[0]?.contentRect.width ?? 0) >= WIDE_BREAKPOINT);+ const width = entries[0]?.contentRect.width ?? 0;+ setIsWide(width >= WIDE_BREAKPOINT);+ if (width > 0) props.onMeasured?.();});observer.observe(el);onCleanup(() => observer.disconnect());diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsxindex fda07f8bf5..040c370b88 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.test.tsx@@ -21,10 +21,12 @@ vi.mock('@channel/DebugSuspense', () => ({vi.mock('./QuickAccessSource', () => ({createQuickAccessValue: () => {const id = userId();+ const error = new Error(`Unavailable for ${id}`);mountSource(id);onCleanup(() => disposeSource(id));return {useList: () => ({+ error: () => error,items: () => [{ kind: 'user', id }],totalCount: () => 1,hasMore: () => true,@@ -52,12 +54,14 @@ it('keeps consumers mounted while creating and disposing account sources acrosslet mounted = 0;let refreshCurrent: () => void = () => {};let loadCurrent: () => Promise<void> = async () => {};+ let currentError: () => unknown = () => undefined;function Consumer() {mounted++;const access = useQuickAccess();const list = access.useList('person');refreshCurrent = access.refresh;loadCurrent = list.loadMore;+ currentError = list.error;return (<div>{list@@ -74,6 +78,7 @@ it('keeps consumers mounted while creating and disposing account sources across));expect(screen.getByText('No account data')).toBeTruthy();expect(mountSource).not.toHaveBeenCalled();+ expect(currentError()).toBeUndefined();refreshCurrent();await loadCurrent();expect(refresh).not.toHaveBeenCalled();@@ -84,6 +89,7 @@ it('keeps consumers mounted while creating and disposing account sources acrossexpect(mountSource).not.toHaveBeenCalled();setAuthenticated(true);expect(screen.getByText('alice')).toBeTruthy();+ expect(currentError()).toMatchObject({ message: 'Unavailable for alice' });refreshCurrent();await loadCurrent();expect(refresh).toHaveBeenCalledOnce();@@ -92,9 +98,11 @@ it('keeps consumers mounted while creating and disposing account sources acrosssetUserId('bob');expect(disposeSource).toHaveBeenCalledWith('alice');expect(screen.getByText('bob')).toBeTruthy();+ expect(currentError()).toMatchObject({ message: 'Unavailable for bob' });setAuthenticated(false);expect(disposeSource).toHaveBeenCalledWith('bob');expect(screen.getByText('No account data')).toBeTruthy();+ expect(currentError()).toBeUndefined();expect(mountSource).toHaveBeenCalledTimes(2);expect(mounted).toBe(1);});diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsxindex 9632d03a0e..b80df93802 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx@@ -32,6 +32,7 @@ const QuickAccessProviderValue: FlowComponent = (props) => {: current.useList(...(args as Bucket[]));});return {+ error: () => sourceList()?.error(),items: () => sourceList()?.items() ?? [],totalCount: () => sourceList()?.totalCount() ?? 0,hasMore: () => sourceList()?.hasMore() ?? false,diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsxindex aa039d93a5..a012bc70ab 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx@@ -1301,6 +1301,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {(cacheHost() ? cachedChannelsQuery.isLoading : channelsLoading())),isLoadingMore: () => projected?.isLoadingMore() ?? false,+ error: () => projected?.error(),loadMore: async () => {await projected?.loadMore();},diff --git a/apps/web/src/lib/core/context/quickAccess/projected-list.test.ts b/apps/web/src/lib/core/context/quickAccess/projected-list.test.tsindex b837b00d33..7af7f6b34a 100644--- a/apps/web/src/lib/core/context/quickAccess/projected-list.test.ts+++ b/apps/web/src/lib/core/context/quickAccess/projected-list.test.ts@@ -55,6 +55,48 @@ function deferred<T>() {}describe('Quick Access local projection', () => {+ it('distinguishes a failed initial read from a successful empty retry', async () => {+ const [revision, setRevision] = createSignal(0);+ const error = new Error('Cache unavailable');+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const search = vi+ .fn()+ .mockRejectedValueOnce(error)+ .mockResolvedValueOnce(page([]));+ const list = root(() =>+ createProjectedList({+ host: { search },+ buckets: ['note'],+ revision,+ materialize,+ })+ );+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));+ expect(list.error()).toBe(error);+ expect(list.items()).toEqual([]);+ expect(list.hasMore()).toBe(false);+ setRevision(1);+ expect(list.isLoading()).toBe(true);+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));+ expect(list.error()).toBeUndefined();+ expect(list.items()).toEqual([]);+ });++ it('reports an initial read as pending before mount effects start it', () => {+ const search = vi.fn().mockResolvedValue(page([]));+ root(() => {+ const list = createProjectedList({+ host: { search },+ buckets: ['note'],+ revision: () => 0,+ materialize,+ });+ // Consumers restore history from eager memos before createEffect runs.+ expect(list.isLoading()).toBe(true);+ expect(list.items()).toEqual([]);+ });+ });+it('retains matching rows until the next query commits, without retaining its cursor', async () => {const [query, setQuery] = createSignal('sea');const pending = deferred<SearchCachePage>();diff --git a/apps/web/src/lib/core/context/quickAccess/projected-list.ts b/apps/web/src/lib/core/context/quickAccess/projected-list.tsindex 6d0a703c17..c67945168c 100644--- a/apps/web/src/lib/core/context/quickAccess/projected-list.ts+++ b/apps/web/src/lib/core/context/quickAccess/projected-list.ts@@ -68,8 +68,11 @@ export function createProjectedList<T extends { id: string }>(options: {const [items, setItems] = createSignal<T[]>([]);const [hasMore, setHasMore] = createSignal(false);const [loading, setLoading] = createSignal<'idle' | 'initial' | 'more'>(- 'idle'+ untrack(() =>+ options.enabled?.() !== false && buckets().length > 0 ? 'initial' : 'idle'+ ));+ const [error, setError] = createSignal<unknown>();let current: Request | undefined;onCleanup(() => {current = undefined;@@ -158,11 +161,13 @@ export function createProjectedList<T extends { id: string }>(options: {);request.cursor = cursor;request.pages = pages;+ setError(undefined);setItems([...merged.values()]);setHasMore(cursor !== undefined);} catch (error) {span.error('Quick Access cache search failed');if (current !== request) return;+ setError(error);// Rows and their continuation are a committed window. A failed replay// (or append) must leave both intact so normal pagination can retry.// The mentions page loader guards automatic retries at the same frontier.@@ -200,6 +205,7 @@ export function createProjectedList<T extends { id: string }>(options: {// Genuine query/bucket changes, disabling, and disposal still fence off// obsolete responses and their queued refreshes.current = undefined;+ setError(undefined);setHasMore(false);const sameBuckets =previous?.buckets.length === activeBuckets.length &&@@ -228,6 +234,7 @@ export function createProjectedList<T extends { id: string }>(options: {return {items,+ error,hasMore,isLoading: () => loading() === 'initial',isLoadingMore: () => loading() === 'more',diff --git a/apps/web/src/lib/core/context/quickAccess/types.ts b/apps/web/src/lib/core/context/quickAccess/types.tsindex 05e5a36fa8..61c660d0b3 100644--- a/apps/web/src/lib/core/context/quickAccess/types.ts+++ b/apps/web/src/lib/core/context/quickAccess/types.ts@@ -174,6 +174,7 @@ export type QuickAccessList<T extends QuickAccessItem = QuickAccessItem> = {hasMore: Accessor<boolean>;isLoading: Accessor<boolean>;isLoadingMore: Accessor<boolean>;+ error: Accessor<unknown>;loadMore: () => Promise<void>;};diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.tsindex 92da421277..a27c86b309 100644--- a/apps/web/src/routes/routes.ts+++ b/apps/web/src/routes/routes.ts@@ -9,6 +9,7 @@ import {} from '@app/features/calendar-view/calendar-url';import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';import { changesSearch } from '@app/features/changes/changes-search';+import { mobileSearchRouteStateSchema } from '@app/features/command/mobile/mobile-search-route-state';import { crmViewReference } from '@app/features/crm/crm-route';import { driveDetailTrailSchema } from '@app/features/drive-view/primitives/drive-detail-trail';import {@@ -634,7 +635,10 @@ export const searchRoute = defineRoute({id: 'view-search',path: 'search',search: '*' as const,+ state: mobileSearchRouteStateSchema,claim: () => ({ namespace: 'component', id: 'search' }),+ // Each visit owns its query and result scroll state, even in a reused pane.+ remountKey: (_params, { entryId }) => entryId,});export const prDetailRoute = defineRoute({diff --git a/docs/agent-guide/search.md b/docs/agent-guide/search.mdindex 5531fba2d3..b459e52018 100644--- a/docs/agent-guide/search.md+++ b/docs/agent-guide/search.md@@ -34,15 +34,53 @@ the build-time `VITE_ENABLE_GRAPHQL_SOUP=true` override; see the[cache guide](../../apps/web/docs/graphql-normalized-cache-plan.md#cached-email-quick-access).Category/mode changes keep the same input mounted and focused. Enter dismisses-the keyboard without ending search. Opening a result or **Close search** ends the-session; reopening starts in All/name mode. Mobile query/category state is transient-and does not modify desktop search state. The dock search row has no Ask AI button.+the keyboard without ending search. Opening a result hides search chrome while+preserving that Search history entry's query, category, mode, result order, and+scroll position. Opening a result does not promote it within that saved list,+even when its last-viewed time changes. Swiping back, pressing the native Back control, or using browser Back+returns to those results without focusing the input or reopening the keyboard.+Native search captures its state when covered: it retains mounted results while+it is among the front two panes, and restores them after deeper navigation evicts+it. A remounted history entry immediately restores its loaded results,+virtualizer measurements and offset (or the full-text scroller's offset).+Refreshing sources rebuild the loaded window and update matching rows in place;+new pages append without reordering saved rows. A saved row missing from an+incomplete source page remains until it is found or pagination exhausts.+Changing the query/category or starting a new dock search computes a fresh order.+Native dock searches carry a new session ID in Search's route state; returning+through history retains the earlier ID and its saved window without changing the URL.+Saved rows and scroll measurements belong to their account; switching accounts+resets the result sources and scrollers and cannot restore another account's window.+Available results show no loading footer. Failed background reads retain the window;+successful empty results replace it, and authoritative errors discard the saved+window in favor of the current source result. A later search+cannot overwrite an earlier entry. **Close search** ends the+session; opening Search from the dock starts in All/name mode. Mobile search state+does not modify desktop search state. The dock search row has no Ask AI button.If a person’s conversation lookup fails, search stays open with its query andcategory intact so the result can be retried.Verify sender-only `teo` matches with one- and two-character prefixes, then switch-categories with the keyboard up. Select full text, edit the query, open a snippet,-reopen search, and check All/name reset. Clear with whitespace and check category+categories with the keyboard up. In both name and full-text modes, scroll several+pages, open a result/snippet, and go Back: check the query, category, mode, visible+rows, and scroll position. Repeat Back/Forward and native swipe/Back; the keyboard+stays dismissed on return. Open Search from the dock and check All/name reset,+then revisit the earlier history entry and confirm its query is intact.+Open a result from midway through the list and confirm it keeps its original+position after Back, both when Search stays mounted and after deeper navigation+evicts it. Refresh row metadata and append pages; existing rows must keep their order.+Switch accounts with a scrolled Search entry still mounted, then remount that+entry: neither path should retain the previous account's rows or scroll offset.+Repeat with a slow refresh: the saved rows and scroll should appear before it+finishes, and its first page must not shrink a previously paginated list.+If the viewport changes on return, scroll manually and confirm+later pages preserve that new position instead of returning to the saved offset.+In full-text mode, repeat Back several times from deep in a long result list;+browser scroll anchoring must not move the viewport after the saved offset is+restored. Restoration waits for responsive row measurement so the temporary wide+layout cannot clamp a deep mobile offset. Check the same row remains at the same+position while results reconcile, including the first return after a fresh search.+Clear with whitespace and check categoryretention; select Projects from full-text mode and confirm it shows name results.Repeat opening with a large recent list: results are virtualized, so transferringkeyboard focus should not mount every cached row. Scroll through later results