Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(search): keep result rows out of navigation history (#8554)

Peter Chinmanf69a2302a635
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index ffc3db6675..314645c6c4 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -118,11 +118,12 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.
- Share sidebar and mobile dock unread presence through `components/app/use-navigation-unread.ts`; keep badges reactive to read/done changes, guard all query data with `queryReadyGate` so pending preferences or paused queries cannot suspend the shell, and avoid fetching extra pages for counts.
- 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.
- Include known Macro users in typed All/People name searches without requiring a DM or CRM contact; resolve a matching person to their existing one-to-one DM while preserving name/email matching.
-- 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.
+- Key mobile name-result history ordering and scroll anchors by the other participant for one-to-one DMs, preserving a person's position when their conversation is created; keep group DMs keyed by channel.
+- Keep mobile Search history lightweight: save query/category/mode, account-scoped item anchors, and at most 200 ordering IDs per mode; never save row objects or virtualizer caches. Restore from current sources with at most three additional pages, fall back when an anchor disappears, and stop restoration on user interaction or scope changes. Dock navigation starts a fresh search session; cached rows belong to the source, not history.
- Release saved entry state when its router entry is replaced, pruned, or closed; retain only the latest split event so obsolete payloads cannot keep result lists alive. Preserve snapshots for entries still reachable through Back/Forward.
- 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; restore after responsive row measurement and disable browser scroll anchoring so layout changes cannot override the saved history offset.
+- Reconcile mobile full-text rows by entity ID so appending a page preserves DOM rows and scroll position; restore item anchors after responsive row measurement and disable browser scroll anchoring so layout changes cannot override restoration.
- Reserve the safe area plus the category row above mobile Search, and only the safe area above Channels; their hidden split headers must not add another blank strip.
- Follow [mobile layout and chrome](../../.agents/rules/web/mobile.md#layout-and-chrome) for full-frame views and record tabs; verify their first controls below the navigation with a nonzero safe area on phones and tablets.
- Keep split chrome portal targets reactive so cached views can mount before their header, and clear a retiring header's targets only while it still owns them.
diff --git a/apps/web/src/features/command/contact-items.ts b/apps/web/src/features/command/contact-items.ts
index 30c1c0ff80..8ed2596ef1 100644
--- a/apps/web/src/features/command/contact-items.ts
+++ b/apps/web/src/features/command/contact-items.ts
@@ -10,6 +10,26 @@ import {
import type { CrmContactEntity } from '@entity';
import type { CommandMenuItem } from './useCommandItems';
+function directMessageRecipient(
+ item: CommandMenuItem,
+ viewerId: string | undefined
+) {
+ if (item.kind !== 'entity' || item.data.type !== 'channel') return;
+ if (item.data.channelType !== 'direct_message') return;
+ const others = (item.data.participantIds ?? []).filter(
+ (id) => id !== viewerId
+ );
+ return others.length === 1 ? others[0] : undefined;
+}
+
+/** A person keeps their search position when opening them creates a DM. */
+export function commandSearchResultKey(
+ item: CommandMenuItem,
+ viewerId: string | undefined
+): string {
+ return directMessageRecipient(item, viewerId) ?? item.id;
+}
+
function directMessagesByUser(
directMessages: readonly QuickAccessItem[],
viewerId: string | undefined
@@ -17,11 +37,8 @@ function directMessagesByUser(
const byUser = new Map<string, EntityItem>();
for (const item of directMessages) {
if (item.kind !== 'entity' || item.data.type !== 'channel') continue;
- if (item.data.channelType !== 'direct_message') continue;
- const others = (item.data.participantIds ?? []).filter(
- (id) => id !== viewerId
- );
- if (others.length === 1) byUser.set(others[0], item);
+ const recipient = directMessageRecipient(item, viewerId);
+ if (recipient) byUser.set(recipient, item);
}
return byUser;
}
diff --git a/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx b/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx
index 0904b6ab5f..4ab0582ff7 100644
--- a/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx
+++ b/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx
@@ -1,4 +1,5 @@
import type { EntryState } from '@components/app/split-layout/layoutManager';
+import type { EntityItem, UserItem } from '@core/context/quickAccess';
import type { EntityData, SearchLocation } from '@entity';
import {
cleanup,
@@ -11,6 +12,7 @@ import {
import { CombinedError } from '@urql/core';
import { type Accessor, createSignal, onMount, Show } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { mergeCommandPeople } from '../contact-items';
import type { EntitySearchItem } from '../queries/entity-search';
import { MobileSearchInput } from './MobileSearchInput';
import { MobileSearchResults } from './MobileSearchResults';
@@ -127,19 +129,22 @@ vi.mock('@entity', () => ({
},
ListEntity: (props: {
entity: EntityData;
+ ref?: (element: HTMLDivElement) => void;
onContentHitClick: (event: MouseEvent, location: SearchLocation) => void;
}) => (
- <button
- type="button"
- onClick={(event) =>
- props.onContentHitClick(event, {
- type: 'email',
- messageId: 'matching-message',
- })
- }
- >
- {props.entity.name} snippet
- </button>
+ <div ref={props.ref}>
+ <button
+ type="button"
+ onClick={(event) =>
+ props.onContentHitClick(event, {
+ type: 'email',
+ messageId: 'matching-message',
+ })
+ }
+ >
+ {props.entity.name} snippet
+ </button>
+ </div>
),
}));
vi.mock('../queries/entity-search', () => ({
@@ -452,21 +457,18 @@ it('restores full-text order, query, category, mode and scroll after measuring r
expect(document.activeElement).not.toBe(input);
expect(SearchState.category()).toBe('email');
expect(SearchState.mode()).toBe('full-text');
- expect(screen.queryByText('Searching…')).toBeNull();
+ expect(screen.getByText('Searching…')).toBeTruthy();
expect(
- screen.getByRole('button', { name: 'Weekly update snippet' })
- ).toBeTruthy();
- expect(screen.getByRole('region', { name: 'Search results' }).scrollTop).toBe(
- 0
- );
+ screen.queryByRole('button', { name: 'Weekly update snippet' })
+ ).toBeNull();
mocks.measureLayout();
+ setItems([email, other]);
+ setSettling(false);
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')
@@ -560,23 +562,116 @@ it('restores the name list order and scroll after opening promotes a result by r
expect(screen.getAllByRole('button').map((row) => row.textContent)).toEqual(
visibleResults
);
+ expect(mocks.entryState?.['mobileSearch.nameScroll']).toMatchObject({
+ offset: 800,
+ });
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
+ const restoredList = screen.getByRole('region', { name: 'Search results' });
+ await waitFor(() => expect(restoredList.scrollTop).toBe(800));
+ fireEvent.scroll(restoredList);
+ expect(screen.getByRole('button', { name: 'Project 2' })).toBeTruthy();
+ expect(mocks.entryState?.['mobileSearch.nameOrder']).toMatchObject({
+ ids: originalItems.map((item) => item.id),
+ });
+ expect(mocks.entryState?.['mobileSearch.nameScroll']).not.toHaveProperty(
+ 'cache'
);
});
-it('restores loaded name pages and scroll before refresh resolves, without a loading footer', async () => {
+it.each(['before navigation', 'while away'])(
+ 'keeps a person in place when their DM arrives %s',
+ async (arrival) => {
+ mocks.hasMore = false;
+ const people: UserItem[] = Array.from({ length: 100 }, (_, index) => ({
+ id: `macro|person-${index}@example.com`,
+ kind: 'user',
+ bucket: 'person',
+ searchText: `Person ${index}`,
+ sortTimestamp: 0,
+ timestamps: {},
+ data: {
+ id: `macro|person-${index}@example.com`,
+ email: `person-${index}@example.com`,
+ name: `Person ${index}`,
+ },
+ }));
+ const [conversations, setConversations] = createSignal<EntityItem[]>([]);
+ // Exercise the real person-to-conversation composition. A new DM is also
+ // promoted by recency, so its raw channel ID no longer occupies the old slot.
+ mocks.items = () =>
+ mergeCommandPeople(
+ [...conversations(), ...people],
+ conversations(),
+ 'owner'
+ );
+ const publishConversation = () => {
+ setConversations([
+ {
+ id: 'new-dm',
+ kind: 'entity',
+ bucket: 'dm',
+ searchText: 'Person 2',
+ sortTimestamp: Date.now(),
+ timestamps: {},
+ data: {
+ id: 'new-dm',
+ type: 'channel',
+ name: 'Person 2',
+ ownerId: 'owner',
+ channelType: 'direct_message',
+ participantIds: ['owner', people[2].id],
+ },
+ },
+ ]);
+ };
+ mocks.directMessage.mockImplementation(async () => {
+ if (arrival === 'before navigation') publishConversation();
+ return { channel_id: 'new-dm' };
+ });
+ SearchState.setQuery('Person');
+ const view = render(() => <MobileSearchResults />);
+ const list = screen.getByRole('region', { name: 'Search results' });
+ fireEvent.scroll(list, { target: { scrollTop: 800 } });
+ const visiblePeople = () =>
+ within(screen.getByRole('region', { name: 'Search results' }))
+ .getAllByRole('button')
+ .map((row) => row.textContent?.match(/Person \d+/)?.[0]);
+ const before = visiblePeople();
+ fireEvent.click(screen.getByRole('button', { name: 'Person 2' }));
+ await waitFor(() => expect(mocks.open).toHaveBeenCalled());
+ mocks.setActive(true);
+ expect(visiblePeople()).toEqual(before);
+ expect(list.scrollTop).toBe(800);
+
+ view.unmount();
+ if (arrival === 'while away') publishConversation();
+ mocks.setActive(true);
+ render(() => <MobileSearchResults />);
+ const restored = screen.getByRole('region', { name: 'Search results' });
+ await waitFor(() => expect(restored.scrollTop).toBe(800));
+ fireEvent.scroll(restored);
+ // Remounting can add an overscan row above the viewport.
+ expect(visiblePeople()).toEqual(expect.arrayContaining(before));
+ expect(visiblePeople().indexOf('Person 3')).toBe(
+ visiblePeople().indexOf('Person 2') + 1
+ );
+ const person = within(restored).getByRole('button', { name: /Person 2$/ });
+ fireEvent.click(person);
+ await waitFor(() =>
+ expect(mocks.open).toHaveBeenLastCalledWith(
+ expect.objectContaining({ id: 'new-dm', type: 'channel' }),
+ expect.anything()
+ )
+ );
+ expect(mocks.directMessage).toHaveBeenCalledOnce();
+ }
+);
+
+it('reloads name rows on remount instead of storing them in history', async () => {
const savedItems: EntitySearchItem[] = Array.from(
{ length: 100 },
(_, index) => ({
@@ -604,43 +699,28 @@ it('restores loaded name pages and scroll before refresh resolves, without a loa
'button'
)[0]
);
+ expect(mocks.entryState?.['mobileSearch.nameOrder']).toEqual({
+ accountId: 'owner',
+ query: 'Project',
+ category: 'projects',
+ ids: savedItems.map((item) => item.id),
+ });
+ expect(mocks.entryState?.['mobileSearch.nameScroll']).not.toHaveProperty(
+ 'cache'
+ );
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));
+ expect(screen.queryByRole('button', { name: 'Project 2' })).toBeNull();
+ expect(SearchState.query()).toBe('Project');
+ setItems(savedItems);
setLoading(false);
- expect(screen.queryByText('Loading…')).toBeNull();
+ const restoredList = screen.getByRole('region', { name: 'Search results' });
+ await waitFor(() => expect(restoredList.scrollTop).toBe(800));
+ fireEvent.scroll(restoredList);
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', () => {
@@ -733,7 +813,9 @@ it.each(['name', 'full-text'] as const)(
mocks.setActive(true);
render(() => <MobileSearchResults />);
const list = screen.getByRole('region', { name: 'Search results' });
- await waitFor(() => expect(list.scrollTop).toBe(300));
+ if (mode === 'full-text')
+ await waitFor(() => expect(list.scrollTop).toBe(300));
+ fireEvent.wheel(list);
// Simulate the browser clamping the initial offset to the new scroll range.
fireEvent.scroll(list, { target: { scrollTop: 200 } });
fireEvent.scroll(list, { target: { scrollTop: 100 } });
@@ -782,7 +864,7 @@ it.each(['name', 'full-text'] as const)(
}
);
-it('keeps restored name results after a failed refresh but accepts a successful empty result', () => {
+it('does not revive saved name rows after a failed refresh or successful empty result', () => {
const [items, setItems] = createSignal<EntitySearchItem[]>([
{
id: 'project',
@@ -811,8 +893,7 @@ it('keeps restored name results after a failed refresh but accepts a successful
render(() => <MobileSearchResults />);
setFailed(true);
setLoading(false);
- expect(screen.getByRole('button', { name: 'Project' })).toBeTruthy();
- expect(screen.queryByText('Loading…')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Project' })).toBeNull();
expect(mocks.loadMore).not.toHaveBeenCalled();
setLoading(true);
setFailed(false);
@@ -985,7 +1066,7 @@ it('fills empty full-text pages until pagination is exhausted', async () => {
await waitFor(() => expect(mocks.fetchNextPage).toHaveBeenCalledTimes(2));
});
-it('keeps full-text rows mounted during same-query refreshes but clears them for a new query', () => {
+it('uses current source rows during refresh and keeps row identity when pages append', () => {
const email: EntityData = {
id: 'thread',
type: 'email',
@@ -1007,25 +1088,23 @@ it('keeps full-text rows mounted during same-query refreshes but clears them for
SearchState.setQuery('teo');
SearchState.searchFullText();
render(() => <MobileSearchResults />);
- const row = screen.getByRole('button', { name: 'Weekly update snippet' });
setLoading(true);
setItems([]);
- expect(screen.getByRole('button', { name: 'Weekly update snippet' })).toBe(
- row
- );
- expect(screen.queryByText('Searching…')).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'Weekly update snippet' })
+ ).toBeNull();
setItems([email]);
setLoading(false);
- expect(screen.getByRole('button', { name: 'Weekly update snippet' })).toBe(
- row
- );
+ const refreshedRow = screen.getByRole('button', {
+ name: 'Weekly update snippet',
+ });
// Service page selection rematerializes existing entities when it appends.
setItems([
{ ...email, name: 'Updated subject' },
{ ...email, id: 'next', name: 'Next page' },
]);
expect(screen.getByRole('button', { name: 'Updated subject snippet' })).toBe(
- row
+ refreshedRow
);
expect(
screen.getByRole('button', { name: 'Next page snippet' })
@@ -1037,3 +1116,79 @@ it('keeps full-text rows mounted during same-query refreshes but clears them for
screen.queryByRole('button', { name: 'Updated subject snippet' })
).toBeNull();
});
+
+it('keeps a full-text top-of-list anchor below the mobile safe-area padding', async () => {
+ mocks.fullTextItems = [
+ {
+ id: 'first',
+ type: 'email',
+ name: 'First',
+ ownerId: 'owner',
+ isRead: true,
+ isDraft: false,
+ isImportant: false,
+ done: false,
+ },
+ ];
+ mocks.hasMore = false;
+ SearchState.setQuery('First');
+ SearchState.searchFullText();
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
+ function (this: HTMLElement) {
+ return new DOMRect(0, this.dataset.mobileSearchId ? 80 : 0, 390, 64);
+ }
+ );
+ const view = render(() => <MobileSearchResults />);
+ fireEvent.click(screen.getByRole('button', { name: 'First snippet' }));
+ expect(mocks.entryState?.['mobileSearch.fullTextScroll']).toMatchObject({
+ id: 'first',
+ offset: 0,
+ within: -80,
+ });
+ view.unmount();
+ mocks.setActive(true);
+ render(() => <MobileSearchResults />);
+ await waitFor(() =>
+ expect(
+ screen.getByRole('region', { name: 'Search results' }).scrollTop
+ ).toBe(0)
+ );
+ await Promise.resolve();
+ expect(screen.getByRole('region', { name: 'Search results' }).scrollTop).toBe(
+ 0
+ );
+});
+
+it('resumes viewport paging when editing a restored search in the dock', async () => {
+ mocks.items = () => [
+ {
+ id: 'first',
+ kind: 'initiative',
+ bucket: 'initiative',
+ name: 'First',
+ searchText: 'First',
+ sortTimestamp: 0,
+ timestamps: {},
+ },
+ ];
+ mocks.entryState = {
+ 'mobileSearch.session': {
+ query: 'First',
+ category: 'projects',
+ mode: 'name',
+ },
+ 'mobileSearch.nameScroll': {
+ accountId: 'owner',
+ query: 'First',
+ category: 'projects',
+ id: 'first',
+ offset: 0,
+ within: 0,
+ },
+ };
+ render(() => <MobileSearchResults />);
+ await Promise.resolve();
+ expect(mocks.loadMore).not.toHaveBeenCalled();
+ SearchState.setQuery('Next');
+ await waitFor(() => expect(mocks.loadMore).toHaveBeenCalledOnce());
+});
diff --git a/apps/web/src/features/command/mobile/MobileSearchResults.tsx b/apps/web/src/features/command/mobile/MobileSearchResults.tsx
index e08ee0e555..4ff5491e04 100644
--- a/apps/web/src/features/command/mobile/MobileSearchResults.tsx
+++ b/apps/web/src/features/command/mobile/MobileSearchResults.tsx
@@ -4,7 +4,6 @@ import { projectRouteId } from '@app/features/projects/core/route';
import { createSoupRowStore } from '@app/features/soup/collection/row-store';
import { MobileTopEdgeFade } from '@components/app/mobile/MobileEdgeFade';
import { MobileViewsRow } from '@components/app/mobile/MobileViewsRow';
-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';
@@ -23,20 +22,11 @@ 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 {
- createEffect,
- createMemo,
- createSignal,
- For,
- on,
- Show,
- Suspense,
- untrack,
-} from 'solid-js';
+import { createMemo, createSignal, For, Show, Suspense } from 'solid-js';
import { type VirtualizerHandle, VList } from 'virtua/solid';
import { ItemDisplay } from '../CommandItem';
+import { commandSearchResultKey } from '../contact-items';
import {
- type EntitySearchCategory,
type EntitySearchItem,
useEntitySearch,
} from '../queries/entity-search';
@@ -44,17 +34,10 @@ import { createMobileFullTextSearch } from '../queries/mobile-full-text-search';
import { createMobileSearchEntry } from './create-mobile-search-entry';
import { createSearchPagination } from './create-search-pagination';
import { createSearchResultWindow } from './create-search-result-window';
+import { createSearchScrollRestoration } from './create-search-scroll-restoration';
import type { MobileSearchSession } from './mobileSearchState';
import { useMobileSearchCategory } from './use-mobile-search-category';
-type SearchScrollState = {
- accountId: string;
- query: string;
- category: EntitySearchCategory;
- offset: number;
- cache?: VirtualizerHandle['cache'];
-};
-
function MobileNameResults(props: {
session: MobileSearchSession;
accountId: string;
@@ -63,17 +46,6 @@ function MobileNameResults(props: {
const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();
const [container, setContainer] = createSignal<HTMLDivElement>();
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,
@@ -82,26 +54,60 @@ function MobileNameResults(props: {
const incoming = createMemo(() =>
source.rankItems(source.items(), state.query())
);
+ const itemKey = (item: EntitySearchItem) =>
+ commandSearchResultKey(item, props.accountId);
const results = createSearchResultWindow({
- key: 'mobileSearch.nameResults',
+ key: 'mobileSearch.nameOrder',
accountId: () => props.accountId,
query: state.query,
category,
items: incoming,
- pending: () =>
- source.isSettling() ||
- source.pagination.isLoadingMore() ||
- source.hasError(),
+ itemKey,
discard: source.hasAuthoritativeError,
- hasMore: source.pagination.hasMore,
});
const items = results.items;
+ const restoration = createSearchScrollRestoration({
+ key: 'mobileSearch.nameScroll',
+ accountId: () => props.accountId,
+ query: state.query,
+ category,
+ items,
+ ready: () => !!virtualizer() || items().length === 0,
+ busy: () => source.isSettling() || source.pagination.isLoadingMore(),
+ failed: source.hasError,
+ hasMore: source.pagination.hasMore,
+ loadMore: source.pagination.loadMore,
+ read: () => {
+ const handle = virtualizer();
+ const offset = handle?.scrollOffset ?? 0;
+ const index = handle?.findItemIndex(offset) ?? 0;
+ const item = items()[index];
+ return {
+ id: item ? itemKey(item) : undefined,
+ offset,
+ within: offset - (handle?.getItemOffset(index) ?? 0),
+ };
+ },
+ apply: (anchor) => {
+ const handle = virtualizer();
+ if (!handle) return !anchor.id && items().length === 0;
+ if (!anchor.id) {
+ handle.scrollTo(anchor.offset);
+ return true;
+ }
+ const index = items().findIndex((item) => itemKey(item) === anchor.id);
+ if (index < 0) return false;
+ handle.scrollToIndex(index, { align: 'start', offset: anchor.within });
+ return true;
+ },
+ });
const loadMoreNearEnd = createSearchPagination({
items: incoming,
+ enabled: restoration.paginationAllowed,
container,
remaining: () => {
const handle = virtualizer();
- return results.needsMore() || items().length === 0
+ return items().length === 0
? 0
: handle
? handle.scrollSize - handle.scrollOffset - handle.viewportSize
@@ -141,32 +147,6 @@ function MobileNameResults(props: {
}
});
};
- 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 {
@@ -178,6 +158,9 @@ function MobileNameResults(props: {
return (
<div
ref={setContainer}
+ onWheel={restoration.cancel}
+ onTouchStart={restoration.cancel}
+ onPointerDown={restoration.cancel}
class="flex h-full min-h-0 flex-col px-3 touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)"
>
<Show when={state.query().trim() && category() !== 'projects'}>
@@ -197,11 +180,10 @@ function MobileNameResults(props: {
<VList
ref={setVirtualizer}
data={items()}
- cache={restore?.cache}
role="region"
aria-label="Search results"
class="min-h-0 flex-1 overscroll-none"
- onScroll={onScroll}
+ onScroll={loadMoreNearEnd}
>
{(item) => (
<CommandMenuListItem
@@ -237,63 +219,63 @@ function MobileFullTextResults(props: {
const panel = useSplitPanelOrThrow();
const [container, setContainer] = createSignal<HTMLDivElement>();
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',
+ key: 'mobileSearch.fullTextOrder',
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);
- let restoreQueued = false;
- createEffect(
- on([results.items, container, layoutReady, hasAuthoritativeError], () => {
- if (hasAuthoritativeError()) restore = undefined;
+ const restoration = createSearchScrollRestoration({
+ key: 'mobileSearch.fullTextScroll',
+ accountId: () => props.accountId,
+ query: state.query,
+ category,
+ items: results.items,
+ ready: layoutReady,
+ busy: () => search.isSettling() || search.isFetchingNextPage(),
+ failed: () => !!search.error(),
+ hasMore: search.hasNextPage,
+ loadMore: search.fetchNextPage,
+ read: () => {
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 top = list?.getBoundingClientRect().top ?? 0;
+ const row = Array.from(
+ list?.querySelectorAll<HTMLElement>('[data-mobile-search-id]') ?? []
+ ).find((element) => element.getBoundingClientRect().bottom > top);
+ return {
+ id: row?.dataset.mobileSearchId,
+ offset: list?.scrollTop ?? 0,
+ within: row ? top - row.getBoundingClientRect().top : 0,
+ };
+ },
+ apply: (anchor) => {
+ const list = container();
+ if (!list) return false;
+ if (!anchor.id) {
+ list.scrollTop = anchor.offset;
+ return true;
+ }
+ const row = Array.from(
+ list.querySelectorAll<HTMLElement>('[data-mobile-search-id]')
+ ).find((element) => element.dataset.mobileSearchId === anchor.id);
+ if (!row) return false;
+ list.scrollTop +=
+ row.getBoundingClientRect().top -
+ list.getBoundingClientRect().top +
+ anchor.within;
+ return true;
+ },
+ });
const loadMoreNearEnd = createSearchPagination({
items: incoming,
+ enabled: restoration.paginationAllowed,
container,
remaining: () => {
- if (results.needsMore()) return 0;
const list = container();
return list
? list.scrollHeight - list.scrollTop - list.clientHeight
@@ -325,16 +307,10 @@ function MobileFullTextResults(props: {
ref={setContainer}
role="region"
aria-label="Search results"
- onScroll={(event) => {
- if (!restore)
- setScroll({
- accountId: props.accountId,
- query: state.query(),
- category: category(),
- offset: event.currentTarget.scrollTop,
- });
- loadMoreNearEnd();
- }}
+ onScroll={loadMoreNearEnd}
+ onWheel={restoration.cancel}
+ onTouchStart={restoration.cancel}
+ onPointerDown={restoration.cancel}
class="soup-list h-full overflow-y-auto overscroll-none [overflow-anchor:none] touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)"
>
<ListEntityMetadataQueryProvider>
@@ -347,6 +323,9 @@ function MobileFullTextResults(props: {
{(entity) => (
<ListEntity
entity={entity}
+ ref={(element) => {
+ element.dataset.mobileSearchId = entity.id;
+ }}
hideCheckbox
hideContentHits={false}
onClick={() => fireAndForget(open(entity), 'mobile-search')}
diff --git a/apps/web/src/features/command/mobile/create-search-pagination.ts b/apps/web/src/features/command/mobile/create-search-pagination.ts
index 6e04a8e9b4..5d9b4410cc 100644
--- a/apps/web/src/features/command/mobile/create-search-pagination.ts
+++ b/apps/web/src/features/command/mobile/create-search-pagination.ts
@@ -7,6 +7,7 @@ export function createSearchPagination<T>(options: {
items: Accessor<readonly T[]>;
container: Accessor<HTMLElement | undefined>;
remaining: Accessor<number | undefined>;
+ enabled: Accessor<boolean>;
hasMore: Accessor<boolean>;
busy: Accessor<boolean>;
loadMore: () => Promise<unknown>;
@@ -19,7 +20,8 @@ export function createSearchPagination<T>(options: {
});
const loadNearEnd = (automatic = false) => {
- if (disposed || !options.hasMore() || options.busy()) return;
+ if (disposed || !options.enabled() || !options.hasMore() || options.busy())
+ return;
const remaining = options.remaining();
if (remaining === undefined || remaining > 44 * 3) return;
const page = options.items();
@@ -40,7 +42,10 @@ export function createSearchPagination<T>(options: {
};
createResizeObserver(options.container, scheduleCheck);
createEffect(
- on([options.items, options.hasMore, options.busy], scheduleCheck)
+ on(
+ [options.items, options.hasMore, options.busy, options.enabled],
+ scheduleCheck
+ )
);
return () => loadNearEnd();
}
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.ts
index 20c361500f..0138d93d39 100644
--- 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.ts
@@ -35,10 +35,7 @@ afterEach(() => {
for (const dispose of cleanups.splice(0)) dispose();
});
-function setup(
- items: Row[],
- initial: { accountId?: string; hasMore?: boolean; pending?: boolean } = {}
-) {
+function setup(items: Row[], initial: { accountId?: string } = {}) {
return createRoot((dispose) => {
cleanups.push(dispose);
const [accountId, setAccountId] = createSignal(
@@ -47,8 +44,6 @@ function setup(
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',
@@ -56,8 +51,6 @@ function setup(
query,
category,
items: incoming,
- pending,
- hasMore,
discard,
});
return {
@@ -67,8 +60,6 @@ function setup(
setQuery,
setCategory,
setItems,
- setPending,
- setHasMore,
setDiscard,
};
});
@@ -89,41 +80,41 @@ it('ranks live until opening, then updates rows in place and appends later resul
expect(results.items()).toEqual([updated, original[0], added]);
});
-it('restores saved order while rebuilding a shorter first page and paging further', () => {
+it('saves only bounded IDs and restores order using current source rows', () => {
const first = setup(original);
- first.results.preserveOrder();
history.state = Object.fromEntries(
[...history.captors].map(([key, read]) => [key, read()])
);
+ expect(history.state).toEqual({
+ results: {
+ accountId: 'alice',
+ query: 'notes',
+ category: 'all',
+ ids: ['a', 'b', 'c'],
+ },
+ });
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]);
+ const updated = { id: 'c', name: 'Current third' };
+ const second = setup([updated]);
+ expect(second.results.items()).toEqual([updated]);
+ second.setItems([updated, original[1], original[0]]);
+ expect(second.results.items()).toEqual([original[0], original[1], updated]);
+ second.setItems([]);
+ expect(second.results.items()).toEqual([]);
});
-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('bounds saved ordering hints even after loading a large search', () => {
+ const rows = Array.from({ length: 1000 }, (_, i) => ({
+ id: `row-${i}`,
+ name: 'Large payload',
+ }));
+ setup(rows);
+ expect(history.captors.get('results')?.()).toEqual({
+ accountId: 'alice',
+ query: 'notes',
+ category: 'all',
+ ids: rows.slice(0, 200).map((row) => row.id),
+ });
});
it('preserves the mounted list when history is captured outside a result opener', () => {
@@ -135,25 +126,6 @@ it('preserves the mounted list when history is captured outside a result opener'
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();
@@ -178,42 +150,32 @@ it('ranks new queries and categories afresh, including revisiting an earlier que
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);
+it('uses current rows after authoritative failure and successful empty results', () => {
+ const { results, setItems, setDiscard } = setup(original);
results.preserveOrder();
batch(() => {
- setPending(true);
- setHasMore(true);
setItems([original[2]]);
});
- expect(results.items()).toEqual(original);
+ expect(results.items()).toEqual([original[2]]);
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);
+ const { results, setAccountId, setItems } = 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]]);
});
@@ -224,16 +186,12 @@ it('ignores another account snapshot when remounting a history entry', () => {
[...history.captors].map(([key, read]) => [key, read()])
);
first.dispose();
- const { results, setItems, setPending } = setup([], {
+ const { results, setItems } = 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.ts
index 611b8c168f..c33c0f4534 100644
--- a/apps/web/src/features/command/mobile/create-search-result-window.ts
+++ b/apps/web/src/features/command/mobile/create-search-result-window.ts
@@ -8,109 +8,71 @@ import {
} from 'solid-js';
import type { EntitySearchCategory } from '../queries/entity-search';
-type SearchResultWindow<T> = {
+// History remembers a small ordering hint; the source owns all row objects.
+const MAX_SAVED_RESULT_IDS = 200;
+type SearchResultOrder = {
accountId: string;
query: string;
category: EntitySearchCategory;
- items: T[];
- /** Live rows already loaded; retained rows may also belong to later pages. */
- sourceSize: number;
+ ids: string[];
};
-/** 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>;
+ itemKey?: (item: T) => string;
discard: Accessor<boolean>;
- hasMore: Accessor<boolean>;
}) {
const { handle } = useSplitPanelOrThrow();
+ const itemKey = options.itemKey ?? ((item: T) => item.id);
const stored = untrack(() => handle.currentEntryState()?.[options.key]) as
- | SearchResultWindow<T>
+ | SearchResultOrder
| undefined;
const scope = createMemo(() => ({
accountId: options.accountId(),
query: options.query(),
category: options.category(),
}));
- const [preservedScope, setPreservedScope] = createSignal(
+ const [order, setOrder] = createSignal(
untrack(() => {
- const initial = scope();
- return stored?.accountId === initial.accountId &&
- stored.query === initial.query &&
- stored.category === initial.category
- ? initial
+ const current = scope();
+ return stored?.accountId === current.accountId &&
+ stored.query === current.query &&
+ stored.category === current.category
+ ? { scope: current, ids: stored.ids }
: 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 items = createMemo(() => {
+ const current = scope();
+ const saved = order();
+ const incoming = options.items();
+ if (options.discard() || !saved || saved.scope !== current) return incoming;
+ const remaining = new Map(incoming.map((item) => [itemKey(item), item]));
+ const ordered: T[] = [];
+ for (const id of saved.ids) {
+ const item = remaining.get(id);
+ if (!item) continue;
+ ordered.push(item);
+ remaining.delete(id);
}
- );
- const preserveOrder = () => setPreservedScope(scope());
+ return [...ordered, ...remaining.values()];
+ });
+ const preserveOrder = () =>
+ setOrder({
+ scope: scope(),
+ ids: items().slice(0, MAX_SAVED_RESULT_IDS).map(itemKey),
+ });
onCleanup(
handle.registerEntryStateCaptor(options.key, () => {
preserveOrder();
- return window();
+ // Never return row objects, source callbacks, or virtualizer caches.
+ const saved = order();
+ return saved ? { ...saved.scope, ids: saved.ids } : undefined;
})
);
- 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,
- };
+ return { items, preserveOrder };
}
diff --git a/apps/web/src/features/command/mobile/create-search-scroll-restoration.test.ts b/apps/web/src/features/command/mobile/create-search-scroll-restoration.test.ts
new file mode 100644
index 0000000000..71ab079723
--- /dev/null
+++ b/apps/web/src/features/command/mobile/create-search-scroll-restoration.test.ts
@@ -0,0 +1,231 @@
+import type { EntryState } from '@components/app/split-layout/layoutManager';
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { EntitySearchCategory } from '../queries/entity-search';
+import { createSearchScrollRestoration } from './create-search-scroll-restoration';
+
+const history = vi.hoisted(() => ({
+ state: undefined as EntryState | undefined,
+ read: undefined as (() => unknown) | undefined,
+}));
+vi.mock('@components/app/split-layout/layoutUtils', () => ({
+ useSplitPanelOrThrow: () => ({
+ handle: {
+ currentEntryState: () => history.state,
+ registerEntryStateCaptor: (_key: string, read: () => unknown) => {
+ history.read = read;
+ return () => {
+ history.read = undefined;
+ };
+ },
+ },
+ }),
+}));
+let dispose: (() => void) | undefined;
+beforeEach(() => {
+ history.state = undefined;
+ history.read = undefined;
+});
+afterEach(() => dispose?.());
+
+function setup() {
+ return createRoot((stop) => {
+ dispose = stop;
+ const [items, setItems] = createSignal<string[]>(['first']);
+ const [accountId, setAccountId] = createSignal('alice');
+ const [query, setQuery] = createSignal('notes');
+ const [category, setCategory] = createSignal<EntitySearchCategory>('all');
+ const [ready, setReady] = createSignal(true);
+ const [busy, setBusy] = createSignal(false);
+ const [failed, setFailed] = createSignal(false);
+ const [hasMore, setHasMore] = createSignal(true);
+ const loadMore = vi.fn(async () => {});
+ const apply = vi.fn(
+ (anchor: { id?: string; offset: number; within: number }) =>
+ !anchor.id || items().includes(anchor.id)
+ );
+ const restoration = createSearchScrollRestoration({
+ key: 'scroll',
+ accountId,
+ query,
+ category,
+ items,
+ ready,
+ busy,
+ failed,
+ hasMore,
+ loadMore,
+ apply,
+ read: () => ({ id: 'first', offset: 40, within: 4 }),
+ });
+ return {
+ restoration,
+ setItems,
+ setAccountId,
+ setQuery,
+ setCategory,
+ setReady,
+ setBusy,
+ setFailed,
+ setHasMore,
+ loadMore,
+ apply,
+ };
+ });
+}
+
+it('captures only a scoped item anchor and pixel offsets', () => {
+ setup();
+ expect(history.read?.()).toEqual({
+ accountId: 'alice',
+ query: 'notes',
+ category: 'all',
+ id: 'first',
+ offset: 40,
+ within: 4,
+ });
+});
+
+it('waits for rows and layout, then restores an anchor from a later page once', async () => {
+ history.state = {
+ scroll: {
+ accountId: 'alice',
+ query: 'notes',
+ category: 'all',
+ id: 'target',
+ offset: 500,
+ within: 8,
+ },
+ };
+ const view = setup();
+ view.setReady(false);
+ await Promise.resolve();
+ expect(view.loadMore).not.toHaveBeenCalled();
+ view.loadMore.mockImplementation(async () => {
+ view.setItems(['first', 'target']);
+ });
+ view.setReady(true);
+ await vi.waitFor(() => expect(view.restoration.pending()).toBe(false));
+ expect(view.loadMore).toHaveBeenCalledOnce();
+ expect(view.apply).toHaveBeenLastCalledWith(
+ expect.objectContaining({ id: 'target', within: 8 })
+ );
+ const calls = view.apply.mock.calls.length;
+ view.setItems(['first', 'target', 'third']);
+ await Promise.resolve();
+ expect(view.apply).toHaveBeenCalledTimes(calls);
+});
+
+it('limits automatic recovery to three additional pages when the anchor disappeared', async () => {
+ history.state = {
+ scroll: {
+ accountId: 'alice',
+ query: 'notes',
+ category: 'all',
+ id: 'missing',
+ offset: 500,
+ within: 8,
+ },
+ };
+ const view = setup();
+ view.loadMore.mockImplementation(async () => {
+ view.setItems(['new-page']);
+ });
+ await vi.waitFor(() => expect(view.restoration.pending()).toBe(false));
+ expect(view.loadMore).toHaveBeenCalledTimes(3);
+ expect(view.apply).toHaveBeenLastCalledWith({ offset: 500, within: 0 });
+ expect(view.restoration.paginationAllowed()).toBe(false);
+ view.restoration.cancel();
+ expect(view.restoration.paginationAllowed()).toBe(true);
+});
+
+it('does not repeatedly fetch an unchanged or exhausted page', async () => {
+ history.state = {
+ scroll: {
+ accountId: 'alice',
+ query: 'notes',
+ category: 'all',
+ id: 'missing',
+ offset: 500,
+ within: 8,
+ },
+ };
+ const view = setup();
+ await vi.waitFor(() => expect(view.restoration.pending()).toBe(false));
+ expect(view.loadMore).toHaveBeenCalledOnce();
+});
+
+it.each(['account', 'query', 'user', 'dispose', 'failure'])(
+ 'cannot scroll or fetch after %s cancels a pending restoration',
+ async (reason) => {
+ history.state = {
+ scroll: {
+ accountId: 'alice',
+ query: 'notes',
+ category: 'all',
+ id: 'target',
+ offset: 500,
+ within: 8,
+ },
+ };
+ const view = setup();
+ view.setBusy(true);
+ if (reason === 'account') view.setAccountId('bob');
+ if (reason === 'query') view.setQuery('different');
+ if (reason === 'user') view.restoration.cancel();
+ if (reason === 'dispose') dispose?.();
+ if (reason === 'failure') view.setFailed(true);
+ view.setBusy(false);
+ view.setItems(['target']);
+ await Promise.resolve();
+ expect(view.loadMore).not.toHaveBeenCalled();
+ expect(view.apply).not.toHaveBeenCalled();
+ }
+);
+
+it('ignores an in-flight page completion after the user changes query', async () => {
+ history.state = {
+ scroll: {
+ accountId: 'alice',
+ query: 'notes',
+ category: 'all',
+ id: 'target',
+ offset: 500,
+ within: 8,
+ },
+ };
+ const view = setup();
+ const page = Promise.withResolvers<void>();
+ view.loadMore.mockImplementation(() => page.promise);
+ await vi.waitFor(() => expect(view.loadMore).toHaveBeenCalledOnce());
+ view.setQuery('another search');
+ const calls = view.apply.mock.calls.length;
+ view.setItems(['target']);
+ page.resolve();
+ await page.promise;
+ await Promise.resolve();
+ expect(view.apply).toHaveBeenCalledTimes(calls);
+ expect(view.loadMore).toHaveBeenCalledOnce();
+});
+
+it.each(['query', 'category'] as const)(
+ 'resumes ordinary pagination when %s changes after restoration finished',
+ async (field) => {
+ history.state = {
+ scroll: {
+ accountId: 'alice',
+ query: 'notes',
+ category: 'all',
+ id: 'first',
+ offset: 0,
+ within: 0,
+ },
+ };
+ const view = setup();
+ await vi.waitFor(() => expect(view.restoration.pending()).toBe(false));
+ expect(view.restoration.paginationAllowed()).toBe(false);
+ if (field === 'query') view.setQuery('another search');
+ else view.setCategory('email');
+ expect(view.restoration.paginationAllowed()).toBe(true);
+ }
+);
diff --git a/apps/web/src/features/command/mobile/create-search-scroll-restoration.ts b/apps/web/src/features/command/mobile/create-search-scroll-restoration.ts
new file mode 100644
index 0000000000..b06859f4ee
--- /dev/null
+++ b/apps/web/src/features/command/mobile/create-search-scroll-restoration.ts
@@ -0,0 +1,166 @@
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ on,
+ onCleanup,
+ untrack,
+} from 'solid-js';
+import type { EntitySearchCategory } from '../queries/entity-search';
+
+type SearchAnchor = { id?: string; offset: number; within: number };
+type SearchScrollState = SearchAnchor & {
+ accountId: string;
+ query: string;
+ category: EntitySearchCategory;
+};
+const MAX_RESTORE_PAGES = 3;
+
+/** Restore from current source rows, without keeping a second result cache in history. */
+export function createSearchScrollRestoration<T>(options: {
+ key: string;
+ accountId: Accessor<string>;
+ query: Accessor<string>;
+ category: Accessor<EntitySearchCategory>;
+ items: Accessor<readonly T[]>;
+ ready: Accessor<boolean>;
+ busy: Accessor<boolean>;
+ failed: Accessor<boolean>;
+ hasMore: Accessor<boolean>;
+ loadMore: () => Promise<unknown>;
+ read: () => SearchAnchor;
+ apply: (anchor: SearchAnchor) => boolean;
+}) {
+ const { handle } = useSplitPanelOrThrow();
+ const saved = untrack(() => handle.currentEntryState()?.[options.key]) as
+ | SearchScrollState
+ | undefined;
+ const matches = (state: SearchScrollState) =>
+ state.accountId === options.accountId() &&
+ state.query === options.query() &&
+ state.category === options.category();
+ const [pending, setPending] = createSignal(
+ saved && untrack(() => matches(saved)) ? saved : undefined
+ );
+ const [paginationAllowed, setPaginationAllowed] = createSignal(!pending());
+ const [revision, setRevision] = createSignal(0);
+ const span = pending() ? Telemetry.span('mobile.search.restore') : undefined;
+ span?.setAttr('restore.kind', options.key);
+ // Person keys and account IDs can contain an email address.
+ span?.setAttr('restore.has_anchor', !!saved?.id);
+ let pages = 0;
+ let disposed = false;
+ let loading = false;
+ let queued = false;
+ let lastPage: readonly T[] | undefined;
+ const finish = (outcome: string) => {
+ if (!pending()) return;
+ lastPage = undefined;
+ setPending(undefined);
+ if (outcome === 'fetch_failed' || outcome === 'source_failed')
+ span?.error('Search restoration source failed');
+ span?.setAttr('restore.outcome', outcome);
+ span?.setAttr('restore.pages', pages);
+ span?.end();
+ };
+ const load = async () => {
+ loading = true;
+ try {
+ await options.loadMore();
+ } catch {
+ finish('fetch_failed');
+ } finally {
+ loading = false;
+ if (!disposed) setRevision((value) => value + 1);
+ }
+ };
+ onCleanup(
+ handle.registerEntryStateCaptor(
+ options.key,
+ () =>
+ pending() ?? {
+ accountId: options.accountId(),
+ query: options.query(),
+ category: options.category(),
+ ...options.read(),
+ }
+ )
+ );
+ onCleanup(() => {
+ disposed = true;
+ finish('disposed');
+ });
+ createEffect(
+ on(
+ [
+ pending,
+ options.items,
+ options.ready,
+ options.busy,
+ options.failed,
+ options.hasMore,
+ options.accountId,
+ options.query,
+ options.category,
+ revision,
+ ],
+ () => {
+ // Editing the dock query/category starts ordinary pagination again, even
+ // after an earlier restoration has already finished.
+ if (saved && !matches(saved)) setPaginationAllowed(true);
+ const anchor = pending();
+ if (!anchor) return;
+ if (!matches(anchor)) {
+ finish('scope_changed');
+ return;
+ }
+ if (options.failed()) {
+ finish('source_failed');
+ return;
+ }
+ if (loading || options.busy() || !options.ready() || queued) return;
+ queued = true;
+ // Responsive row layout and the virtualizer must commit before scrolling.
+ queueMicrotask(() => {
+ queued = false;
+ if (
+ disposed ||
+ pending() !== anchor ||
+ !matches(anchor) ||
+ loading ||
+ options.busy() ||
+ !options.ready()
+ )
+ return;
+ if (options.apply(anchor)) {
+ finish('restored');
+ return;
+ }
+ if (
+ !options.hasMore() ||
+ pages >= MAX_RESTORE_PAGES ||
+ lastPage === options.items()
+ ) {
+ options.apply({ offset: anchor.offset, within: 0 });
+ finish('fallback');
+ return;
+ }
+ pages++;
+ lastPage = options.items();
+ fireAndForget(load(), 'mobile-search');
+ });
+ }
+ )
+ );
+ return {
+ pending: () => pending() !== undefined,
+ paginationAllowed,
+ cancel: () => {
+ setPaginationAllowed(true);
+ finish('user_scrolled');
+ },
+ };
+}
diff --git a/docs/agent-guide/search.md b/docs/agent-guide/search.md
index 2d46a3f49a..8dcd45e3e2 100644
--- a/docs/agent-guide/search.md
+++ b/docs/agent-guide/search.md
@@ -48,23 +48,29 @@ 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).
-Snapshots are released when their history entry is removed or replaced, or its
-pane closes; entries still reachable with Back/Forward retain their snapshots.
-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
+Name-result ordering and scroll anchors identify a one-to-one DM by its other
+participant, so a person keeps their place when opening them creates a conversation
+with a new channel ID. Group conversations keep their own channel identity.
+Native Search captures lightweight state when covered so deeper navigation can
+unmount it. History saves the query/category/mode, an account-scoped item ID and
+offset within that row, a fallback pixel offset, and at most 200 ordering IDs per
+mode. It never stores result row objects or virtualizer measurement caches.
+A remount reads current source data; it may show loading while those rows are
+unavailable. Restoration waits for layout and fetches at most three additional
+pages to find the anchor. Missing anchors, exhausted/no-progress pagination, or
+the page limit use the available scroll range instead. Touch, pointer, or wheel
+interaction cancels pending restoration so later pages cannot move the user.
+Automatic viewport paging stays paused after recovery until the user interacts
+or changes the query/category.
+Matching current rows follow the bounded saved order; absent rows are not revived
+from history. The live source owns result data and its cache lifetime. Leaving
+Search through native dock navigation disposes its result view while lightweight
+entries may remain reachable through history. Starting a new dock Search supplies
+a fresh route session ID and computes a fresh order.
+Snapshots are released when their history entry is removed/replaced or its pane
+closes. Account changes recreate result sources/scrollers and cannot restore
+another account's anchor or ordering. A failed or empty source cannot revive rows
+from a historical snapshot. 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.
@@ -80,17 +86,22 @@ 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.
+Include a person without a DM: open them from midway through All/People results,
+then go Back and confirm that person's new DM is still in the same place and opens
+the existing conversation on a second selection. Repeat with the DM arriving after
+Search unmounts, and verify group DMs stay separate.
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.
+Repeat with a slow refresh: a remount waits for current rows rather than showing
+saved row objects. Use an anchor on a later page and confirm restoration waits
+for that page and responsive layout. Remove the anchor or keep it beyond three
+additional pages and verify recovery stops at the available position. While
+recovery is pending, scroll manually and confirm later pages do not move the
+viewport. In full-text mode, repeat Back from a deep list and check the same row
+returns to the same position when it is available within the recovery limit.
+Inspect captured Search entry state: it contains bounded IDs and scalar state,
+with no row objects, snippets, or virtualizer caches. Switch dock views repeatedly
+and confirm old source rows can be collected even while lightweight history remains.
Clear with whitespace and check category
retention; select Projects from full-text mode and confirm it shows name results.
Repeat opening with a large recent list: results are virtualized, so transferring