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.

Seanaye/fix/missing mentions entries (#6696)

Sean Aye2f1d83ccad83
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
index 28529a0d84..41f242da81 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
@@ -43,6 +43,7 @@ import type {
import { useMenuKeyboardNavigation } from '../useMenuKeyboardNavigation';
import { ItemBin } from './components/ItemBin';
import { MentionsMenuItem } from './components/MentionsMenuItem';
+import { createMentionPageLoader } from './hooks/createMentionPageLoader';
import { useEmailSearchMention } from './hooks/useEmailSearchMention';
import {
useEntityMention,
@@ -503,6 +504,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {
});
});
+ const maybeLoadMentionPage = createMentionPageLoader();
createEffect(() => {
const items = controller.combinedItems();
if (!items) return;
@@ -511,13 +513,12 @@ function MentionsMenuInner(props: MentionsMenuProps) {
const activeBucket = viewAllMode
? controller.getBucket(viewAllMode)
: undefined;
- if (
- controller.selectedIndex() >= items.length - 5 &&
- activeBucket?.hasMore?.() &&
- !activeBucket.isLoadingMore?.()
- ) {
- void activeBucket.loadMore?.();
- }
+ maybeLoadMentionPage({
+ bucket: activeBucket,
+ query: activeSearchTerm(),
+ selectedIndex: controller.selectedIndex(),
+ itemCount: items.length,
+ });
if (controller.selectedIndex() >= items.length) {
controller.selectItem(items.length - 1);
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/createMentionPageLoader.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/createMentionPageLoader.test.ts
new file mode 100644
index 0000000000..b2212ffc50
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/createMentionPageLoader.test.ts
@@ -0,0 +1,68 @@
+import { createEffect, createRoot, createSignal } from 'solid-js';
+import { expect, it, vi } from 'vitest';
+import type { MentionBucketId } from '../MentionsMenuController';
+import { createMentionPageLoader } from './createMentionPageLoader';
+
+it('does not turn a bounded empty/duplicate scan into an automatic loading loop', async () => {
+ const [loading, setLoading] = createSignal(false);
+ const [selectedIndex, setSelectedIndex] = createSignal(0);
+ const [itemCount, setItemCount] = createSignal(1);
+ const [query, setQuery] = createSignal('');
+ const loadMore = vi.fn(async () => {
+ setLoading(true);
+ await Promise.resolve();
+ setLoading(false);
+ });
+ const bucket = {
+ id: 'documents' as const,
+ hasMore: () => true,
+ isLoadingMore: loading,
+ loadMore,
+ };
+ const dispose = createRoot((dispose) => {
+ const maybeLoad = createMentionPageLoader();
+ createEffect(() =>
+ maybeLoad({
+ bucket,
+ selectedIndex: selectedIndex(),
+ itemCount: itemCount(),
+ query: query(),
+ })
+ );
+ return dispose;
+ });
+ try {
+ await vi.waitFor(() => expect(loading()).toBe(false));
+ expect(loadMore).toHaveBeenCalledOnce();
+ setSelectedIndex(1);
+ await vi.waitFor(() => expect(loading()).toBe(false));
+ expect(loadMore).toHaveBeenCalledTimes(2);
+ setItemCount(2);
+ await vi.waitFor(() => expect(loading()).toBe(false));
+ expect(loadMore).toHaveBeenCalledTimes(3);
+ setQuery('new query');
+ await vi.waitFor(() => expect(loading()).toBe(false));
+ expect(loadMore).toHaveBeenCalledTimes(4);
+ } finally {
+ dispose();
+ }
+});
+
+it('allows another automatic load after leaving or changing category', () => {
+ const loadMore = vi.fn();
+ const maybeLoad = createMentionPageLoader();
+ const args = (id: MentionBucketId) => ({
+ bucket: { id, hasMore: () => true, loadMore },
+ query: '',
+ selectedIndex: 0,
+ itemCount: 2,
+ });
+ maybeLoad(args('documents'));
+ maybeLoad(args('documents'));
+ expect(loadMore).toHaveBeenCalledOnce();
+ maybeLoad(args('channels'));
+ expect(loadMore).toHaveBeenCalledTimes(2);
+ maybeLoad({ ...args('channels'), bucket: undefined });
+ maybeLoad(args('channels'));
+ expect(loadMore).toHaveBeenCalledTimes(3);
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/createMentionPageLoader.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/createMentionPageLoader.ts
new file mode 100644
index 0000000000..44f2e275a4
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/createMentionPageLoader.ts
@@ -0,0 +1,44 @@
+import type { BucketConfig } from '../MentionsMenuController';
+
+type Frontier = {
+ bucketId: string;
+ query: string;
+ selectedIndex: number;
+ itemCount: number;
+};
+
+/** Don't restart an exhausted scan just because its loading flag flips back.
+ * A new selection, query, category or visible row count allows another request. */
+export function createMentionPageLoader() {
+ let lastRequested: Frontier | undefined;
+ return (input: {
+ bucket?: Pick<
+ BucketConfig,
+ 'id' | 'hasMore' | 'isLoadingMore' | 'loadMore'
+ >;
+ query: string;
+ selectedIndex: number;
+ itemCount: number;
+ }) => {
+ const { bucket, query, selectedIndex, itemCount } = input;
+ if (!bucket) {
+ lastRequested = undefined;
+ return;
+ }
+ if (
+ selectedIndex < itemCount - 5 ||
+ !bucket.hasMore?.() ||
+ bucket.isLoadingMore?.()
+ )
+ return;
+ if (
+ lastRequested?.bucketId === bucket.id &&
+ lastRequested.query === query &&
+ lastRequested.selectedIndex === selectedIndex &&
+ lastRequested.itemCount === itemCount
+ )
+ return;
+ lastRequested = { bucketId: bucket.id, query, selectedIndex, itemCount };
+ void bucket.loadMore?.();
+ };
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.test.ts
new file mode 100644
index 0000000000..f425160c98
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.test.ts
@@ -0,0 +1,32 @@
+import { createRoot } from 'solid-js';
+import { expect, it, vi } from 'vitest';
+import { useEntityMention } from './useEntityMention';
+
+const list = vi.hoisted(() => ({
+ items: () => [],
+ totalCount: () => 50,
+ hasMore: () => true,
+ isLoading: () => false,
+ isLoadingMore: () => true,
+ loadMore: vi.fn(),
+}));
+vi.mock('@core/context/quickAccess', () => ({
+ useQuickAccess: () => ({
+ useList: () => list,
+ usesRecordSelection: () => false,
+ usesSearchProjection: () => true,
+ isLoading: () => false,
+ }),
+}));
+
+it('exposes pagination from search projections, not just legacy record selection', async () => {
+ const { mention, dispose } = createRoot((dispose) => ({
+ mention: useEntityMention({ buckets: ['note'], searchTerm: () => '' }),
+ dispose,
+ }));
+ expect(mention.hasMore()).toBe(true);
+ expect(mention.isLoadingMore()).toBe(true);
+ await mention.loadMore();
+ expect(list.loadMore).toHaveBeenCalledOnce();
+ dispose();
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts
index 52378a99e7..b993ca6ffd 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts
@@ -45,13 +45,12 @@ export function useEntityMention(
entities,
totalCount: () =>
usesRankedList() ? entityList.totalCount() : entities().length,
- hasMore: () => quickAccess.usesRecordSelection() && entityList.hasMore(),
+ hasMore: () => usesRankedList() && entityList.hasMore(),
isLoading: () =>
usesRankedList() ? entityList.isLoading() : quickAccess.isLoading(),
- isLoadingMore: () =>
- quickAccess.usesRecordSelection() && entityList.isLoadingMore(),
+ isLoadingMore: () => usesRankedList() && entityList.isLoadingMore(),
loadMore: async () => {
- if (quickAccess.usesRecordSelection()) await entityList.loadMore();
+ if (usesRankedList()) await entityList.loadMore();
},
};
}
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
new file mode 100644
index 0000000000..da89f98198
--- /dev/null
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
@@ -0,0 +1,203 @@
+import type { CacheChangeOptions } from '@graphql-cache/host/types';
+import type {
+ SearchCacheArgs,
+ SearchCachePage,
+ SearchDocumentWire,
+} from '@graphql-cache/index';
+import type { HistoryItem } from '@queries/history/types';
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MAX_BROWSE_PAGES_PER_LOAD } from './projected-list';
+import { createQuickAccessValue } from './QuickAccessSource';
+import type { QuickAccessContextValue } from './types';
+
+const mocks = vi.hoisted(() => ({
+ search: vi.fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>(),
+ history: [] as HistoryItem[],
+ changed: undefined as (() => void) | undefined,
+ unsubscribe: vi.fn(),
+ channelRefetch: vi.fn(),
+ onCacheChanged: vi.fn(),
+}));
+vi.mock('@core/constant/allBlocks', () => ({
+ itemToSafeName: (item: { name: string }) => item.name,
+}));
+vi.mock('@core/context/channels', () => ({
+ useChannelsContext: () => ({ channels: () => [], isLoading: () => false }),
+ useDmActivityByUserId: () => () => new Map(),
+}));
+vi.mock('@core/user', () => ({
+ useContacts: () => () => [],
+ useIsConnectedSecondaryInbox: () => () => false,
+}));
+vi.mock('@queries/channel/channels', () => ({
+ useCachedGraphqlChannelsQuery: () => ({
+ data: [],
+ isLoading: false,
+ refetch: mocks.channelRefetch,
+ }),
+}));
+vi.mock('@queries/channel/graphql', () => ({
+ materializeCachedGraphqlChannels: async () => [],
+}));
+vi.mock('@queries/gate', () => ({ queryReadyGate: () => true }));
+vi.mock('@queries/history/history', () => ({
+ useHistoryQuery: () => ({
+ data: mocks.history,
+ isLoading: false,
+ refetch: vi.fn(),
+ }),
+}));
+vi.mock('@queries/history/graphql', () => ({
+ materializeCachedGraphqlHistoryItems: async (
+ _host: unknown,
+ documents: SearchDocumentWire[]
+ ): Promise<HistoryItem[]> =>
+ documents.map((document) => ({
+ id: document.recordKey.split(':')[1],
+ type: 'document',
+ fileType: 'md',
+ name: document.searchText,
+ ownerId: 'owner',
+ })),
+}));
+vi.mock('@queries/soup/quick-access-agent-sessions', () => ({
+ useQuickAccessAgentSessionsQuery: () => ({ query: {}, sessions: () => [] }),
+}));
+vi.mock('@queries/soup/quick-access-crm-companies', () => ({
+ useQuickAccessCrmCompaniesQuery: () => ({ query: {}, companies: () => [] }),
+}));
+vi.mock('@queries/soup/quick-access-skills', () => ({
+ useQuickAccessSkillsQuery: () => ({ query: {}, skills: () => [] }),
+}));
+vi.mock('@queries/soup/quick-access-snippets', () => ({
+ useQuickAccessSnippetsQuery: () => ({ query: {}, snippets: () => [] }),
+}));
+vi.mock('@queries/soup/recently-viewed', () => ({
+ useRecentlyViewedSoupQuery: () => ({ data: [] }),
+}));
+vi.mock('@queries/storage/instructions-md', () => ({
+ useInstructionsMdIdQuery: () => ({ data: undefined }),
+}));
+vi.mock('@service-storage/util/filename', () => ({
+ formatDocumentName: (name: string) => name,
+}));
+vi.mock('@service-storage/graphql-soup', () => ({
+ getGraphqlSoupCacheHost: () => ({
+ search: mocks.search,
+ onCacheChanged: mocks.onCacheChanged,
+ }),
+}));
+
+let dispose: (() => void) | undefined;
+function setup<T>(fn: (source: QuickAccessContextValue) => T): T {
+ return createRoot((cleanup) => {
+ dispose = cleanup;
+ return fn(createQuickAccessValue());
+ });
+}
+function page(start: number, count: number, more = false): SearchCachePage {
+ const documents: SearchDocumentWire[] = Array.from(
+ { length: count },
+ (_, i) => ({
+ profile: 'quick-access-v1',
+ recordKey: `GraphqlSoupDocument:${start + i}`,
+ bucket: 'note',
+ searchText: `Document ${start + i}`,
+ timestampMs: 1,
+ sourceHash: 'hash',
+ })
+ );
+ return {
+ documents,
+ nextCursor: more
+ ? {
+ recordKey: `GraphqlSoupDocument:${start + count - 1}`,
+ timestampMs: 1,
+ }
+ : null,
+ };
+}
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.history = [];
+ mocks.search.mockReset().mockResolvedValue(page(0, 0));
+ mocks.onCacheChanged.mockImplementation(
+ (callback: () => void, _options: CacheChangeOptions) => {
+ mocks.changed = callback;
+ return mocks.unsubscribe;
+ }
+ );
+});
+afterEach(() => dispose?.());
+
+describe('Quick Access source integration', () => {
+ it('updates an open list on opted-in hydration notifications without changing its query', async () => {
+ const list = setup((source) => source.useList({ buckets: ['note'] }));
+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));
+ expect(list.items()).toEqual([]);
+ expect(mocks.onCacheChanged).toHaveBeenCalledWith(expect.any(Function), {
+ includeHydration: true,
+ });
+ mocks.search.mockResolvedValue(page(0, 1));
+ mocks.changed?.();
+ await vi.waitFor(() => expect(list.items()).toHaveLength(1));
+ expect(mocks.channelRefetch).toHaveBeenCalledOnce();
+ dispose?.();
+ expect(mocks.unsubscribe).toHaveBeenCalledOnce();
+ });
+
+ it('uses one shared scan budget when hundreds of projected rows duplicate history', async () => {
+ mocks.history = Array.from({ length: 500 }, (_, i) => ({
+ id: String(i),
+ type: 'document',
+ name: `Document ${i}`,
+ fileType: 'md',
+ ownerId: 'owner',
+ }));
+ mocks.search.mockImplementation(async (args) => {
+ const start = args.cursor
+ ? Number(args.cursor.recordKey.split(':')[1]) + 1
+ : 0;
+ const count = Math.min(50, 501 - start);
+ return page(start, count, start + count < 501);
+ });
+ const list = setup((source) => source.useList({ buckets: ['note'] }));
+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));
+ expect(list.items()).toHaveLength(500);
+ expect(mocks.search).toHaveBeenCalledTimes(1);
+ await list.loadMore();
+ expect(mocks.search).toHaveBeenCalledTimes(1 + MAX_BROWSE_PAGES_PER_LOAD);
+ expect(list.items()).toHaveLength(500);
+ expect(list.hasMore()).toBe(true);
+ await list.loadMore();
+ expect(mocks.search).toHaveBeenCalledTimes(
+ 1 + MAX_BROWSE_PAGES_PER_LOAD * 2
+ );
+ await list.loadMore();
+ expect(list.items()).toHaveLength(501);
+ expect(list.hasMore()).toBe(false);
+ });
+
+ it('loads through pages duplicated in local history until list height can grow', async () => {
+ mocks.history = Array.from({ length: 80 }, (_, i) => ({
+ id: String(i),
+ type: 'document',
+ name: `Document ${i}`,
+ fileType: 'md',
+ ownerId: 'owner',
+ }));
+ mocks.search
+ .mockResolvedValueOnce(page(0, 50, true))
+ .mockResolvedValueOnce(page(50, 30, true))
+ .mockResolvedValueOnce(page(80, 1));
+ const list = setup((source) => source.useList({ buckets: ['note'] }));
+ await vi.waitFor(() => expect(list.hasMore()).toBe(true));
+ expect(list.items()).toHaveLength(80);
+ await list.loadMore();
+ expect(list.items()).toHaveLength(81);
+ expect(list.totalCount()).toBe(81);
+ expect(list.hasMore()).toBe(false);
+ expect(mocks.search).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
index 4836af15af..df40daafa8 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
@@ -33,9 +33,11 @@ import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';
import { getGraphqlSoupCacheHost } from '@service-storage/graphql-soup';
import { formatDocumentName } from '@service-storage/util/filename';
import { createLazyMemo } from '@solid-primitives/memo';
+import { leadingAndTrailing, throttle } from '@solid-primitives/scheduled';
import { toDate } from 'date-fns';
import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js';
import { searchQuickAccessItems } from './entity-search';
+import { createProjectedList } from './projected-list';
import type {
Bucket,
BucketCombination,
@@ -318,11 +320,24 @@ export function createQuickAccessValue(): QuickAccessContextValue {
const cacheHost = graphqlCacheHost?.disabled ? undefined : graphqlCacheHost;
const [cacheRevision, setCacheRevision] = createSignal(0);
const cachedChannelsQuery = useCachedGraphqlChannelsQuery(cacheHost);
- const unsubscribeCacheChanges = cacheHost?.onCacheChanged(() => {
- setCacheRevision((revision) => revision + 1);
- void cachedChannelsQuery.refetch();
+ const refreshCachedLists = leadingAndTrailing(
+ throttle,
+ () => {
+ setCacheRevision((revision) => revision + 1);
+ void cachedChannelsQuery.refetch();
+ },
+ 250
+ );
+ const unsubscribeCacheChanges = cacheHost?.onCacheChanged(
+ refreshCachedLists,
+ {
+ includeHydration: true,
+ }
+ );
+ onCleanup(() => {
+ unsubscribeCacheChanges?.();
+ refreshCachedLists.clear();
});
- onCleanup(() => unsubscribeCacheChanges?.());
const instructionsIdQuery = useInstructionsMdIdQuery();
const { query: crmCompaniesQuery, companies: crmCompaniesAccessor } =
useQuickAccessCrmCompaniesQuery();
@@ -879,131 +894,88 @@ export function createQuickAccessValue(): QuickAccessContextValue {
return resolveEntries(indices);
});
- const [projectedItems, setProjectedItems] = createSignal<
- | {
- recordKeys: string[];
- materialized: Map<string, QuickAccessItem>;
- }
- | undefined
- >(undefined);
- if (options && cacheHost) {
- let generation = 0;
- onCleanup(() => {
- generation += 1;
- });
- createEffect(() => {
- cacheRevision();
- const enabled = options.enabled?.() !== false;
- const query = options.searchTerm?.() ?? '';
- const currentGeneration = ++generation;
- if (!enabled) {
- setProjectedItems(undefined);
- return;
- }
- void (async () => {
- try {
- const page = await cacheHost.search({
- profile: 'quick-access-v1',
- buckets,
- query,
- limit: query.trim() ? 500 : 50,
- });
- const missingDocuments = page.documents.filter(({ recordKey }) => {
- const separator = recordKey.indexOf(':');
- const id =
- separator < 0 ? recordKey : recordKey.slice(separator + 1);
- return !itemCache.has(id);
- });
- const [historyItems, cachedChannelItems] = await Promise.all([
- materializeCachedGraphqlHistoryItems(cacheHost, missingDocuments),
- materializeCachedGraphqlChannels(cacheHost, missingDocuments),
- ]);
- if (currentGeneration !== generation) return;
- const materializedHistoryItems = new Map(
- historyItems.map((item) => [item.id, item] as const)
- );
- const materializedChannelItems = new Map(
- cachedChannelItems.map((item) => [item.id, item] as const)
- );
- const recordKeys: string[] = [];
- const materialized = new Map<string, QuickAccessItem>();
- const seen = new Set<string>();
- for (const document of page.documents) {
- const separator = document.recordKey.indexOf(':');
- const id =
- separator < 0
- ? document.recordKey
- : document.recordKey.slice(separator + 1);
- if (seen.has(id)) continue;
- if (itemCache.get(id)?.item) {
- seen.add(id);
- recordKeys.push(document.recordKey);
- continue;
- }
- const historyItem = materializedHistoryItems.get(id);
- const cachedChannel = materializedChannelItems.get(id);
- let item: QuickAccessItem | undefined;
- if (historyItem) {
- const entity = historyItemToEntity(historyItem);
- item = {
- kind: 'entity',
- id,
- bucket: getBucketForHistoryItem(historyItem),
- searchText: getEntitySearchText(entity),
- sortTimestamp: document.timestampMs,
- timestamps: {
- updatedAt: historyItem.updatedAt,
- createdAt: historyItem.createdAt,
- },
- data: entity,
- };
- } else if (cachedChannel) {
- item = channelToQuickAccessItem(
- cachedChannel,
- document.timestampMs
- );
- }
- if (!item) continue;
- seen.add(id);
- recordKeys.push(document.recordKey);
- materialized.set(id, item);
- }
- setProjectedItems({ recordKeys, materialized });
- } catch {
- if (currentGeneration === generation) {
- setProjectedItems({ recordKeys: [], materialized: new Map() });
- }
- }
- })();
- });
- }
+ const localItems = createLazyMemo(() =>
+ options
+ ? searchQuickAccessItems(baseList(), options.searchTerm?.() ?? '')
+ : baseList()
+ );
+ const projected =
+ options && cacheHost
+ ? createProjectedList<QuickAccessItem>({
+ host: cacheHost,
+ buckets,
+ revision: cacheRevision,
+ searchTerm: options.searchTerm,
+ enabled: options.enabled,
+ existingItems: localItems,
+ materialize: async (documents) => {
+ const idOf = (recordKey: string) =>
+ recordKey.slice(recordKey.indexOf(':') + 1);
+ const missing = documents.filter(
+ ({ recordKey }) => !itemCache.has(idOf(recordKey))
+ );
+ const [historyItems, cachedChannelItems] = await Promise.all([
+ materializeCachedGraphqlHistoryItems(cacheHost, missing),
+ materializeCachedGraphqlChannels(cacheHost, missing),
+ ]);
+ const historyById = new Map(
+ historyItems.map((item) => [item.id, item])
+ );
+ const channelsById = new Map(
+ cachedChannelItems.map((item) => [item.id, item])
+ );
+ return documents.flatMap((document): QuickAccessItem[] => {
+ const id = idOf(document.recordKey);
+ const cached = itemCache.get(id)?.item;
+ if (cached) return [cached];
+ const historyItem = historyById.get(id);
+ if (historyItem) {
+ const entity = historyItemToEntity(historyItem);
+ return [
+ {
+ kind: 'entity',
+ id,
+ bucket: getBucketForHistoryItem(historyItem),
+ searchText: getEntitySearchText(entity),
+ sortTimestamp: document.timestampMs,
+ timestamps: {
+ updatedAt: historyItem.updatedAt,
+ createdAt: historyItem.createdAt,
+ },
+ data: entity,
+ },
+ ];
+ }
+ const channel = channelsById.get(id);
+ return channel
+ ? [channelToQuickAccessItem(channel, document.timestampMs)]
+ : [];
+ });
+ },
+ })
+ : undefined;
const list = createLazyMemo(() => {
- const base = baseList();
- if (!options) return base;
- const local = searchQuickAccessItems(base, options.searchTerm?.() ?? '');
- const projected = projectedItems();
- if (!projected) return local;
+ const local = localItems();
+ if (!projected || options?.enabled?.() === false) return local;
// Search describes cached contents, not corpus completeness. Preserve
- // projection rank, then append server/local candidates as fallback.
- const ranked = projected.recordKeys.flatMap((recordKey) => {
- const separator = recordKey.indexOf(':');
- const key = separator < 0 ? recordKey : recordKey.slice(separator + 1);
- const item =
- itemCache.get(key)?.item ?? projected.materialized.get(key);
- return item ? [item] : [];
- });
+ // projection rank, then append candidates from the existing local sources.
+ const ranked = projected
+ .items()
+ .map((item) => itemCache.get(item.id)?.item ?? item);
const seen = new Set(ranked.map((item) => item.id));
return ranked.concat(local.filter((item) => !seen.has(item.id)));
});
return {
items: list,
totalCount: () => list().length,
- hasMore: () => false,
- isLoading: () => false,
- isLoadingMore: () => false,
- loadMore: async () => undefined,
+ hasMore: () => projected?.hasMore() ?? false,
+ isLoading: () => projected?.isLoading() ?? false,
+ isLoadingMore: () => projected?.isLoadingMore() ?? false,
+ loadMore: async () => {
+ await projected?.loadMore();
+ },
};
}) as QuickAccessContextValue['useList'];
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.ts
new file mode 100644
index 0000000000..fdf7943b4b
--- /dev/null
+++ b/apps/web/src/lib/core/context/quickAccess/projected-list.test.ts
@@ -0,0 +1,308 @@
+import type {
+ SearchCacheArgs,
+ SearchCachePage,
+ SearchDocumentWire,
+} from '@graphql-cache/index';
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ createProjectedList,
+ MAX_BROWSE_PAGES_PER_LOAD,
+} from './projected-list';
+import { exclude } from './types';
+
+const cleanups: (() => void)[] = [];
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) cleanup();
+});
+
+function root<T>(fn: () => T): T {
+ return createRoot((dispose) => {
+ cleanups.push(dispose);
+ return fn();
+ });
+}
+function document(id: string, bucket = 'note'): SearchDocumentWire {
+ return {
+ profile: 'quick-access-v1',
+ recordKey: `GraphqlSoupDocument:${id}`,
+ bucket,
+ searchText: id,
+ timestampMs: 1,
+ sourceHash: 'hash',
+ };
+}
+function page(ids: string[], more = false): SearchCachePage {
+ return {
+ documents: ids.map((id) => document(id)),
+ nextCursor: more
+ ? { recordKey: `GraphqlSoupDocument:${ids.at(-1)}`, timestampMs: 1 }
+ : null,
+ };
+}
+const materialize = async (documents: SearchDocumentWire[]) =>
+ documents.map((document) => ({ id: document.recordKey }));
+const ids = (count: number, start = 0) =>
+ Array.from({ length: count }, (_, i) => `${start + i}`);
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+describe('Quick Access local projection', () => {
+ it('follows the local browse cursor, deduplicates hits, and stops at the last page', async () => {
+ const search = vi
+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()
+ .mockResolvedValueOnce(page(ids(50), true))
+ .mockResolvedValueOnce(page(['49', ...ids(30, 50)]));
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['note'],
+ revision: () => 0,
+ materialize,
+ })
+ );
+ await vi.waitFor(() => expect(list.items()).toHaveLength(50));
+ expect(list.hasMore()).toBe(true);
+ await list.loadMore();
+ expect(search.mock.calls[1][0]).toMatchObject({
+ query: '',
+ limit: 50,
+ cursor: { recordKey: 'GraphqlSoupDocument:49', timestampMs: 1 },
+ });
+ expect(list.items()).toHaveLength(80);
+ expect(list.hasMore()).toBe(false);
+ await list.loadMore();
+ expect(search).toHaveBeenCalledTimes(2);
+ });
+
+ it('replays the loaded window after hydration, retaining visible rows while it refreshes', async () => {
+ const [revision, setRevision] = createSignal(0);
+ const refresh = deferred<SearchCachePage>();
+ const search = vi
+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()
+ .mockResolvedValueOnce(page(['one'], true))
+ .mockResolvedValueOnce(page(['two']))
+ .mockReturnValueOnce(refresh.promise)
+ .mockResolvedValueOnce(page(['two', 'newly-hydrated']));
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['note'],
+ revision,
+ materialize,
+ })
+ );
+ await vi.waitFor(() => expect(list.hasMore()).toBe(true));
+ await list.loadMore();
+ setRevision(1);
+ expect(list.items()).toHaveLength(2);
+ refresh.resolve(page(['one'], true));
+ await vi.waitFor(() => expect(list.items()).toHaveLength(3));
+ expect(search).toHaveBeenCalledTimes(4);
+ });
+
+ it('searches only materializable buckets before applying the limit', async () => {
+ const emailHits = Array.from({ length: 500 }, (_, i) =>
+ document(`email-${i}`, 'email')
+ );
+ const search = vi.fn(
+ async (args: SearchCacheArgs): Promise<SearchCachePage> => ({
+ documents: [...emailHits, document('target')]
+ .filter((hit) => args.buckets?.includes(hit.bucket))
+ .slice(0, args.limit),
+ nextCursor: null,
+ })
+ );
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: exclude('person'),
+ revision: () => 0,
+ searchTerm: () => 'target',
+ materialize,
+ })
+ );
+ await vi.waitFor(() =>
+ expect(list.items()).toEqual([{ id: 'GraphqlSoupDocument:target' }])
+ );
+ expect(search.mock.calls[0][0].buckets).not.toEqual(
+ expect.arrayContaining(['email'])
+ );
+ expect(search.mock.calls[0][0].buckets).not.toEqual(
+ expect.arrayContaining(['crm_company'])
+ );
+ expect(search.mock.calls[0][0].buckets).not.toEqual(
+ expect.arrayContaining(['agent_session'])
+ );
+ });
+
+ it('never interprets an unsupported-only list as an all-bucket search', async () => {
+ const search = vi.fn();
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['email', 'person', 'crm_company', 'agent_session'],
+ revision: () => 0,
+ materialize,
+ })
+ );
+ expect(list.items()).toEqual([]);
+ expect(list.hasMore()).toBe(false);
+ expect(search).not.toHaveBeenCalled();
+ });
+
+ it('continues past incomplete or duplicate pages instead of stranding scroll pagination', async () => {
+ const search = vi
+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()
+ .mockResolvedValueOnce(page(['incomplete'], true))
+ .mockResolvedValueOnce(page(['one'], true))
+ .mockResolvedValueOnce(page(['one'], true))
+ .mockResolvedValueOnce(page(['two']));
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['note'],
+ revision: () => 0,
+ materialize: async (documents) =>
+ materialize(
+ documents.filter((doc) => !doc.recordKey.endsWith('incomplete'))
+ ),
+ })
+ );
+ await vi.waitFor(() => expect(list.items()).toHaveLength(1));
+ await list.loadMore();
+ expect(list.items()).toHaveLength(2);
+ expect(search).toHaveBeenCalledTimes(4);
+ });
+
+ it('bounds incomplete scans, preserves the cursor, and resumes on the next action', async () => {
+ const [revision, setRevision] = createSignal(0);
+ const search = vi.fn(
+ async (args: SearchCacheArgs): Promise<SearchCachePage> => {
+ const next = args.cursor
+ ? Number(args.cursor.recordKey.split(':')[1]) + 1
+ : 1;
+ return page([String(next)], true);
+ }
+ );
+ const project = vi.fn(materialize).mockResolvedValue([]);
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['note'],
+ revision,
+ materialize: project,
+ })
+ );
+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));
+ expect(search).toHaveBeenCalledTimes(MAX_BROWSE_PAGES_PER_LOAD);
+ expect(list.items()).toEqual([]);
+ expect(list.hasMore()).toBe(true);
+ setRevision(1);
+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));
+ expect(search).toHaveBeenCalledTimes(MAX_BROWSE_PAGES_PER_LOAD * 2);
+ await list.loadMore();
+ expect(search).toHaveBeenCalledTimes(MAX_BROWSE_PAGES_PER_LOAD * 3);
+ expect(list.hasMore()).toBe(true);
+ project.mockImplementation(materialize);
+ await list.loadMore();
+ expect(search.mock.calls.at(-1)?.[0].cursor?.recordKey).toBe(
+ `GraphqlSoupDocument:${MAX_BROWSE_PAGES_PER_LOAD * 2}`
+ );
+ expect(list.items()).toEqual([
+ { id: `GraphqlSoupDocument:${MAX_BROWSE_PAGES_PER_LOAD * 2 + 1}` },
+ ]);
+ });
+
+ it('drops an obsolete in-flight page when the query changes', async () => {
+ const [query, setQuery] = createSignal('');
+ const obsolete = deferred<SearchCachePage>();
+ const search = vi
+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()
+ .mockResolvedValueOnce(page(['old'], true))
+ .mockReturnValueOnce(obsolete.promise)
+ .mockResolvedValueOnce(page(['new']));
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['note'],
+ revision: () => 0,
+ searchTerm: query,
+ materialize,
+ })
+ );
+ await vi.waitFor(() => expect(list.items()).toHaveLength(1));
+ const loading = list.loadMore();
+ setQuery('new');
+ expect(list.items()).toEqual([]);
+ await vi.waitFor(() =>
+ expect(list.items()).toEqual([{ id: 'GraphqlSoupDocument:new' }])
+ );
+ obsolete.resolve(page(['obsolete']));
+ await loading;
+ expect(list.items()).toEqual([{ id: 'GraphqlSoupDocument:new' }]);
+ expect(search.mock.calls[2][0]).toMatchObject({ query: 'new', limit: 500 });
+ expect(search.mock.calls[2][0].cursor).toBeUndefined();
+ });
+
+ it('coalesces simultaneous loadMore calls and retains rows on failure', async () => {
+ const next = deferred<SearchCachePage>();
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const search = vi
+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()
+ .mockResolvedValueOnce(page(['one'], true))
+ .mockReturnValueOnce(next.promise)
+ .mockRejectedValueOnce(new Error('cache unavailable'))
+ .mockResolvedValueOnce(page(['three']));
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['note'],
+ revision: () => 0,
+ materialize,
+ })
+ );
+ await vi.waitFor(() => expect(list.hasMore()).toBe(true));
+ const pending = list.loadMore();
+ expect(list.isLoadingMore()).toBe(true);
+ await list.loadMore();
+ expect(search).toHaveBeenCalledTimes(2);
+ next.resolve(page(['two'], true));
+ await pending;
+ await list.loadMore();
+ expect(list.items()).toHaveLength(2);
+ expect(list.isLoadingMore()).toBe(false);
+ expect(list.hasMore()).toBe(false);
+ await list.loadMore();
+ expect(list.items()).toHaveLength(3);
+ warning.mockRestore();
+ });
+
+ it('disabling and disposing prevent late results from populating a list', async () => {
+ const [enabled, setEnabled] = createSignal(true);
+ const pending = deferred<SearchCachePage>();
+ const search = vi.fn().mockReturnValue(pending.promise);
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['note'],
+ revision: () => 0,
+ enabled,
+ materialize,
+ })
+ );
+ setEnabled(false);
+ pending.resolve(page(['late']));
+ await pending.promise;
+ expect(list.items()).toEqual([]);
+ expect(list.isLoading()).toBe(false);
+ expect(list.hasMore()).toBe(false);
+ cleanups.splice(0).forEach((cleanup) => cleanup());
+ });
+});
diff --git a/apps/web/src/lib/core/context/quickAccess/projected-list.ts b/apps/web/src/lib/core/context/quickAccess/projected-list.ts
new file mode 100644
index 0000000000..2d56f80d28
--- /dev/null
+++ b/apps/web/src/lib/core/context/quickAccess/projected-list.ts
@@ -0,0 +1,167 @@
+import type {
+ CacheHost,
+ SearchCursor,
+ SearchDocumentWire,
+} from '@graphql-cache/index';
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ onCleanup,
+ untrack,
+} from 'solid-js';
+import type { Bucket } from './types';
+
+// Only these buckets can be materialized from cache hits. Other Quick Access
+// sources (contacts, CRM, sessions) are merged locally, after the search limit.
+const PROJECTED_BUCKETS: ReadonlySet<Bucket> = new Set([
+ 'document',
+ 'note',
+ 'task',
+ 'snippet',
+ 'skill',
+ 'chat',
+ 'project',
+ 'channel',
+ 'dm',
+]);
+const BROWSE_PAGE_SIZE = 50;
+const SEARCH_LIMIT = 500;
+/** Maximum cache pages inspected by one initial browse or load-more action. */
+export const MAX_BROWSE_PAGES_PER_LOAD = 4;
+
+type Request = {
+ query: string;
+ pages: number;
+ cursor?: SearchCursor;
+ busy: boolean;
+};
+
+/** A paginated, cache-only search. Refreshes replay the loaded browse window
+ * rather than shrinking a scrolled list back to its first page. */
+export function createProjectedList<T extends { id: string }>(options: {
+ host: Pick<CacheHost, 'search'>;
+ buckets: readonly Bucket[];
+ revision: Accessor<number>;
+ searchTerm?: Accessor<string>;
+ enabled?: Accessor<boolean>;
+ /** Visible fallback rows; duplicates do not grow the combined menu. */
+ existingItems?: Accessor<readonly T[]>;
+ materialize: (documents: SearchDocumentWire[]) => Promise<T[]>;
+}) {
+ const buckets =
+ options.buckets.length === 0
+ ? [...PROJECTED_BUCKETS]
+ : options.buckets.filter((bucket) => PROJECTED_BUCKETS.has(bucket));
+ const [items, setItems] = createSignal<T[]>([]);
+ const [hasMore, setHasMore] = createSignal(false);
+ const [loading, setLoading] = createSignal<'idle' | 'initial' | 'more'>(
+ 'idle'
+ );
+ let current: Request | undefined;
+ onCleanup(() => {
+ current = undefined;
+ });
+
+ const fetchPages = async (
+ request: Request,
+ pageCount: number,
+ append: boolean
+ ) => {
+ request.busy = true;
+ setLoading(append ? 'more' : 'initial');
+ const previous = append ? untrack(items) : [];
+ const merged = new Map(previous.map((item) => [item.id, item]));
+ const visibleIds = new Set([
+ ...merged.keys(),
+ ...(append
+ ? untrack(() => options.existingItems?.() ?? []).map((item) => item.id)
+ : []),
+ ]);
+ // Refreshes may replay a window the user already loaded, but never scan
+ // beyond that window without the same bounded budget as a new browse.
+ const pageBudget = Math.max(pageCount, MAX_BROWSE_PAGES_PER_LOAD);
+ let fetchedPages = 0;
+ let foundNewRow = false;
+ let cursor = append ? request.cursor : undefined;
+ let pages = append ? request.pages : 0;
+ try {
+ do {
+ const page = await options.host.search({
+ profile: 'quick-access-v1',
+ buckets,
+ query: request.query,
+ limit: request.query ? SEARCH_LIMIT : BROWSE_PAGE_SIZE,
+ ...(cursor ? { cursor } : {}),
+ });
+ if (current !== request) return;
+ const materialized = await options.materialize(page.documents);
+ if (current !== request) return;
+ for (const item of materialized) {
+ merged.set(item.id, item);
+ if (!visibleIds.has(item.id)) foundNewRow = true;
+ }
+ cursor = page.nextCursor ?? undefined;
+ pages += 1;
+ fetchedPages += 1;
+ pageCount -= 1;
+ // Skip incomplete/duplicate pages only within this action's budget.
+ // Retain the continuation even if no visible row was found.
+ } while (
+ cursor &&
+ fetchedPages < pageBudget &&
+ (pageCount > 0 || !foundNewRow)
+ );
+ request.cursor = cursor;
+ request.pages = pages;
+ setItems([...merged.values()]);
+ setHasMore(cursor !== undefined);
+ } catch (error) {
+ if (current !== request) return;
+ // Keep visible rows. Suppress automatic end-of-list retry loops; an
+ // explicit loadMore or the next revision/query change can retry locally.
+ setHasMore(false);
+ console.warn('Quick Access cache search failed', error);
+ } finally {
+ if (current === request) {
+ request.busy = false;
+ setLoading('idle');
+ }
+ }
+ };
+
+ createEffect(() => {
+ options.revision();
+ const query = options.searchTerm?.().trim() ?? '';
+ const enabled = options.enabled?.() !== false && buckets.length > 0;
+ const previous = current;
+ current = undefined;
+ setHasMore(false);
+ if (!enabled) {
+ setItems([]);
+ setLoading('idle');
+ return;
+ }
+ const sameQuery = previous?.query === query;
+ if (!sameQuery) setItems([]);
+ const request: Request = {
+ query,
+ pages: sameQuery ? (previous?.pages ?? 1) : 1,
+ busy: false,
+ };
+ current = request;
+ void fetchPages(request, request.pages, false);
+ });
+
+ return {
+ items,
+ hasMore,
+ isLoading: () => loading() === 'initial',
+ isLoadingMore: () => loading() === 'more',
+ loadMore: async () => {
+ const request = current;
+ if (!request || request.busy || !request.cursor) return;
+ await fetchPages(request, 1, true);
+ },
+ };
+}
diff --git a/apps/web/src/lib/core/context/quickAccess/types.ts b/apps/web/src/lib/core/context/quickAccess/types.ts
index 6657a44423..a0701e1b56 100644
--- a/apps/web/src/lib/core/context/quickAccess/types.ts
+++ b/apps/web/src/lib/core/context/quickAccess/types.ts
@@ -149,7 +149,7 @@ export type ItemsForBuckets<Buckets extends Bucket[]> = Buckets extends [
export type QuickAccessList<T extends QuickAccessItem = QuickAccessItem> = {
items: Accessor<T[]>;
- /** Total matching items, including pages not loaded yet. */
+ /** Number of loaded matching items. Check hasMore for additional cached pages. */
totalCount: Accessor<number>;
hasMore: Accessor<boolean>;
isLoading: Accessor<boolean>;
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index 9e6cb14846..c7ed61b57a 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -2,9 +2,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const invokeMock = vi.hoisted(() => vi.fn());
const listenMock = vi.hoisted(() => vi.fn());
+const emitMock = vi.hoisted(() => vi.fn());
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
-vi.mock('@tauri-apps/api/event', () => ({ listen: listenMock }));
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: listenMock,
+ emit: emitMock,
+}));
import {
type EntityFilterCacheArgs,
@@ -40,6 +44,7 @@ describe('createTauriCacheHost', () => {
vi.clearAllMocks();
eventCallbacks = new Map();
invokeMock.mockResolvedValue(null);
+ emitMock.mockResolvedValue(undefined);
listenMock.mockImplementation((event: string, cb: EventCallback) => {
eventCallbacks.set(event, cb);
return Promise.resolve(unlisten);
@@ -410,7 +415,12 @@ describe('createTauriCacheHost', () => {
it('returns only the native hydration projection', async () => {
const host = createTauriCacheHost({ scope: 'scope-1' });
- const hydration = { kind: 'data' as const, data: { cursor: 'next' } };
+ const hydration = {
+ kind: 'data' as const,
+ data: { cursor: 'next' },
+ revision: '1',
+ revisionAdvanced: true,
+ };
invokeMock.mockImplementation((command: string) =>
Promise.resolve(command === 'graphql_cache_hydrate' ? hydration : null)
);
@@ -422,6 +432,9 @@ describe('createTauriCacheHost', () => {
identity: 'user-1',
})
).resolves.toEqual(hydration);
+ expect(emitMock).toHaveBeenCalledWith('graphql-cache://cache-hydrated', {
+ revision: '1',
+ });
expect(invokeMock).toHaveBeenCalledWith('graphql_cache_hydrate', {
query: 'query Backfill { items @cacheOnly { id } cursor }',
operationName: undefined,
@@ -431,6 +444,112 @@ describe('createTauriCacheHost', () => {
});
});
+ it.each(['data', 'void'])(
+ 'skips native no-op hydration notifications (%s)',
+ async (kind) => {
+ const host = createTauriCacheHost({ scope: 'scope-1' });
+ const hydration = {
+ kind,
+ data: null,
+ revision: '5',
+ revisionAdvanced: false,
+ };
+ invokeMock.mockImplementation(async (command: string) =>
+ command === 'graphql_cache_hydrate' ? hydration : null
+ );
+ await expect(
+ host.hydrateQuery({ query: '{ x }', data: { x: 1 } })
+ ).resolves.toEqual(hydration);
+ expect(emitMock).not.toHaveBeenCalled();
+ host.dispose();
+ }
+ );
+
+ it('deduplicates repeated and out-of-order legacy revisions without an extra IPC read', async () => {
+ const host = createTauriCacheHost({ scope: 'scope-1' });
+ const revisions = [
+ '9007199254740993',
+ '9007199254740993',
+ '9007199254740992',
+ '9007199254740994',
+ ];
+ invokeMock.mockImplementation(async (command: string) =>
+ command === 'graphql_cache_hydrate'
+ ? { kind: 'void', revision: revisions.shift() }
+ : null
+ );
+ for (let i = 0; i < 4; i++)
+ await host.hydrateQuery({ query: '{ x }', data: { x: 1 } });
+ expect(emitMock.mock.calls).toEqual([
+ ['graphql-cache://cache-hydrated', { revision: '9007199254740993' }],
+ ['graphql-cache://cache-hydrated', { revision: '9007199254740994' }],
+ ]);
+ expect(invokeMock).not.toHaveBeenCalledWith(
+ 'graphql_cache_current_revision',
+ expect.anything()
+ );
+ host.dispose();
+ });
+
+ it.each(['cache-changed', 'cache-hydrated'])(
+ 'does not re-announce a legacy revision already observed via %s',
+ async (event) => {
+ const host = createTauriCacheHost({ scope: 'scope-1' });
+ eventCallbacks.get(`graphql-cache://${event}`)?.({
+ payload: { revision: '7' },
+ });
+ invokeMock.mockImplementation(async (command: string) =>
+ command === 'graphql_cache_hydrate'
+ ? { kind: 'void', revision: '7' }
+ : null
+ );
+ await host.hydrateQuery({ query: '{ x }', data: { x: 1 } });
+ expect(emitMock).not.toHaveBeenCalled();
+ host.dispose();
+ }
+ );
+
+ it('delivers cross-window hydration only to opted-in listeners', async () => {
+ const host = createTauriCacheHost({ scope: 'scope-1' });
+ const foreground = vi.fn();
+ const quickAccess = vi.fn();
+ const operations = vi.fn();
+ host.onCacheChanged(foreground);
+ host.onOpsAffected(operations);
+ const unsubscribe = host.onCacheChanged(quickAccess, {
+ includeHydration: true,
+ });
+ const hydrated = () =>
+ eventCallbacks.get('graphql-cache://cache-hydrated')?.({
+ payload: { revision: INITIAL_CACHE_REVISION },
+ });
+ hydrated();
+ expect(quickAccess).toHaveBeenCalledOnce();
+ expect(foreground).not.toHaveBeenCalled();
+ expect(operations).not.toHaveBeenCalled();
+ unsubscribe();
+ hydrated();
+ expect(quickAccess).toHaveBeenCalledOnce();
+ host.onCacheChanged(quickAccess, { includeHydration: true });
+ host.dispose();
+ hydrated();
+ expect(quickAccess).toHaveBeenCalledOnce();
+ });
+
+ it('does not fail a committed hydration when its notification fails', async () => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const host = createTauriCacheHost({ scope: 'scope-1' });
+ const hydration = { kind: 'void', revision: '1', revisionAdvanced: true };
+ invokeMock.mockResolvedValue(hydration);
+ emitMock.mockRejectedValueOnce(new Error('notification failed'));
+ await expect(
+ host.hydrateQuery({ query: '{ x }', data: { x: 1 } })
+ ).resolves.toEqual(hydration);
+ expect(emitMock).toHaveBeenCalledOnce();
+ warning.mockRestore();
+ host.dispose();
+ });
+
it('settles optimistic writes through the dedicated commands', async () => {
const host = createTauriCacheHost({ scope: 'scope-1' });
const optimistic = {
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
index e79c891fed..97a3df0de2 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -8,7 +8,7 @@
*/
import { invoke } from '@tauri-apps/api/core';
-import { listen, type UnlistenFn } from '@tauri-apps/api/event';
+import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event';
import type {
AffectedOperationsResult,
CachedQueryInstanceWire,
@@ -37,6 +37,7 @@ import {
validateRecordSelectionKeys,
} from '../protocol';
import type {
+ CacheChangeOptions,
CacheHost,
CacheReadArgs,
CacheWriteArgs,
@@ -50,6 +51,8 @@ import type {
const OPS_AFFECTED_EVENT = 'graphql-cache://ops-affected';
/** Keep in sync with `CACHE_CHANGED_EVENT` in the native plugin. */
const CACHE_CHANGED_EVENT = 'graphql-cache://cache-changed';
+// Published by the JS host after hydration, including on older native binaries.
+const CACHE_HYDRATED_EVENT = 'graphql-cache://cache-hydrated';
/** Keep in sync with `MUTATION_SETTLED_EVENT` in graphql_cache_plugin. */
const MUTATION_SETTLED_EVENT = 'graphql-cache://mutation-settled';
@@ -61,6 +64,9 @@ type OpsAffectedPayload = {
type CacheChangedPayload = { revision: string };
+// Older native binaries omit the advancement bit and still receive OTA JS.
+type NativeHydrationResult = HydrationResult & { revisionAdvanced?: boolean };
+
export interface TauriHostOptions {
scope: string;
hotCapacity?: number;
@@ -81,6 +87,7 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
const clientId = crypto.randomUUID();
const affectedSubscribers = new Set<(opKeys: number[]) => void>();
const cacheChangeSubscribers = new Set<(revision: CacheRevision) => void>();
+ const hydrationSubscribers = new Set<(revision: CacheRevision) => void>();
const settlementSubscribers = new Set<
(settlement: MutationSettlement) => void
>();
@@ -93,6 +100,16 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
// Keep this per host so a new native binary is probed again after restarting.
let entityFilterUnavailable = false;
+ // Revisions are monotonic for the native engine's lifetime. This also gates
+ // repeated no-op hydrations on older binaries without revisionAdvanced.
+ let latestObservedRevision = 0n;
+ function observeRevision(revision: CacheRevision): boolean {
+ const next = BigInt(revision);
+ if (next <= latestObservedRevision) return false;
+ latestObservedRevision = next;
+ return true;
+ }
+
function request<T>(
command: string,
args: Record<string, unknown>,
@@ -146,12 +163,34 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
const unlistenCacheChanges: Promise<UnlistenFn | undefined> =
listen<CacheChangedPayload>(CACHE_CHANGED_EVENT, (event) => {
const revision = parseCacheRevision(event.payload.revision);
+ observeRevision(revision);
for (const cb of cacheChangeSubscribers) cb(revision);
}).catch((error) => {
console.warn('graphql cache change listener failed', error);
return undefined;
});
+ async function listenForHydration(): Promise<UnlistenFn | undefined> {
+ try {
+ return await listen<CacheChangedPayload>(
+ CACHE_HYDRATED_EVENT,
+ (event) => {
+ const revision = parseCacheRevision(event.payload.revision);
+ observeRevision(revision);
+ for (const cb of hydrationSubscribers) cb(revision);
+ }
+ );
+ } catch (error) {
+ console.warn('graphql cache hydration listener failed', error);
+ return undefined;
+ }
+ }
+ const unlistenHydration = listenForHydration();
+ async function removeHydrationListener(): Promise<void> {
+ const unlisten = await unlistenHydration;
+ unlisten?.();
+ }
+
const ready = request<void>('graphql_cache_init', {
scope: options.scope,
hotCapacity: options.hotCapacity,
@@ -259,13 +298,27 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
args: Omit<CacheWriteArgs, 'opKey'>
): Promise<HydrationResult> {
await ready;
- return await request<HydrationResult>('graphql_cache_hydrate', {
- query: args.query,
- operationName: args.operationName,
- variables: args.variables,
- data: args.data,
- identity: args.identity,
- });
+ const result = await request<NativeHydrationResult>(
+ 'graphql_cache_hydrate',
+ {
+ query: args.query,
+ operationName: args.operationName,
+ variables: args.variables,
+ data: args.data,
+ identity: args.identity,
+ }
+ );
+ const newlyObserved = observeRevision(
+ parseCacheRevision(result.revision)
+ );
+ if (result.revisionAdvanced === false || !newlyObserved) return result;
+ try {
+ await emit(CACHE_HYDRATED_EVENT, { revision: result.revision });
+ } catch (error) {
+ // Notification failure must not turn a committed hydration into a retry.
+ console.warn('graphql cache hydration notification failed', error);
+ }
+ return result;
},
async enqueueOptimisticMutation(
@@ -425,9 +478,16 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
return () => affectedSubscribers.delete(cb);
},
- onCacheChanged(cb: (revision: CacheRevision) => void): () => void {
+ onCacheChanged(
+ cb: (revision: CacheRevision) => void,
+ options?: CacheChangeOptions
+ ): () => void {
cacheChangeSubscribers.add(cb);
- return () => cacheChangeSubscribers.delete(cb);
+ if (options?.includeHydration) hydrationSubscribers.add(cb);
+ return () => {
+ cacheChangeSubscribers.delete(cb);
+ hydrationSubscribers.delete(cb);
+ };
},
onCacheGenerationChanged(): () => void {
@@ -445,9 +505,11 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
dispose() {
affectedSubscribers.clear();
cacheChangeSubscribers.clear();
+ hydrationSubscribers.clear();
settlementSubscribers.clear();
void unlistenOps.then((fn) => fn?.());
void unlistenCacheChanges.then((fn) => fn?.());
+ void removeHydrationListener();
void unlistenSettlements.then((fn) => fn?.());
},
};
diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.ts
index a8ec1746f2..884f7ba45c 100644
--- a/apps/web/src/lib/graphql-cache/host/types.ts
+++ b/apps/web/src/lib/graphql-cache/host/types.ts
@@ -84,6 +84,11 @@ export interface InitialMutationClaimArgs {
leaseExpiresAtMs: number;
}
+export type CacheChangeOptions = {
+ /** Also observe background hydration without re-executing foreground queries. */
+ includeHydration?: boolean;
+};
+
export interface CacheHost {
/** Stable id of this context; used to namespace operation ids. */
readonly clientId: string;
@@ -106,6 +111,7 @@ export interface CacheHost {
* Stores a background query response and returns only fields not marked
* `@cacheOnly`. Advances the internal revision for coherent reads without
* notifying foreground subscribers unless the write resets cache identity.
+ * Cache-only consumers can opt into hydration via onCacheChanged.
*/
hydrateQuery(args: Omit<CacheWriteArgs, 'opKey'>): Promise<HydrationResult>;
/** Durably queues an optimistic mutation and claims the strict head. */
@@ -161,7 +167,10 @@ export interface CacheHost {
onOpsAffected(cb: (opKeys: number[]) => void): () => void;
/** Subscribes whenever the effective normalized-cache view changes. */
- onCacheChanged(cb: (revision: CacheRevision) => void): () => void;
+ onCacheChanged(
+ cb: (revision: CacheRevision) => void,
+ options?: CacheChangeOptions
+ ): () => void;
/** Invalidates revision watermarks before a replacement engine is used. */
onCacheGenerationChanged(cb: () => void): () => void;
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
index e84ecc165a..d8b40ba637 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
@@ -1038,6 +1038,34 @@ describe('createWorkerCacheHost', () => {
host.dispose();
});
+ it('delivers hydration only to opted-in subscribers and cleans them up', async () => {
+ const host = createWorkerCacheHost({ scope: 'scope-1' });
+ const foreground = vi.fn();
+ const quickAccess = vi.fn();
+ const operations = vi.fn();
+ host.onCacheChanged(foreground);
+ host.onOpsAffected(operations);
+ const unsubscribe = host.onCacheChanged(quickAccess, {
+ includeHydration: true,
+ });
+ await host.currentRevision();
+ const adapter = requireAdapter();
+ adapter.push({ kind: 'cache-hydrated', revision: INITIAL_CACHE_REVISION });
+ expect(quickAccess).toHaveBeenCalledOnce();
+ expect(foreground).not.toHaveBeenCalled();
+ expect(operations).not.toHaveBeenCalled();
+ adapter.push({ kind: 'cache-changed', revision: INITIAL_CACHE_REVISION });
+ expect(quickAccess).toHaveBeenCalledTimes(2);
+ expect(foreground).toHaveBeenCalledOnce();
+ unsubscribe();
+ adapter.push({ kind: 'cache-hydrated', revision: INITIAL_CACHE_REVISION });
+ expect(quickAccess).toHaveBeenCalledTimes(2);
+ host.onCacheChanged(quickAccess, { includeHydration: true });
+ host.dispose();
+ adapter.push({ kind: 'cache-hydrated', revision: INITIAL_CACHE_REVISION });
+ expect(quickAccess).toHaveBeenCalledTimes(2);
+ });
+
it('strictly filters pushes to the exact client operation prefix', async () => {
const host = createWorkerCacheHost({ scope: 'scope-1' });
const affected: number[][] = [];
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.ts
index aa6183b64f..7bcff4cdc1 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts
@@ -58,6 +58,7 @@ import {
} from '../worker/startup';
import { createNoopCacheHost } from './noop-host';
import type {
+ CacheChangeOptions,
CacheHost,
CacheReadArgs,
CacheWriteArgs,
@@ -202,6 +203,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
const replacementReadOpKeys = new Set<number>();
const affectedSubscribers = new Set<(opKeys: number[]) => void>();
const cacheChangeSubscribers = new Set<(revision: CacheRevision) => void>();
+ const hydrationSubscribers = new Set<(revision: CacheRevision) => void>();
const generationChangeSubscribers = new Set<() => void>();
const settlementSubscribers = new Set<
(settlement: MutationSettlement) => void
@@ -262,6 +264,10 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
const onMessage = (event: MessageEvent<WorkerMessage>) => {
const msg = event.data;
if (isCachePush(msg)) {
+ if (msg.kind === 'cache-hydrated') {
+ for (const cb of hydrationSubscribers) cb(msg.revision);
+ return;
+ }
if (msg.kind === 'cache-changed') {
for (const cb of cacheChangeSubscribers) cb(msg.revision);
return;
@@ -537,6 +543,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
function clearSubscribers(): void {
affectedSubscribers.clear();
cacheChangeSubscribers.clear();
+ hydrationSubscribers.clear();
generationChangeSubscribers.clear();
settlementSubscribers.clear();
}
@@ -1179,9 +1186,16 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
return () => affectedSubscribers.delete(cb);
},
- onCacheChanged(cb: (revision: CacheRevision) => void): () => void {
+ onCacheChanged(
+ cb: (revision: CacheRevision) => void,
+ options?: CacheChangeOptions
+ ): () => void {
cacheChangeSubscribers.add(cb);
- return () => cacheChangeSubscribers.delete(cb);
+ if (options?.includeHydration) hydrationSubscribers.add(cb);
+ return () => {
+ cacheChangeSubscribers.delete(cb);
+ hydrationSubscribers.delete(cb);
+ };
},
onCacheGenerationChanged(cb: () => void): () => void {
diff --git a/apps/web/src/lib/graphql-cache/protocol.test.ts b/apps/web/src/lib/graphql-cache/protocol.test.ts
index afbcb39ad5..775b5eb925 100644
--- a/apps/web/src/lib/graphql-cache/protocol.test.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.test.ts
@@ -145,6 +145,7 @@ describe('cache worker message validators', () => {
},
{ kind: 'ops-affected', opIds: ['client:7'], keys: ['User:1'] },
{ kind: 'cache-changed', revision: INITIAL_CACHE_REVISION },
+ { kind: 'cache-hydrated', revision: INITIAL_CACHE_REVISION },
{
kind: 'mutation-settled',
settlement: { transactionId: '3', status: 'committed' },
@@ -184,6 +185,8 @@ describe('cache worker message validators', () => {
{ kind: 'ops-affected', opIds: [7], keys: [] },
{ kind: 'ops-affected', opIds: [], keys: [], extra: true },
{ kind: 'cache-changed', keys: [] },
+ { kind: 'cache-hydrated', revision: 1 },
+ { kind: 'cache-hydrated', revision: '1', extra: true },
{
kind: 'mutation-settled',
settlement: { transactionId: '3', status: 'committed', error: 'extra' },
diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.ts
index d06d4b69aa..45416885c8 100644
--- a/apps/web/src/lib/graphql-cache/protocol.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.ts
@@ -595,6 +595,7 @@ export type CachePush =
keys: string[];
}
| { kind: 'cache-changed'; revision: CacheRevision }
+ | { kind: 'cache-hydrated'; revision: CacheRevision }
| { kind: 'mutation-settled'; settlement: MutationSettlement };
export type WorkerMessage = CacheResponse | CachePush;
@@ -669,6 +670,7 @@ export function isCachePush(value: unknown): value is CachePush {
isWireStringArray(value.keys)
);
case 'cache-changed':
+ case 'cache-hydrated':
return (
hasOnlyWireKeys(value, ['kind', 'revision']) &&
isCacheRevision(value.revision)
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
index 5732a0ca91..cd67e8435b 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
@@ -923,52 +923,70 @@ describe('CacheWorkerCore', () => {
});
});
- it('keeps revision-advancing background hydration silent', async () => {
- const hydrateQuery = vi.fn().mockResolvedValue({
- revision: INITIAL_CACHE_REVISION,
- revisionAdvanced: true,
- changed: ['GraphqlSoupDocument:doc-1'],
- affectedOps: ['client:7'],
- reset: false,
- data: { cursor: 'next' },
- });
- loadCacheWasmMock.mockResolvedValue({
- openCache: vi.fn().mockResolvedValue({ hydrateQuery }),
- });
- const messages: unknown[] = [];
- const port = { postMessage: (message: unknown) => messages.push(message) };
- const core = new CacheWorkerCore();
- core.addPort(port);
-
- await core.handleRequest(port, {
- id: 1,
- kind: 'init',
- scope: 'scope-1',
- });
- await core.handleRequest(port, {
- id: 2,
- kind: 'hydrate',
- query: 'query Backfill { cursor }',
- data: { cursor: 'next' },
- });
-
- expect(messages).not.toContainEqual(
- expect.objectContaining({ kind: 'ops-affected' })
- );
- expect(messages).not.toContainEqual(
- expect.objectContaining({ kind: 'cache-changed' })
- );
- expect(messages.at(-1)).toEqual({
- id: 2,
- ok: true,
- result: {
- kind: 'data',
- data: { cursor: 'next' },
+ it.each([true, false])(
+ 'notifies only hydration listeners when its revision advances (%s)',
+ async (revisionAdvanced) => {
+ const hydrateQuery = vi.fn().mockResolvedValue({
revision: INITIAL_CACHE_REVISION,
+ changed: ['GraphqlSoupDocument:doc-1'],
+ affectedOps: ['client:7'],
reset: false,
- },
- });
- });
+ data: { cursor: 'next' },
+ revisionAdvanced,
+ });
+ loadCacheWasmMock.mockResolvedValue({
+ openCache: vi.fn().mockResolvedValue({ hydrateQuery }),
+ });
+ const messages: unknown[] = [];
+ const port = {
+ postMessage: (message: unknown) => messages.push(message),
+ };
+ const core = new CacheWorkerCore();
+ core.addPort(port);
+
+ await core.handleRequest(port, {
+ id: 1,
+ kind: 'init',
+ scope: 'scope-1',
+ });
+ await core.handleRequest(port, {
+ id: 2,
+ kind: 'hydrate',
+ query: 'query Backfill { cursor }',
+ data: { cursor: 'next' },
+ });
+
+ expect(messages).not.toContainEqual(
+ expect.objectContaining({ kind: 'ops-affected' })
+ );
+ expect(messages).not.toContainEqual(
+ expect.objectContaining({ kind: 'cache-changed' })
+ );
+ expect(
+ messages.filter(
+ (message) =>
+ typeof message === 'object' &&
+ message !== null &&
+ 'kind' in message &&
+ message.kind === 'cache-hydrated'
+ )
+ ).toEqual(
+ revisionAdvanced
+ ? [{ kind: 'cache-hydrated', revision: INITIAL_CACHE_REVISION }]
+ : []
+ );
+ expect(messages.at(-1)).toEqual({
+ id: 2,
+ ok: true,
+ result: {
+ kind: 'data',
+ data: { cursor: 'next' },
+ revision: INITIAL_CACHE_REVISION,
+ reset: false,
+ },
+ });
+ }
+ );
it('drains earlier request responses before consuming close and rejects later admission', async () => {
const order: string[] = [];
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
index 491db518ca..db93a21230 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
@@ -490,11 +490,13 @@ export class CacheWorkerCore {
request.identity
);
result.revision = parseCacheRevision(result.revision);
- // Hydration is background cache warming. Keep its revision advancement
- // for coherent reads, but do not publish foreground invalidations that
- // would make mounted Soup views switch authority mid-backfill. An
- // identity change is a real cache reset and must still be broadcast.
+ // Only cache-only consumers opt into hydration. Do not invalidate
+ // foreground Soup queries or switch their authority mid-backfill.
+ // Identity changes remain ordinary cache resets for every subscriber.
if (result.reset) this.fanOut(result, true);
+ else if (result.revisionAdvanced) {
+ this.push({ kind: 'cache-hydrated', revision: result.revision });
+ }
const hydration: HydrationResult & Pick<WriteResult, 'reset'> =
result.data === null
? { kind: 'void', revision: result.revision, reset: result.reset }
diff --git a/apps/web/src/lib/queries/history/history.ts b/apps/web/src/lib/queries/history/history.ts
index c98b04c9c2..693d824b3f 100644
--- a/apps/web/src/lib/queries/history/history.ts
+++ b/apps/web/src/lib/queries/history/history.ts
@@ -4,14 +4,16 @@ import { catchToResult, throwOnErr } from '@core/util/result';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { type ItemType, storageServiceClient } from '@service-storage/client';
import { getGraphqlSoupCacheHost } from '@service-storage/graphql-soup';
+import { leadingAndTrailing, throttle } from '@solid-primitives/scheduled';
import {
type QueryClient,
queryOptions,
type Updater,
useMutation,
useQuery,
+ useQueryClient,
} from '@tanstack/solid-query';
-import type { Accessor, Setter } from 'solid-js';
+import { type Accessor, createEffect, onCleanup, type Setter } from 'solid-js';
import { queryClient } from '../client';
import { readCachedGraphqlHistoryItems } from './graphql';
import { historyKeys } from './keys';
@@ -23,7 +25,7 @@ export type { HistoryItem } from './types';
const HISTORY_STALE_TIME = 5 * 60 * 1000;
const HISTORY_GC_TIME = 10 * 60 * 1000;
-const _HISTORY_CACHE_REFRESH_DEBOUNCE_MS = 250;
+const HISTORY_CACHE_REFRESH_INTERVAL_MS = 250;
type HistoryQueryFnResult = HistoryItem[];
@@ -92,12 +94,34 @@ type HistoryQueryKey =
export function useHistoryQuery() {
const graphqlSoupFlag = useFeatureFlag(enableGraphqlSoup);
+ const activeQueryClient = useQueryClient();
const graphqlCacheHost = () => {
if (!graphqlSoupFlag().enabled) return undefined;
const cacheHost = getGraphqlSoupCacheHost();
return cacheHost?.disabled ? undefined : cacheHost;
};
+ createEffect(() => {
+ const host = graphqlCacheHost();
+ if (!host) return;
+ const refresh = leadingAndTrailing(
+ throttle,
+ () => {
+ void activeQueryClient.invalidateQueries({
+ queryKey: historyKeys.graphqlList.queryKey,
+ });
+ },
+ HISTORY_CACHE_REFRESH_INTERVAL_MS
+ );
+ const unsubscribe = host.onCacheChanged(refresh, {
+ includeHydration: true,
+ });
+ onCleanup(() => {
+ unsubscribe();
+ refresh.clear();
+ });
+ });
+
return useQuery<
HistoryQueryFnResult,
Error,
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.tsx
new file mode 100644
index 0000000000..11952ef222
--- /dev/null
+++ b/apps/web/src/lib/queries/history/tests/cache-refresh.test.tsx
@@ -0,0 +1,75 @@
+import type { CacheChangeOptions } from '@graphql-cache/host/types';
+import { render, waitFor } from '@solidjs/testing-library';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { describe, expect, it, vi } from 'vitest';
+import { useHistoryQuery } from '../history';
+
+const mocks = vi.hoisted(() => ({
+ readHistory: vi.fn(),
+ fetchHistory: vi.fn(),
+ subscribe: vi.fn(),
+ unsubscribe: vi.fn(),
+}));
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: true }),
+}));
+vi.mock('@core/constant/featureFlags', () => ({ enableGraphqlSoup: {} }));
+vi.mock('@core/constant/allBlocks', () => ({
+ itemToSafeName: (item: { name: string }) => item.name,
+}));
+vi.mock('@service-storage/util/filename', () => ({
+ formatDocumentName: (name: string) => name,
+}));
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: { getUsersHistory: mocks.fetchHistory },
+}));
+vi.mock('@service-storage/graphql-soup', () => ({
+ getGraphqlSoupCacheHost: () => ({ onCacheChanged: mocks.subscribe }),
+}));
+vi.mock('@queries/history/graphql', () => ({
+ readCachedGraphqlHistoryItems: mocks.readHistory,
+}));
+vi.mock('@queries/client', () => ({ queryClient: {} }));
+vi.mock('@queries/utils', () => ({ withCallbacks: vi.fn() }));
+
+describe('cache-backed history refresh', () => {
+ it('opts into hydration, refreshes only local history, and unsubscribes on disposal', async () => {
+ let notify: (() => void) | undefined;
+ mocks.subscribe.mockImplementation(
+ (callback: () => void, options: CacheChangeOptions) => {
+ expect(options).toEqual({ includeHydration: true });
+ notify = callback;
+ return mocks.unsubscribe;
+ }
+ );
+ mocks.readHistory.mockResolvedValueOnce([]).mockResolvedValue([
+ {
+ id: 'new-document',
+ name: 'New document',
+ type: 'document',
+ ownerId: 'owner',
+ },
+ ]);
+ 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>
+ ));
+ await waitFor(() => expect(query?.isSuccess).toBe(true));
+ expect(query?.data).toEqual([]);
+ notify?.();
+ await waitFor(() => expect(query?.data).toHaveLength(1));
+ expect(mocks.fetchHistory).not.toHaveBeenCalled();
+ view.unmount();
+ expect(mocks.unsubscribe).toHaveBeenCalledOnce();
+ client.clear();
+ });
+});
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
index 0b39e43aaa..3b5e64593b 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
@@ -27,6 +27,9 @@ use cache_turso::TursoFileDatabase;
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Manager, Runtime, State};
+#[cfg(test)]
+mod test;
+
type Variables = serde_json::Map<String, serde_json::Value>;
fn engine_handle(state: &State<'_, CacheState>) -> Result<EngineHandle, String> {
@@ -195,11 +198,17 @@ pub enum HydrationResultWire {
data: serde_json::Value,
/// Revision installed by the hydration write.
revision: String,
+ /// Whether this hydration changed the effective cache view.
+ #[serde(rename = "revisionAdvanced")]
+ revision_advanced: bool,
},
/// Every response field was cache-only.
Void {
/// Revision installed by the hydration write.
revision: String,
+ /// Whether this hydration changed the effective cache view.
+ #[serde(rename = "revisionAdvanced")]
+ revision_advanced: bool,
},
}
@@ -239,9 +248,11 @@ pub async fn graphql_cache_hydrate<R: Runtime>(
Some(data) => HydrationResultWire::Data {
data,
revision: result.write_result.revision,
+ revision_advanced: result.write_result.revision_advanced,
},
None => HydrationResultWire::Void {
revision: result.write_result.revision,
+ revision_advanced: result.write_result.revision_advanced,
},
})
}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands/test.rs b/apps/web/tauri/graphql_cache_plugin/src/commands/test.rs
new file mode 100644
index 0000000000..97a5911678
--- /dev/null
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands/test.rs
@@ -0,0 +1,23 @@
+use super::HydrationResultWire;
+
+#[test]
+fn hydration_results_preserve_the_native_advancement_bit() {
+ for revision_advanced in [false, true] {
+ for result in [
+ HydrationResultWire::Data {
+ data: serde_json::json!({"cursor": null}),
+ revision: "7".to_string(),
+ revision_advanced,
+ },
+ HydrationResultWire::Void {
+ revision: "7".to_string(),
+ revision_advanced,
+ },
+ ] {
+ let json = serde_json::to_value(result).unwrap();
+ assert_eq!(json["revisionAdvanced"], revision_advanced);
+ assert_eq!(json["revision"], "7");
+ assert!(json.get("revision_advanced").is_none());
+ }
+ }
+}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
index 32f46b8ef3..78c4ce5275 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
@@ -138,6 +138,27 @@ fn write_then_read_round_trips() {
assert_eq!(data, soup_data(false));
}
+#[test]
+fn identical_hydration_does_not_advance_the_native_revision() {
+ let handle = spawn_handle();
+ let hydrate = || {
+ block_on(handle.hydrate_query(
+ HYDRATION_QUERY.to_string(),
+ Some("Soup".to_string()),
+ variables(),
+ soup_data(true),
+ None,
+ ))
+ .unwrap()
+ .write_result
+ };
+ let first = hydrate();
+ let duplicate = hydrate();
+ assert!(first.revision_advanced);
+ assert!(!duplicate.revision_advanced);
+ assert_eq!(first.revision, duplicate.revision);
+}
+
#[test]
fn hydration_returns_only_unmarked_fields() {
let handle = spawn_handle();
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 435d9f4e87..3da0949527 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -298,6 +298,17 @@ Opens a dialog with a focused `Search...` textbox and bubble-style category radi
the top hit. Also exposes commands: `Create`, `Change theme`, `MCP setup`. Keys: Tab cycles
category, Esc closes. The category strip and footer have transparent backgrounds.
+With the local GraphQL cache enabled, Cmd+K and document/channel `@` mentions
+search cached entities without waiting for a server search. Background hydration
+updates an already-open menu. For an empty search, scroll toward the end (or use
+Down); mentions offer **View all** for a category and then load more local pages.
+Counts describe loaded results, not the full server corpus. Scans through
+incomplete or already-visible cache hits are bounded per action; continue
+navigating/scrolling, or narrow the query, to resume from the saved cursor.
+A missing item may still be uncached, but should appear after hydration without retyping. Cmd+K's
+local search excludes unsupported email hits before limiting entity results;
+email mentions keep their separate search-service path.
+
## Keyboard model (from the in-app guide; verified partially)
- `Ctrl/Cmd+K` — jump to anything by name.