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(command): prevent cache refresh bursts from starving entity results (#6923)
Sean Ayeff58e7d7733e
diff --git a/apps/web/src/features/command/CommandMenu.tsx b/apps/web/src/features/command/CommandMenu.tsxindex 3854fd06bf..608fc9454b 100644--- a/apps/web/src/features/command/CommandMenu.tsx+++ b/apps/web/src/features/command/CommandMenu.tsx@@ -157,6 +157,8 @@ export function CommandMenuInner(props: {});const filteredItems = props.items ?? defaultCommandItems!.items;const pagination = defaultCommandItems?.pagination;+ const isLoadingEntities = () =>+ defaultCommandItems?.isLoadingEntities() ?? false;const listController = createCommandListController({items: filteredItems,selectedIndex: CommandState.selectedIndex,@@ -638,6 +640,11 @@ export function CommandMenuInner(props: {</Show><CommandMenuShell.Body>+ <Show when={isLoadingEntities() && filteredItems().length > 0}>+ <div role="status" class="px-4 py-2 text-xs text-ink-muted">+ Loading results…+ </div>+ </Show><divclass="overflow-hidden transition-[height] duration-60 ease-out p-2"style={{ height: `${resultsHeight()}px` }}@@ -645,7 +652,11 @@ export function CommandMenuInner(props: {<Showwhen={filteredItems().length > 0}fallback={- <CommandMenuEmptyState>No results found</CommandMenuEmptyState>+ <CommandMenuEmptyState>+ <Show when={isLoadingEntities()} fallback="No results found">+ <span role="status">Loading results…</span>+ </Show>+ </CommandMenuEmptyState>}><VirtualizedCommandListdiff --git a/apps/web/src/features/command/useCommandItems.test.ts b/apps/web/src/features/command/useCommandItems.test.tsnew file mode 100644index 0000000000..c12607dd0f--- /dev/null+++ b/apps/web/src/features/command/useCommandItems.test.ts@@ -0,0 +1,154 @@+import type {+ QuickAccessItem,+ QuickAccessList,+} from '@core/context/quickAccess/types';+import type { CommandWithInfo } from '@core/hotkey/getCommands';+import { createRoot, createSignal } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { CategoryFilter } from './types';+import { useCommandItems } from './useCommandItems';++const mocks = vi.hoisted(() => ({+ list: undefined as QuickAccessList | undefined,+ entityMode: (): boolean => false,+ scope: (): CommandWithInfo[] => [],+}));+vi.mock('@app/constants/hotkeys', () => ({+ GO_TO_COMMAND_SCOPE: 'go-to',+ GO_TO_LEADER_KEY: 'g',+}));+vi.mock('@core/context/quickAccess', () => ({+ exclude: () => ['note', 'channel'],+ useQuickAccess: () => ({+ useList: () => {+ if (!mocks.list) throw new Error('Missing test list');+ return mocks.list;+ },+ usesRecordSelection: () => false,+ usesSearchProjection: () => true,+ }),+}));+vi.mock('@core/hotkey/getCommands', () => ({+ getActiveCommandsFromScope: (scope: string) =>+ scope === 'go-to'+ ? []+ : [+ {+ scopeId: 'global',+ description: 'Create',+ runWithInputFocused: true,+ scopeLevel: 0,+ hotkeyIsShadowed: false,+ },+ ],+}));+vi.mock('@core/hotkey/state', () => ({+ activeScope: () => 'global',+ hotkeyScopeTree: new Map(),+}));+vi.mock('./recency', () => ({ getCommandLastUsedAt: () => undefined }));+vi.mock('./state', () => ({+ CommandState: {+ commandScopeCommands: () => mocks.scope(),+ isEntityActionMode: () => mocks.entityMode(),+ },+}));++let dispose: (() => void) | undefined;+afterEach(() => {+ dispose?.();+});+function setup() {+ return createRoot((cleanup) => {+ dispose = cleanup;+ const [items, setItems] = createSignal<QuickAccessItem[]>([]);+ const [loading, setLoading] = createSignal(true);+ const [category, setCategory] = createSignal<CategoryFilter>('all');+ const [entityMode, setEntityMode] = createSignal(false);+ const [scope, setScope] = createSignal<CommandWithInfo[]>([]);+ mocks.entityMode = entityMode;+ mocks.scope = scope;+ mocks.list = {+ items,+ isLoading: loading,+ totalCount: () => items().length,+ hasMore: () => false,+ isLoadingMore: () => false,+ loadMore: async () => {},+ };+ const result = useCommandItems(() => '', category, {+ searchActive: () => true,+ });+ return {+ result,+ setItems,+ setLoading,+ setCategory,+ setEntityMode,+ setScope,+ };+ });+}++const entity: QuickAccessItem = {+ id: 'document',+ kind: 'entity',+ bucket: 'note',+ searchText: 'Document',+ sortTimestamp: 1,+ timestamps: {},+ data: {+ id: 'document',+ type: 'document',+ fileType: 'md',+ name: 'Document',+ ownerId: 'owner',+ },+};++describe('command menu entity loading', () => {+ it('keeps commands available while entities load, then shows arriving results', () => {+ const { result, setItems, setLoading } = setup();+ expect(result.items().map((item) => item.kind)).toEqual(['command']);+ expect(result.isLoadingEntities()).toBe(true);+ setItems([entity]);+ expect(result.items().map((item) => item.kind)).toEqual([+ 'command',+ 'entity',+ ]);+ // A dirty follow-up may still be fetching; available entities remove the notice.+ expect(result.isLoadingEntities()).toBe(false);+ setLoading(false);+ expect(result.isLoadingEntities()).toBe(false);+ });++ it('distinguishes loading from a settled empty entity category', () => {+ const { result, setCategory, setLoading } = setup();+ setCategory('documents');+ expect(result.items()).toEqual([]);+ expect(result.isLoadingEntities()).toBe(true);+ setLoading(false);+ expect(result.items()).toEqual([]);+ expect(result.isLoadingEntities()).toBe(false);+ });++ it('does not report entity loading in commands, entity actions, or nested command scopes', () => {+ const { result, setCategory, setEntityMode, setScope } = setup();+ setCategory('commands');+ expect(result.isLoadingEntities()).toBe(false);+ setCategory('all');+ setEntityMode(true);+ expect(result.isLoadingEntities()).toBe(false);+ setEntityMode(false);+ setScope([+ {+ scopeId: 'nested',+ description: 'Nested',+ runWithInputFocused: true,+ scopeLevel: 0,+ hotkeyIsShadowed: false,+ },+ ]);+ expect(result.isLoadingEntities()).toBe(false);+ });+});diff --git a/apps/web/src/features/command/useCommandItems.ts b/apps/web/src/features/command/useCommandItems.tsindex a83546557f..0dbad2f388 100644--- a/apps/web/src/features/command/useCommandItems.ts+++ b/apps/web/src/features/command/useCommandItems.ts@@ -379,6 +379,10 @@ function useQuickAccessCategory(return {items,+ isLoadingEntities: () => {+ const list = activeList();+ return !!list?.isLoading() && list.items().length === 0;+ },pagination: {hasMore: () => activeList()?.hasMore() ?? false,isLoadingMore: () => activeList()?.isLoadingMore() ?? false,@@ -508,6 +512,7 @@ export function useCommandItems(return {items: filteredItems,+ isLoadingEntities: category.isLoadingEntities,pagination: category.pagination,};}diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.tsindex 8b75a17ce0..0792af24ba 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts@@ -29,6 +29,7 @@ import {BUCKET_COMBINATIONS,type Bucket,type QuickAccessContextValue,+ type QuickAccessListOptions,} from './types';const mocks = vi.hoisted(() => ({@@ -265,12 +266,17 @@ const retainedListText = {'recently-viewed': `older-note@${Date.parse('2026-08-03T00:00:00.000Z')},newer-note@${Date.parse('2026-08-02T00:00:00.000Z')}`,};-function renderRetainedList(client: QueryClient) {+function renderRetainedList(+ client: QueryClient,+ options?: QuickAccessListOptions+) {const Shell = () => {- const list = useQuickAccess().useList();+ const quickAccess = useQuickAccess();+ const list = options ? quickAccess.useList(options) : quickAccess.useList();const node = document.createElement('main');node.dataset.testid = 'retained-shell';createRenderEffect(() => {+ node.dataset.loading = String(list.isLoading());node.textContent = list.items().map((item) => `${item.id}@${item.sortTimestamp}`)@@ -293,6 +299,136 @@ function renderRetainedList(client: QueryClient) {}describe('Quick Access source integration', () => {+ it('lets initially empty cached channels populate during hydration and replays the last change', async () => {+ const first = retainedQueryData.channels;+ const latest = [{ ...first[0], name: 'Updated channel' }];+ let finishFirst!: (data: typeof first) => void;+ let finishLatest!: (data: typeof first) => void;+ const fetch = vi+ .fn<() => Promise<typeof first>>()+ .mockResolvedValueOnce([])+ .mockReturnValueOnce(+ new Promise<typeof first>((resolve) => {+ finishFirst = resolve;+ })+ )+ .mockReturnValueOnce(+ new Promise<typeof first>((resolve) => {+ finishLatest = resolve;+ })+ );+ let query: UseQueryResult<unknown[]> | undefined;+ mocks.queries.channels = () =>+ (query = useQuery(() => ({+ queryKey: ['channel-burst'],+ queryFn: fetch,+ retry: false,+ })));+ const client = new QueryClient();+ const rendered = renderRetainedList(client);+ try {+ await vi.waitFor(() => expect(query?.isSuccess).toBe(true));+ vi.useFakeTimers();+ mocks.changed?.();+ for (let i = 0; i < 8; i++) {+ mocks.changed?.();+ await vi.advanceTimersByTimeAsync(250);+ }+ expect(fetch).toHaveBeenCalledTimes(2);+ expect(rendered.getByTestId('retained-shell').dataset.loading).toBe(+ 'false'+ );+ finishFirst(first);+ await vi.advanceTimersByTimeAsync(250);+ expect(rendered.getByTestId('retained-shell').textContent).toBe(+ retainedListText.channels+ );+ expect(fetch).toHaveBeenCalledTimes(3);+ finishLatest(latest);+ await vi.advanceTimersByTimeAsync(1000);+ expect(query?.data).toEqual(latest);+ expect(fetch).toHaveBeenCalledTimes(3);+ expect(rendered.getByTestId('retained-shell').dataset.loading).toBe(+ 'false'+ );+ } finally {+ rendered.unmount();+ client.clear();+ }+ });++ it.each(['history', 'channels'] as const)(+ 'reports loading while the %s fallback is initially pending',+ async (source) => {+ let finish!: (data: unknown[]) => void;+ mocks.queries[source] = () =>+ useQuery(() => ({+ queryKey: ['initial-loading', source],+ queryFn: () =>+ new Promise<unknown[]>((resolve) => {+ finish = resolve;+ }),+ retry: false,+ }));+ const client = new QueryClient();+ const rendered = renderRetainedList(client);+ try {+ const shell = rendered.getByTestId('retained-shell');+ await vi.waitFor(() => expect(shell.dataset.loading).toBe('true'));+ finish(retainedQueryData[source]);+ await vi.waitFor(() => expect(shell.dataset.loading).toBe('false'));+ expect(shell.textContent).toBe(retainedListText[source]);+ } finally {+ rendered.unmount();+ client.clear();+ }+ }+ );++ it.each(['history', 'channels'] as const)(+ 'keeps settled empty search results idle during a background %s refetch',+ async (source) => {+ let finishRefresh!: (data: unknown[]) => void;+ const fetch = vi+ .fn<() => Promise<unknown[]>>()+ .mockResolvedValueOnce([])+ .mockReturnValueOnce(+ new Promise<unknown[]>((resolve) => {+ finishRefresh = resolve;+ })+ );+ let query: UseQueryResult<unknown[]> | undefined;+ mocks.queries[source] = () =>+ (query = useQuery(() => ({+ queryKey: ['empty-background-refresh', source],+ queryFn: fetch,+ retry: false,+ })));+ const client = new QueryClient();+ const rendered = renderRetainedList(client, {+ buckets: ['note'],+ searchTerm: () => 'no matching entities',+ });+ try {+ const shell = rendered.getByTestId('retained-shell');+ await vi.waitFor(() => expect(query?.isSuccess).toBe(true));+ await vi.waitFor(() => expect(shell.dataset.loading).toBe('false'));+ expect(shell.textContent).toBe('');+ const refresh = query!.refetch();+ await vi.waitFor(() => expect(query?.isRefetching).toBe(true));+ expect(shell.dataset.loading).toBe('false');+ expect(shell.textContent).toBe('');+ finishRefresh([]);+ await refresh;+ expect(shell.dataset.loading).toBe('false');+ expect(shell.textContent).toBe('');+ } finally {+ rendered.unmount();+ client.clear();+ }+ }+ );+it.each((['history', 'channels', 'recently-viewed'] as const).flatMap((source) =>(['resolve', 'reject'] as const).map((settlement) => ({@@ -388,6 +524,7 @@ describe('Quick Access source integration', () => {expect(shell.textContent).toBe(expected);const refresh = query!.refetch();await vi.waitFor(() => expect(query?.isRefetching).toBe(true));+ expect(shell.dataset.loading).toBe('false');expect(shell.textContent).toBe(expected);rejectRefresh(new Error('cache refresh failed'));await refresh;diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsxindex 6fc65a1ec0..16c2b465fc 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx@@ -328,7 +328,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {onCleanup(subscribeToVisibleCacheChanges(cacheHost, () => {setCacheRevision((revision) => revision + 1);- void cachedChannelsQuery.refetch();+ return cachedChannelsQuery.refetch({ cancelRefetch: false });}));}@@ -1001,7 +1001,13 @@ export function createQuickAccessValue(): QuickAccessContextValue {items: list,totalCount: () => list().length,hasMore: () => projected?.hasMore() ?? false,- isLoading: () => projected?.isLoading() ?? false,+ isLoading: () =>+ options?.enabled?.() !== false &&+ Boolean(+ projected?.isLoading() ||+ historyQuery.isLoading ||+ (cacheHost ? cachedChannelsQuery.isLoading : channelsLoading())+ ),isLoadingMore: () => projected?.isLoadingMore() ?? false,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 de73aff86c..48e5e93d88 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@@ -82,6 +82,126 @@ describe('Quick Access local projection', () => {expect(search).toHaveBeenCalledTimes(2);});+ it.each(['search', 'materialize'] as const)(+ 'publishes a slow %s during continuous revisions and coalesces a follow-up',+ async (stage) => {+ const [revision, setRevision] = createSignal(0);+ const first = deferred<SearchCachePage>();+ const firstMaterialization = deferred<{ id: string }[]>();+ const followUp = deferred<SearchCachePage>();+ const search = vi+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()+ .mockReturnValueOnce(+ stage === 'search' ? first.promise : Promise.resolve(page(['first']))+ )+ .mockReturnValueOnce(followUp.promise);+ const project = vi.fn(materialize);+ if (stage === 'materialize')+ project.mockReturnValueOnce(firstMaterialization.promise);+ const list = root(() =>+ createProjectedList({+ host: { search },+ buckets: ['note'],+ revision,+ materialize: project,+ })+ );+ if (stage === 'materialize')+ await vi.waitFor(() => expect(project).toHaveBeenCalledOnce());+ for (let i = 1; i <= 8; i++) setRevision(i);+ expect(search).toHaveBeenCalledOnce();+ first.resolve(page(['first']));+ firstMaterialization.resolve([{ id: 'GraphqlSoupDocument:first' }]);+ await vi.waitFor(() =>+ expect(list.items()).toEqual([{ id: 'GraphqlSoupDocument:first' }])+ );+ expect(search).toHaveBeenCalledTimes(2);+ expect(list.isLoading()).toBe(true);+ followUp.resolve(page(['latest']));+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));+ expect(list.items()).toEqual([{ id: 'GraphqlSoupDocument:latest' }]);+ expect(search).toHaveBeenCalledTimes(2);+ }+ );++ it('commits a load-more page before replaying the enlarged window after hydration', async () => {+ const [revision, setRevision] = createSignal(0);+ const next = deferred<SearchCachePage>();+ const replay = deferred<SearchCachePage>();+ const search = vi+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()+ .mockResolvedValueOnce(page(['one'], true))+ .mockReturnValueOnce(next.promise)+ .mockReturnValueOnce(replay.promise)+ .mockResolvedValueOnce(page(['two', 'new']));+ const list = root(() =>+ createProjectedList({+ host: { search },+ buckets: ['note'],+ revision,+ materialize,+ })+ );+ await vi.waitFor(() => expect(list.hasMore()).toBe(true));+ const append = list.loadMore();+ setRevision(1);+ setRevision(2);+ expect(search).toHaveBeenCalledTimes(2);+ next.resolve(page(['two'], true));+ await append;+ expect(list.items()).toHaveLength(2);+ expect(search).toHaveBeenCalledTimes(3);+ expect(search.mock.calls[2][0].cursor).toBeUndefined();+ replay.resolve(page(['one'], true));+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));+ expect(list.items()).toHaveLength(3);+ expect(search).toHaveBeenCalledTimes(4);+ });++ it.each(['query', 'buckets', 'disable', 'dispose'] as const)(+ 'drops a queued refresh and late results on %s changes',+ async (change) => {+ const [revision, setRevision] = createSignal(0);+ const [query, setQuery] = createSignal('old');+ const [buckets, setBuckets] = createSignal<Bucket[]>(['note']);+ const [enabled, setEnabled] = createSignal(true);+ const obsolete = deferred<SearchCachePage>();+ const search = vi+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()+ .mockReturnValueOnce(obsolete.promise)+ .mockResolvedValue(page(['new']));+ const list = root(() =>+ createProjectedList({+ host: { search },+ get buckets() {+ return buckets();+ },+ revision,+ searchTerm: query,+ enabled,+ materialize,+ })+ );+ setRevision(1);+ expect(search).toHaveBeenCalledOnce();+ if (change === 'query') setQuery('new');+ if (change === 'buckets') setBuckets(['task']);+ if (change === 'disable') setEnabled(false);+ if (change === 'dispose')+ cleanups.splice(0).forEach((cleanup) => cleanup());+ obsolete.resolve(page(['old']));+ const replaced = change === 'query' || change === 'buckets';+ await vi.waitFor(() =>+ expect(list.items()).toEqual(+ replaced ? [{ id: 'GraphqlSoupDocument:new' }] : []+ )+ );+ await obsolete.promise;+ await Promise.resolve();+ expect(search).toHaveBeenCalledTimes(replaced ? 2 : 1);+ }+ );+it('resets the loaded window and cursor when reactive buckets change', async () => {const [buckets, setBuckets] = createSignal<Bucket[]>(['note',diff --git a/apps/web/src/lib/core/context/quickAccess/projected-list.ts b/apps/web/src/lib/core/context/quickAccess/projected-list.tsindex 7dd29dab0c..770ea2d746 100644--- a/apps/web/src/lib/core/context/quickAccess/projected-list.ts+++ b/apps/web/src/lib/core/context/quickAccess/projected-list.ts@@ -37,6 +37,7 @@ type Request = {pages: number;cursor?: SearchCursor;busy: boolean;+ refreshPending: boolean;};/** A paginated, cache-only search. Refreshes replay the loaded browse window@@ -68,12 +69,25 @@ export function createProjectedList<T extends { id: string }>(options: {current = undefined;});+ const finishRequest = (request: Request) => {+ if (current !== request) return;+ request.busy = false;+ if (request.refreshPending) {+ // Publish the completed window before replaying changes received during+ // search/materialization (or a load-more operation).+ void fetchPages(request, request.pages, false);+ } else {+ setLoading('idle');+ }+ };+const fetchPages = async (request: Request,pageCount: number,append: boolean) => {request.busy = true;+ request.refreshPending = false;setLoading(append ? 'more' : 'initial');const previous = append ? untrack(items) : [];const merged = new Map(previous.map((item) => [item.id, item]));@@ -129,10 +143,7 @@ export function createProjectedList<T extends { id: string }>(options: {setHasMore(request.cursor !== undefined);console.warn('Quick Access cache search failed', error);} finally {- if (current === request) {- request.busy = false;- setLoading('idle');- }+ finishRequest(request);}};@@ -142,26 +153,34 @@ export function createProjectedList<T extends { id: string }>(options: {const activeBuckets = buckets();const enabled = options.enabled?.() !== false && activeBuckets.length > 0;const previous = current;+ if (+ enabled &&+ previous?.query === query &&+ previous.buckets.length === activeBuckets.length &&+ previous.buckets.every((bucket, index) => bucket === activeBuckets[index])+ ) {+ // A cache revision is not a new search. Replacing an in-flight request+ // here starves results when hydration is faster than cache reads.+ if (previous.busy) previous.refreshPending = true;+ else void fetchPages(previous, previous.pages, false);+ return;+ }++ // Genuine query/bucket changes, disabling, and disposal still fence off+ // obsolete responses and their queued refreshes.current = undefined;setHasMore(false);+ setItems([]);if (!enabled) {- setItems([]);setLoading('idle');return;}- const sameSearch =- previous?.query === query &&- previous.buckets.length === activeBuckets.length &&- previous.buckets.every(- (bucket, index) => bucket === activeBuckets[index]- );- if (!sameSearch) setItems([]);const request: Request = {buckets: activeBuckets,query,- pages: sameSearch ? previous.pages : 1,- cursor: sameSearch ? previous.cursor : undefined,+ pages: 1,busy: false,+ refreshPending: false,};current = request;void fetchPages(request, request.pages, false);diff --git a/apps/web/src/lib/queries/history/history.ts b/apps/web/src/lib/queries/history/history.tsindex 2d0a2599c8..272a8ca644 100644--- a/apps/web/src/lib/queries/history/history.ts+++ b/apps/web/src/lib/queries/history/history.ts@@ -104,11 +104,12 @@ export function useHistoryQuery() {const host = graphqlCacheHost();if (!host) return;onCleanup(- subscribeToVisibleCacheChanges(host, () => {- void activeQueryClient.invalidateQueries({- queryKey: historyKeys.graphqlList.queryKey,- });- })+ subscribeToVisibleCacheChanges(host, () =>+ activeQueryClient.invalidateQueries(+ { queryKey: historyKeys.graphqlList.queryKey },+ { cancelRefetch: false }+ )+ ));});diff --git a/apps/web/src/lib/queries/history/tests/cache-refresh.test.tsx b/apps/web/src/lib/queries/history/tests/cache-refresh.test.tsxindex 43d6c84765..5c983cd3fb 100644--- a/apps/web/src/lib/queries/history/tests/cache-refresh.test.tsx+++ b/apps/web/src/lib/queries/history/tests/cache-refresh.test.tsx@@ -94,6 +94,68 @@ describe('cache-backed history refresh', () => {client.clear();});+ it('populates initially empty history during a slow hydration burst, then catches up once', async () => {+ let notify: (() => void) | undefined;+ mocks.subscribe.mockImplementation((callback: () => void) => {+ notify = callback;+ return mocks.unsubscribe;+ });+ const first = [+ { id: 'first', name: 'First', type: 'document', ownerId: 'owner' },+ ];+ const latest = [...first, { ...first[0], id: 'latest' }];+ let finishFirst!: (data: typeof first) => void;+ let finishLatest!: (data: typeof first) => void;+ mocks.readHistory+ .mockResolvedValueOnce([])+ .mockReturnValueOnce(+ new Promise<typeof first>((resolve) => {+ finishFirst = resolve;+ })+ )+ .mockReturnValueOnce(+ new Promise<typeof first>((resolve) => {+ finishLatest = resolve;+ })+ );+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ let query: ReturnType<typeof useHistoryQuery> | undefined;+ const Probe = () => {+ query = useHistoryQuery();+ return null;+ };+ const view = render(() => (+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>+ ));+ try {+ await waitFor(() => expect(query?.isSuccess).toBe(true));+ expect(query?.data).toEqual([]);+ vi.useFakeTimers();+ notify?.();+ for (let i = 0; i < 8; i++) {+ notify?.();+ await vi.advanceTimersByTimeAsync(250);+ }+ expect(mocks.readHistory).toHaveBeenCalledTimes(2);+ finishFirst(first);+ await vi.advanceTimersByTimeAsync(250);+ expect(query?.data).toEqual(first);+ expect(mocks.readHistory).toHaveBeenCalledTimes(3);+ finishLatest(latest);+ await vi.advanceTimersByTimeAsync(1000);+ expect(query?.data).toEqual(latest);+ expect(mocks.readHistory).toHaveBeenCalledTimes(3);+ expect(mocks.fetchHistory).not.toHaveBeenCalled();+ } finally {+ view.unmount();+ client.clear();+ }+ });+it('opts into hydration, refreshes only local history, and unsubscribes on disposal', async () => {let notify: (() => void) | undefined;mocks.subscribe.mockImplementation(diff --git a/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.test.ts b/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.test.tsindex 3791efc108..1db4a80fb3 100644--- a/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.test.ts+++ b/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.test.ts@@ -10,7 +10,7 @@ function setVisibility(value: DocumentVisibilityState) {document.dispatchEvent(new Event('visibilitychange'));}-function setup() {+function setup(refresh = vi.fn<() => void | Promise<unknown>>()) {let notify = () => {};const unsubscribe = vi.fn();const host = {@@ -19,7 +19,6 @@ function setup() {return unsubscribe;}),} satisfies Pick<CacheHost, 'onCacheChanged'>;- const refresh = vi.fn();dispose = subscribeToVisibleCacheChanges(host, refresh);return { host, notify, refresh, unsubscribe };}@@ -116,6 +115,81 @@ describe('subscribeToVisibleCacheChanges', () => {expect(refresh).not.toHaveBeenCalled();});+ it('finishes a slow refresh before one follow-up for changes received in flight', async () => {+ let finishFirst!: () => void;+ let finishSecond!: () => void;+ const refresh = vi+ .fn<() => void | Promise<unknown>>()+ .mockReturnValueOnce(+ new Promise<void>((resolve) => {+ finishFirst = resolve;+ })+ )+ .mockReturnValueOnce(+ new Promise<void>((resolve) => {+ finishSecond = resolve;+ })+ );+ const { notify } = setup(refresh);+ notify();+ for (let i = 0; i < 6; i++) {+ notify();+ await vi.advanceTimersByTimeAsync(250);+ }+ expect(refresh).toHaveBeenCalledOnce();+ finishFirst();+ await vi.advanceTimersByTimeAsync(250);+ expect(refresh).toHaveBeenCalledTimes(2);+ finishSecond();+ await vi.advanceTimersByTimeAsync(1000);+ expect(refresh).toHaveBeenCalledTimes(2);+ });++ it.each(['hidden', 'disposed'] as const)(+ 'does not run a dirty follow-up while %s after a pending refresh settles',+ async (state) => {+ let finish!: () => void;+ const refresh = vi+ .fn<() => void | Promise<unknown>>()+ .mockReturnValueOnce(+ new Promise<void>((resolve) => {+ finish = resolve;+ })+ );+ const { notify } = setup(refresh);+ notify();+ notify();+ if (state === 'hidden') setVisibility('hidden');+ else dispose?.();+ finish();+ await vi.advanceTimersByTimeAsync(1000);+ expect(refresh).toHaveBeenCalledOnce();+ setVisibility('visible');+ await vi.advanceTimersByTimeAsync(250);+ expect(refresh).toHaveBeenCalledTimes(state === 'hidden' ? 2 : 1);+ }+ );++ it('handles rejection without dropping a dirty follow-up or retrying forever', async () => {+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});+ let reject!: (error: Error) => void;+ const refresh = vi+ .fn<() => void | Promise<unknown>>()+ .mockReturnValueOnce(+ new Promise<void>((_resolve, fail) => {+ reject = fail;+ })+ )+ .mockRejectedValueOnce(new Error('still unavailable'));+ const { notify } = setup(refresh);+ notify();+ notify();+ reject(new Error('unavailable'));+ await vi.advanceTimersByTimeAsync(1000);+ expect(refresh).toHaveBeenCalledTimes(2);+ expect(warning).toHaveBeenCalledTimes(2);+ });+it.each(['hidden', 'visible'] as const)('disposes notifications, visibility handling, and timers while %s',(state) => {diff --git a/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.ts b/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.tsindex 443eee6ce9..b7eda5f2fc 100644--- a/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.ts+++ b/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.ts@@ -7,26 +7,40 @@ const CACHE_REFRESH_INTERVAL_MS = 250;/*** Throttles cache-driven UI refreshes while visible. Hidden tabs retain one* dirty bit instead of repeatedly reading the shared cache; becoming visible- * refreshes once against its latest state. This does not pause cache ingestion,- * mutations, or explicit/initial query requests.+ * refreshes once against its latest state. Async refreshes finish before one+ * dirty follow-up runs, so a busy cache cannot continually cancel its readers.+ * This does not pause cache ingestion, mutations, or explicit/initial requests.** The caller must unsubscribe on disposal.*/export function subscribeToVisibleCacheChanges(host: Pick<CacheHost, 'onCacheChanged'>,- refresh: () => void+ refresh: () => void | Promise<unknown>): () => void {let dirty = false;let disposed = false;+ let refreshing = false;const isVisible = () => document.visibilityState === 'visible';+ const runRefresh = async () => {+ // Visibility can change between scheduling and the trailing callback.+ if (disposed || refreshing || !dirty || !isVisible()) return;+ dirty = false;+ refreshing = true;+ try {+ const completion = refresh();+ if (completion) await completion;+ } catch (error) {+ console.warn('Cache-driven refresh failed', error);+ } finally {+ refreshing = false;+ // Keep changes received during a read, including the last change in a+ // burst. A failed read only retries if another change made it dirty.+ if (dirty && !disposed && isVisible()) scheduled();+ }+ };const scheduled = leadingAndTrailing(throttle,- () => {- // Visibility can change between scheduling and the trailing callback.- if (disposed || !dirty || !isVisible()) return;- dirty = false;- refresh();- },+ () => void runRefresh(),CACHE_REFRESH_INTERVAL_MS);const unsubscribe = host.onCacheChanged(diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex 6f5a9d57b1..dc5f59b678 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -411,7 +411,16 @@ email mentions keep their separate search-service path.Pending or failed Quick Access history, recently-viewed, and cached-channel lookupsmust not hide the app shell. Verify a cold lookup with Cmd/Ctrl+K: navigation stays-mounted and usable while the optional source loads or fails. A failed background+mounted and usable while the optional source loads or fails. When no entity rows+are available yet, the menu shows **Loading results…** while keeping commands+usable; a settled empty category shows **No results found**. Background history+or channel refetches alone must not switch settled empty results back to loading,+including when the active category does not use that source. Cache-update bursts+must let in-flight history, channel, and menu-search reads publish their results,+then catch up with one coalesced refresh. Verify with cache reads slower than the+250 ms update throttle, starting from an empty cache: entities appear without+waiting for background updates to stop. Changing the query/category or closing+the menu still discards obsolete search results. A failed backgroundrefresh retains available history/channel items and recently-viewed ordering.Placeholder results also remain usable while replacement data loads. A normal cache-workerhandoff between tabs preserves backfill cursors and watermarks; only a replacement