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.

perf(cache): scope hydration-driven Quick Access refreshes (#7230)

Sean Ayebfd4025de310
diff --git a/Cargo.lock b/Cargo.lock
index 280ec26a3f..b0c2234d4a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3309,7 +3309,7 @@ dependencies = [
[[package]]
name = "cache-wasm"
-version = "0.6.31"
+version = "0.6.32"
dependencies = [
"async-lock",
"cache-core",
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
index 93d7e6d2f4..bcf61274ae 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
@@ -1,11 +1,15 @@
import type { CrmCompanyEntity } from '@entity';
-import type { CacheChangeOptions } from '@graphql-cache/host/types';
+import type {
+ CacheChangeListener,
+ CacheChangeOptions,
+} from '@graphql-cache/host/types';
import type {
SearchCacheArgs,
SearchCachePage,
SearchDocumentWire,
} from '@graphql-cache/index';
import { INITIAL_CACHE_REVISION } from '@graphql-cache/index';
+import type { HydrationSearchChanges } from '@graphql-cache/protocol';
import type { CachedGraphqlChannel } from '@queries/channel/graphql';
import type { HistoryItem } from '@queries/history/types';
import { render } from '@solidjs/testing-library';
@@ -39,7 +43,9 @@ const mocks = vi.hoisted(() => ({
channels: vi.fn(() => []),
cachedChannels: (): CachedGraphqlChannel[] => [],
projectedChannels: [] as CachedGraphqlChannel[],
- changed: undefined as (() => void) | undefined,
+ changed: undefined as
+ | ((changes?: HydrationSearchChanges) => void)
+ | undefined,
unsubscribe: vi.fn(),
channelRefetch: vi.fn(),
onCacheChanged: vi.fn(),
@@ -202,10 +208,17 @@ beforeEach(() => {
],
});
mocks.search.mockReset().mockResolvedValue(page(0, 0));
+ const listeners = new Set<CacheChangeListener>();
+ mocks.changed = (changes) => {
+ for (const callback of listeners) callback(INITIAL_CACHE_REVISION, changes);
+ };
mocks.onCacheChanged.mockImplementation(
- (callback: () => void, _options: CacheChangeOptions) => {
- mocks.changed = callback;
- return mocks.unsubscribe;
+ (callback: CacheChangeListener, _options: CacheChangeOptions) => {
+ listeners.add(callback);
+ return () => {
+ listeners.delete(callback);
+ mocks.unsubscribe();
+ };
}
);
});
@@ -1036,6 +1049,40 @@ describe('Quick Access source integration', () => {
).toEqual(['folder', 'note', 'task']);
});
+ it('ignores email hydration and refreshes only the affected open list and source', async () => {
+ const lists = setup((source) => ({
+ notes: source.useList({ buckets: ['note'] }),
+ channels: source.useList({ buckets: ['channel', 'dm'] }),
+ }));
+ await vi.waitFor(() =>
+ expect(lists.notes.isLoading() || lists.channels.isLoading()).toBe(false)
+ );
+ mocks.search.mockClear();
+ vi.useFakeTimers();
+ for (let i = 0; i < 13; i++)
+ mocks.changed?.({ searchChangedBuckets: ['email'] });
+ mocks.changed?.({ searchChangedBuckets: [] });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.search).not.toHaveBeenCalled();
+ expect(mocks.readRecordsByKeys).not.toHaveBeenCalled();
+ expect(mocks.channelRefetch).not.toHaveBeenCalled();
+
+ mocks.search.mockResolvedValue(page(0, 1));
+ mocks.changed?.({ searchChangedBuckets: ['note'] });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.search).toHaveBeenCalledOnce();
+ expect(mocks.search.mock.calls[0][0].buckets).toEqual(['note']);
+ expect(lists.notes.items()).toHaveLength(1);
+ expect(mocks.channelRefetch).not.toHaveBeenCalled();
+
+ mocks.search.mockClear();
+ mocks.changed?.({ searchChangedBuckets: ['channel'] });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.channelRefetch).toHaveBeenCalledOnce();
+ expect(mocks.search).toHaveBeenCalledOnce();
+ expect(mocks.search.mock.calls[0][0].buckets).toEqual(['channel', 'dm']);
+ });
+
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));
@@ -1048,7 +1095,7 @@ describe('Quick Access source integration', () => {
await vi.waitFor(() => expect(list.items()).toHaveLength(1));
expect(mocks.channelRefetch).toHaveBeenCalledOnce();
dispose?.();
- expect(mocks.unsubscribe).toHaveBeenCalledOnce();
+ expect(mocks.unsubscribe).toHaveBeenCalledTimes(2);
});
it('keeps hidden lists stable and refreshes their latest state once on visibility', async () => {
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
index caa8f6dea7..38a487aa42 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
@@ -367,16 +367,17 @@ export function createQuickAccessValue(): QuickAccessContextValue {
const graphqlCacheHost = getGraphqlSoupCacheHost();
return graphqlCacheHost?.disabled ? undefined : graphqlCacheHost;
});
- const [cacheRevision, setCacheRevision] = createSignal(0);
+ const [manualRefreshRevision, setManualRefreshRevision] = createSignal(0);
const cachedChannelsQuery = useCachedGraphqlChannelsQuery(cacheHost);
createEffect(() => {
const host = cacheHost();
if (!host) return;
onCleanup(
- subscribeToVisibleCacheChanges(host, () => {
- setCacheRevision((revision) => revision + 1);
- return cachedChannelsQuery.refetch({ cancelRefetch: false });
- })
+ subscribeToVisibleCacheChanges(
+ host,
+ () => cachedChannelsQuery.refetch({ cancelRefetch: false }),
+ { searchBuckets: () => ['channel', 'dm'] }
+ )
);
});
const instructionsIdQuery = useInstructionsMdIdQuery();
@@ -956,6 +957,19 @@ export function createQuickAccessValue(): QuickAccessContextValue {
);
// A retired host degrades this list to local items; later lists skip it.
const projectionHost = options ? cacheHost() : undefined;
+ const [cacheRevision, setCacheRevision] = createSignal(0);
+ createEffect(() => {
+ if (!projectionHost || cacheHost() !== projectionHost) return;
+ onCleanup(
+ subscribeToVisibleCacheChanges(
+ projectionHost,
+ () => {
+ setCacheRevision((revision) => revision + 1);
+ },
+ { searchBuckets: projectedBuckets }
+ )
+ );
+ });
const projected =
options && projectionHost
? createProjectedList<QuickAccessItem>({
@@ -963,7 +977,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {
get buckets() {
return projectedBuckets();
},
- revision: cacheRevision,
+ revision: () => cacheRevision() + manualRefreshRevision(),
searchTerm: options.searchTerm,
// An empty bucket list means "all" to the cache, not "none".
enabled: () =>
@@ -1093,7 +1107,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {
const refresh = () => {
if (cacheHost()) {
- setCacheRevision((revision) => revision + 1);
+ setManualRefreshRevision((revision) => revision + 1);
void cachedChannelsQuery.refetch();
}
historyQuery.refetch();
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 0f73b0931f..b8b1a2e401 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
@@ -535,6 +535,37 @@ describe('createTauriCacheHost', () => {
}
);
+ it.each(
+ [[], ['note']].map((searchChangedBuckets) => ({ searchChangedBuckets }))
+ )(
+ 'forwards native bucket metadata $searchChangedBuckets across windows',
+ async ({ searchChangedBuckets }) => {
+ const host = createTauriCacheHost({ scope: 'scope-1' });
+ const listener = vi.fn();
+ host.onCacheChanged(listener, { includeHydration: true });
+ invokeMock.mockImplementation(async (command: string) =>
+ command === 'graphql_cache_hydrate'
+ ? {
+ kind: 'void',
+ revision: '7',
+ revisionAdvanced: true,
+ searchChangedBuckets,
+ }
+ : null
+ );
+ await host.hydrateQuery({ query: '{ x }', data: { x: 1 } });
+ expect(emitMock).toHaveBeenCalledWith('graphql-cache://cache-hydrated', {
+ revision: '7',
+ searchChangedBuckets,
+ });
+ eventCallbacks.get('graphql-cache://cache-hydrated')?.({
+ payload: { revision: '7', searchChangedBuckets },
+ });
+ expect(listener).toHaveBeenCalledWith('7', { searchChangedBuckets });
+ host.dispose();
+ }
+ );
+
it('delivers cross-window hydration only to opted-in listeners', async () => {
const host = createTauriCacheHost({ scope: 'scope-1' });
const foreground = vi.fn();
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 7a2b065a10..d9c8f36fe6 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -21,6 +21,7 @@ import type {
EntityFilterCacheArgs,
EntityFilterCacheResult,
HydrationResult,
+ HydrationSearchChanges,
MutationClaim,
MutationSettlement,
ReadRecordsByKeysArgs,
@@ -38,6 +39,7 @@ import {
validateRecordSelectionKeys,
} from '../protocol';
import type {
+ CacheChangeListener,
CacheChangeOptions,
CacheGenerationChange,
CacheHost,
@@ -64,7 +66,10 @@ type OpsAffectedPayload = {
keys: string[];
};
-type CacheChangedPayload = { revision: string; reset?: boolean };
+type CacheChangedPayload = {
+ revision: string;
+ reset?: boolean;
+} & HydrationSearchChanges;
// Older native binaries omit the advancement bit and still receive OTA JS.
type NativeHydrationResult = HydrationResult & { revisionAdvanced?: boolean };
@@ -88,8 +93,8 @@ const ENTITY_FILTER_COMMAND = 'graphql_cache_entity_filter';
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 cacheChangeSubscribers = new Set<CacheChangeListener>();
+ const hydrationSubscribers = new Set<CacheChangeListener>();
const generationChangeSubscribers = new Set<
(change: CacheGenerationChange) => void
>();
@@ -185,7 +190,13 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
(event) => {
const revision = parseCacheRevision(event.payload.revision);
observeRevision(revision);
- for (const cb of hydrationSubscribers) cb(revision);
+ for (const cb of hydrationSubscribers) {
+ if (event.payload.searchChangedBuckets === undefined) cb(revision);
+ else
+ cb(revision, {
+ searchChangedBuckets: event.payload.searchChangedBuckets,
+ });
+ }
}
);
} catch (error) {
@@ -328,7 +339,12 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
);
if (result.revisionAdvanced === false || !newlyObserved) return result;
try {
- await emit(CACHE_HYDRATED_EVENT, { revision: result.revision });
+ await emit(CACHE_HYDRATED_EVENT, {
+ revision: result.revision,
+ ...(result.searchChangedBuckets !== undefined
+ ? { searchChangedBuckets: result.searchChangedBuckets }
+ : {}),
+ });
} catch (error) {
// Notification failure must not turn a committed hydration into a retry.
console.warn('graphql cache hydration notification failed', error);
@@ -494,7 +510,7 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
},
onCacheChanged(
- cb: (revision: CacheRevision) => void,
+ cb: CacheChangeListener,
options?: CacheChangeOptions
): () => void {
cacheChangeSubscribers.add(cb);
diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.ts
index 5bfb39f53d..aadccab4ee 100644
--- a/apps/web/src/lib/graphql-cache/host/types.ts
+++ b/apps/web/src/lib/graphql-cache/host/types.ts
@@ -20,6 +20,7 @@ import type {
EntityFilterCacheArgs,
EntityFilterCacheResult,
HydrationResult,
+ HydrationSearchChanges,
MutationClaim,
MutationSettlement,
OptimisticLinkPatchWire,
@@ -84,6 +85,12 @@ export interface InitialMutationClaimArgs {
leaseExpiresAtMs: number;
}
+export type CacheChangeListener = (
+ revision: CacheRevision,
+ /** Undefined for ordinary writes/resets and older runtimes: refresh conservatively. */
+ searchChanges?: HydrationSearchChanges
+) => void;
+
export type CacheChangeOptions = {
/** Also observe background hydration without re-executing foreground queries. */
includeHydration?: boolean;
@@ -176,7 +183,7 @@ export interface CacheHost {
/** Subscribes whenever the effective normalized-cache view changes. */
onCacheChanged(
- cb: (revision: CacheRevision) => void,
+ cb: CacheChangeListener,
options?: CacheChangeOptions
): () => 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 13e24df94f..9e3afc4340 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
@@ -1136,6 +1136,29 @@ describe('createWorkerCacheHost', () => {
}
);
+ it.each(
+ [[], ['note'], ['channel', 'dm']].map((searchChangedBuckets) => ({
+ searchChangedBuckets,
+ }))
+ )(
+ 'forwards hydration search metadata $searchChangedBuckets',
+ async ({ searchChangedBuckets }) => {
+ const host = createWorkerCacheHost({ scope: 'scope-1' });
+ const listener = vi.fn();
+ host.onCacheChanged(listener, { includeHydration: true });
+ await host.currentRevision();
+ requireAdapter().push({
+ kind: 'cache-hydrated',
+ revision: INITIAL_CACHE_REVISION,
+ searchChangedBuckets,
+ });
+ expect(listener).toHaveBeenCalledWith(INITIAL_CACHE_REVISION, {
+ searchChangedBuckets,
+ });
+ 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();
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 56672fb7fd..a1d54b37f4 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts
@@ -63,6 +63,7 @@ import {
import { CacheNavigationError } from './navigation-error';
import { createNoopCacheHost } from './noop-host';
import type {
+ CacheChangeListener,
CacheChangeOptions,
CacheGenerationChange,
CacheHost,
@@ -221,8 +222,8 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
const lostRegisteredOpKeys = new Set<number>();
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 cacheChangeSubscribers = new Set<CacheChangeListener>();
+ const hydrationSubscribers = new Set<CacheChangeListener>();
const generationChangeSubscribers = new Set<
(change: CacheGenerationChange) => void
>();
@@ -290,7 +291,13 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
const msg = event.data;
if (isCachePush(msg)) {
if (msg.kind === 'cache-hydrated') {
- for (const cb of hydrationSubscribers) cb(msg.revision);
+ for (const cb of hydrationSubscribers) {
+ if (msg.searchChangedBuckets === undefined) cb(msg.revision);
+ else
+ cb(msg.revision, {
+ searchChangedBuckets: msg.searchChangedBuckets,
+ });
+ }
return;
}
if (msg.kind === 'cache-changed') {
@@ -1397,7 +1404,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
},
onCacheChanged(
- cb: (revision: CacheRevision) => void,
+ cb: CacheChangeListener,
options?: CacheChangeOptions
): () => void {
cacheChangeSubscribers.add(cb);
diff --git a/apps/web/src/lib/graphql-cache/protocol.test.ts b/apps/web/src/lib/graphql-cache/protocol.test.ts
index 775b5eb925..b97e9a369f 100644
--- a/apps/web/src/lib/graphql-cache/protocol.test.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.test.ts
@@ -146,6 +146,16 @@ 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: 'cache-hydrated',
+ revision: INITIAL_CACHE_REVISION,
+ searchChangedBuckets: [],
+ },
+ {
+ kind: 'cache-hydrated',
+ revision: INITIAL_CACHE_REVISION,
+ searchChangedBuckets: ['note', 'email'],
+ },
{
kind: 'mutation-settled',
settlement: { transactionId: '3', status: 'committed' },
@@ -187,6 +197,8 @@ describe('cache worker message validators', () => {
{ kind: 'cache-changed', keys: [] },
{ kind: 'cache-hydrated', revision: 1 },
{ kind: 'cache-hydrated', revision: '1', extra: true },
+ { kind: 'cache-hydrated', revision: '1', searchChangedBuckets: 'note' },
+ { kind: 'cache-hydrated', revision: '1', searchChangedBuckets: [1] },
{
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 af6d6026e9..9ed4eb03c7 100644
--- a/apps/web/src/lib/graphql-cache/protocol.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.ts
@@ -344,9 +344,16 @@ export type CachedQueryInstanceWire = CachedQueryVariantWire & {
value?: unknown;
};
-export type HydrationResult =
- | { kind: 'data'; data: unknown; revision: CacheRevision }
- | { kind: 'void'; revision: CacheRevision };
+/** Missing metadata means unknown (older runtimes); [] proves no search change. */
+export type HydrationSearchChanges = {
+ searchChangedBuckets?: string[];
+};
+
+export type HydrationResult = HydrationSearchChanges &
+ (
+ | { kind: 'data'; data: unknown; revision: CacheRevision }
+ | { kind: 'void'; revision: CacheRevision }
+ );
export type WriteResult = {
/** Effective-view revision installed by this logical mutation. */
@@ -626,7 +633,10 @@ export type CachePush =
keys: string[];
}
| { kind: 'cache-changed'; revision: CacheRevision; reset?: boolean }
- | { kind: 'cache-hydrated'; revision: CacheRevision }
+ | ({
+ kind: 'cache-hydrated';
+ revision: CacheRevision;
+ } & HydrationSearchChanges)
| { kind: 'mutation-settled'; settlement: MutationSettlement };
export type WorkerMessage = CacheResponse | CachePush;
@@ -717,8 +727,10 @@ export function isCachePush(value: unknown): value is CachePush {
);
case 'cache-hydrated':
return (
- hasOnlyWireKeys(value, ['kind', 'revision']) &&
- isCacheRevision(value.revision)
+ hasOnlyWireKeys(value, ['kind', 'revision', 'searchChangedBuckets']) &&
+ isCacheRevision(value.revision) &&
+ (value.searchChangedBuckets === undefined ||
+ isWireStringArray(value.searchChangedBuckets))
);
case 'mutation-settled': {
const settlement = value.settlement;
diff --git a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
index 1e39dc0c77..043d2b2910 100644
--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
@@ -21,6 +21,7 @@ import type {
EnqueueOptimisticMutationResult,
EntityFilterCacheArgs,
EntityFilterCacheResult,
+ HydrationSearchChanges,
OptimisticLinkPatchWire,
QueryRevalidationWire,
ReadRecordsByKeysResult,
@@ -64,9 +65,10 @@ export interface CacheOpenResult {
outcome: CacheOpenOutcome;
}
-export type CacheEngineHydrationResult = WriteResult & {
- data: unknown | null;
-};
+export type CacheEngineHydrationResult = WriteResult &
+ HydrationSearchChanges & {
+ data: unknown | null;
+ };
export interface CacheEngine {
currentRevision(): Promise<CacheRevision>;
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 456b1dfb59..7136a905c4 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
@@ -1018,6 +1018,7 @@ describe('CacheWorkerCore', () => {
reset: false,
data: { cursor: 'next' },
revisionAdvanced,
+ searchChangedBuckets: ['note'],
});
loadCacheWasmMock.mockResolvedValue({
openCache: vi.fn().mockResolvedValue({ hydrateQuery }),
@@ -1057,7 +1058,13 @@ describe('CacheWorkerCore', () => {
)
).toEqual(
revisionAdvanced
- ? [{ kind: 'cache-hydrated', revision: INITIAL_CACHE_REVISION }]
+ ? [
+ {
+ kind: 'cache-hydrated',
+ revision: INITIAL_CACHE_REVISION,
+ searchChangedBuckets: ['note'],
+ },
+ ]
: []
);
expect(messages.at(-1)).toEqual({
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 3b8c643b7b..99a5914480 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
@@ -531,7 +531,13 @@ export class CacheWorkerCore {
// 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 });
+ this.push({
+ kind: 'cache-hydrated',
+ revision: result.revision,
+ ...(result.searchChangedBuckets !== undefined
+ ? { searchChangedBuckets: result.searchChangedBuckets }
+ : {}),
+ });
}
const hydration: HydrationResult & Pick<WriteResult, 'reset'> =
result.data === null
diff --git a/apps/web/src/lib/queries/history/graphql.ts b/apps/web/src/lib/queries/history/graphql.ts
index 1328250e3c..12aab19977 100644
--- a/apps/web/src/lib/queries/history/graphql.ts
+++ b/apps/web/src/lib/queries/history/graphql.ts
@@ -134,6 +134,17 @@ export async function materializeCachedGraphqlHistoryItems(
});
}
+/** Buckets consumed by history and its hydration subscription. */
+export const HISTORY_SEARCH_BUCKETS = [
+ 'document',
+ 'note',
+ 'task',
+ 'snippet',
+ 'skill',
+ 'chat',
+ 'project',
+] as const;
+
/** Reads a bounded recent history through the indexed search projection, then
* materializes only those final normalized entity keys. */
export async function readCachedGraphqlHistoryItems(
@@ -141,15 +152,7 @@ export async function readCachedGraphqlHistoryItems(
): Promise<HistoryItem[]> {
const page = await cacheHost.search({
profile: 'quick-access-v1',
- buckets: [
- 'document',
- 'note',
- 'task',
- 'snippet',
- 'skill',
- 'chat',
- 'project',
- ],
+ buckets: [...HISTORY_SEARCH_BUCKETS],
query: '',
limit: 500,
});
diff --git a/apps/web/src/lib/queries/history/history.ts b/apps/web/src/lib/queries/history/history.ts
index 272a8ca644..18bf418760 100644
--- a/apps/web/src/lib/queries/history/history.ts
+++ b/apps/web/src/lib/queries/history/history.ts
@@ -15,7 +15,10 @@ import {
import { type Accessor, createEffect, onCleanup, type Setter } from 'solid-js';
import { queryClient } from '../client';
import { subscribeToVisibleCacheChanges } from '../subscribe-to-visible-cache-changes';
-import { readCachedGraphqlHistoryItems } from './graphql';
+import {
+ HISTORY_SEARCH_BUCKETS,
+ readCachedGraphqlHistoryItems,
+} from './graphql';
import { historyKeys } from './keys';
import { transformHistoryItem, transformHistoryResponse } from './transforms';
import type { HistoryItem } from './types';
@@ -104,11 +107,14 @@ export function useHistoryQuery() {
const host = graphqlCacheHost();
if (!host) return;
onCleanup(
- subscribeToVisibleCacheChanges(host, () =>
- activeQueryClient.invalidateQueries(
- { queryKey: historyKeys.graphqlList.queryKey },
- { cancelRefetch: false }
- )
+ subscribeToVisibleCacheChanges(
+ host,
+ () =>
+ activeQueryClient.invalidateQueries(
+ { queryKey: historyKeys.graphqlList.queryKey },
+ { cancelRefetch: false }
+ ),
+ { searchBuckets: () => HISTORY_SEARCH_BUCKETS }
)
);
});
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
index 5c983cd3fb..16e5e022d4 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
@@ -1,4 +1,8 @@
-import type { CacheChangeOptions } from '@graphql-cache/host/types';
+import type {
+ CacheChangeListener,
+ CacheChangeOptions,
+} from '@graphql-cache/host/types';
+import { INITIAL_CACHE_REVISION } from '@graphql-cache/protocol';
import { cleanup, render, waitFor } from '@solidjs/testing-library';
import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -26,7 +30,8 @@ vi.mock('@service-storage/client', () => ({
vi.mock('@service-storage/graphql-soup', () => ({
getGraphqlSoupCacheHost: () => ({ onCacheChanged: mocks.subscribe }),
}));
-vi.mock('@queries/history/graphql', () => ({
+vi.mock('@queries/history/graphql', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../graphql')>()),
readCachedGraphqlHistoryItems: mocks.readHistory,
}));
vi.mock('@queries/client', () => ({ queryClient: {} }));
@@ -156,10 +161,10 @@ describe('cache-backed history refresh', () => {
}
});
- it('opts into hydration, refreshes only local history, and unsubscribes on disposal', async () => {
- let notify: (() => void) | undefined;
+ it('ignores unrelated hydration but discovers newly hydrated documents', async () => {
+ let notify: CacheChangeListener | undefined;
mocks.subscribe.mockImplementation(
- (callback: () => void, options: CacheChangeOptions) => {
+ (callback: CacheChangeListener, options: CacheChangeOptions) => {
expect(options).toEqual({ includeHydration: true });
notify = callback;
return mocks.unsubscribe;
@@ -188,8 +193,18 @@ describe('cache-backed history refresh', () => {
));
await waitFor(() => expect(query?.isSuccess).toBe(true));
expect(query?.data).toEqual([]);
- notify?.();
- await waitFor(() => expect(query?.data).toHaveLength(1));
+ const callsBefore = mocks.readHistory.mock.calls.length;
+ vi.useFakeTimers();
+ notify?.(INITIAL_CACHE_REVISION, { searchChangedBuckets: ['email'] });
+ notify?.(INITIAL_CACHE_REVISION, {
+ searchChangedBuckets: ['channel', 'dm'],
+ });
+ notify?.(INITIAL_CACHE_REVISION, { searchChangedBuckets: [] });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.readHistory).toHaveBeenCalledTimes(callsBefore);
+ notify?.(INITIAL_CACHE_REVISION, { searchChangedBuckets: ['note'] });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(query?.data).toHaveLength(1);
expect(mocks.fetchHistory).not.toHaveBeenCalled();
view.unmount();
expect(mocks.unsubscribe).toHaveBeenCalledOnce();
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.ts
index 1db4a80fb3..d918613c4b 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
@@ -1,4 +1,8 @@
-import type { CacheHost } from '@graphql-cache/host/types';
+import type { CacheChangeListener, CacheHost } from '@graphql-cache/host/types';
+import {
+ type HydrationSearchChanges,
+ INITIAL_CACHE_REVISION,
+} from '@graphql-cache/protocol';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { subscribeToVisibleCacheChanges } from './subscribe-to-visible-cache-changes';
@@ -10,17 +14,26 @@ function setVisibility(value: DocumentVisibilityState) {
document.dispatchEvent(new Event('visibilitychange'));
}
-function setup(refresh = vi.fn<() => void | Promise<unknown>>()) {
- let notify = () => {};
+function setup(
+ refresh = vi.fn<() => void | Promise<unknown>>(),
+ options?: Parameters<typeof subscribeToVisibleCacheChanges>[2]
+) {
+ let notify: CacheChangeListener = () => {};
const unsubscribe = vi.fn();
const host = {
- onCacheChanged: vi.fn((callback: () => void) => {
+ onCacheChanged: vi.fn((callback: CacheChangeListener) => {
notify = callback;
return unsubscribe;
}),
} satisfies Pick<CacheHost, 'onCacheChanged'>;
- dispose = subscribeToVisibleCacheChanges(host, refresh);
- return { host, notify, refresh, unsubscribe };
+ dispose = subscribeToVisibleCacheChanges(host, refresh, options);
+ return {
+ host,
+ notify: (changes?: HydrationSearchChanges) =>
+ notify(INITIAL_CACHE_REVISION, changes),
+ refresh,
+ unsubscribe,
+ };
}
beforeEach(() => {
@@ -38,6 +51,61 @@ afterEach(() => {
});
describe('subscribeToVisibleCacheChanges', () => {
+ it('does no work for unrelated hydration, including while hidden', () => {
+ const { notify, refresh } = setup(undefined, {
+ searchBuckets: () => ['note', 'task'],
+ });
+ notify({ searchChangedBuckets: ['email'] });
+ notify({ searchChangedBuckets: [] });
+ setVisibility('hidden');
+ notify({ searchChangedBuckets: ['channel'] });
+ setVisibility('visible');
+ vi.advanceTimersByTime(1000);
+ expect(refresh).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('refreshes newly hydrated matching buckets and falls back for legacy/reset notifications', () => {
+ const { notify, refresh } = setup(undefined, {
+ searchBuckets: () => ['note'],
+ });
+ notify({ searchChangedBuckets: ['note'] });
+ expect(refresh).toHaveBeenCalledOnce();
+ vi.advanceTimersByTime(250);
+ notify();
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not queue a follow-up for unrelated hydration during a slow refresh', async () => {
+ let finish!: () => void;
+ const refresh = vi.fn<() => void | Promise<unknown>>().mockReturnValueOnce(
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ })
+ );
+ const { notify } = setup(refresh, {
+ searchBuckets: () => ['channel', 'dm'],
+ });
+ notify({ searchChangedBuckets: ['dm'] });
+ for (let i = 0; i < 20; i++)
+ notify({ searchChangedBuckets: ['email', 'note'] });
+ finish();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(refresh).toHaveBeenCalledOnce();
+ });
+
+ it('uses current bucket interests for projected lists', () => {
+ let buckets = ['note'];
+ const { notify, refresh } = setup(undefined, {
+ searchBuckets: () => buckets,
+ });
+ notify({ searchChangedBuckets: ['channel'] });
+ expect(refresh).not.toHaveBeenCalled();
+ buckets = ['channel'];
+ notify({ searchChangedBuckets: ['channel'] });
+ expect(refresh).toHaveBeenCalledOnce();
+ });
+
it('retains leading/trailing throttling and hydration updates when visible', () => {
const { host, notify, refresh } = setup();
expect(host.onCacheChanged).toHaveBeenCalledWith(expect.any(Function), {
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.ts
index b7eda5f2fc..7cd074dc64 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
@@ -1,6 +1,7 @@
import type { CacheHost } from '@graphql-cache/host/types';
import { makeEventListener } from '@solid-primitives/event-listener';
import { leadingAndTrailing, throttle } from '@solid-primitives/scheduled';
+import { type Accessor, untrack } from 'solid-js';
const CACHE_REFRESH_INTERVAL_MS = 250;
@@ -15,7 +16,8 @@ const CACHE_REFRESH_INTERVAL_MS = 250;
*/
export function subscribeToVisibleCacheChanges(
host: Pick<CacheHost, 'onCacheChanged'>,
- refresh: () => void | Promise<unknown>
+ refresh: () => void | Promise<unknown>,
+ options?: { searchBuckets: Accessor<readonly string[]> }
): () => void {
let dirty = false;
let disposed = false;
@@ -44,8 +46,13 @@ export function subscribeToVisibleCacheChanges(
CACHE_REFRESH_INTERVAL_MS
);
const unsubscribe = host.onCacheChanged(
- () => {
+ (_revision, changes) => {
if (disposed) return;
+ const changedBuckets = changes?.searchChangedBuckets;
+ if (options && changedBuckets !== undefined) {
+ const watched = untrack(options.searchBuckets);
+ if (!changedBuckets.some((bucket) => watched.includes(bucket))) return;
+ }
dirty = true;
if (isVisible()) scheduled();
},
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
index dfcc63418b..e8ab6ea14d 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
@@ -202,6 +202,9 @@ pub async fn graphql_cache_write<R: Runtime>(
pub enum HydrationResultWire {
/// At least one non-cache-only field was projected.
Data {
+ /// Quick Access buckets whose searchable or materialized fields changed.
+ #[serde(rename = "searchChangedBuckets")]
+ search_changed_buckets: std::collections::BTreeSet<String>,
/// Projected GraphQL response data.
data: serde_json::Value,
/// Revision installed by the hydration write.
@@ -212,6 +215,9 @@ pub enum HydrationResultWire {
},
/// Every response field was cache-only.
Void {
+ /// Quick Access buckets whose searchable or materialized fields changed.
+ #[serde(rename = "searchChangedBuckets")]
+ search_changed_buckets: std::collections::BTreeSet<String>,
/// Revision installed by the hydration write.
revision: String,
/// Whether this hydration changed the effective cache view.
@@ -258,11 +264,13 @@ pub async fn graphql_cache_hydrate<R: Runtime>(
}
Ok(match result.data {
Some(data) => HydrationResultWire::Data {
+ search_changed_buckets: result.search_changed_buckets,
data,
revision: result.write_result.revision,
revision_advanced: result.write_result.revision_advanced,
},
None => HydrationResultWire::Void {
+ search_changed_buckets: result.search_changed_buckets,
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
index 97a5911678..3a2210be9b 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands/test.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands/test.rs
@@ -5,11 +5,13 @@ fn hydration_results_preserve_the_native_advancement_bit() {
for revision_advanced in [false, true] {
for result in [
HydrationResultWire::Data {
+ search_changed_buckets: ["note".into()].into(),
data: serde_json::json!({"cursor": null}),
revision: "7".to_string(),
revision_advanced,
},
HydrationResultWire::Void {
+ search_changed_buckets: ["note".into()].into(),
revision: "7".to_string(),
revision_advanced,
},
@@ -17,6 +19,7 @@ fn hydration_results_preserve_the_native_advancement_bit() {
let json = serde_json::to_value(result).unwrap();
assert_eq!(json["revisionAdvanced"], revision_advanced);
assert_eq!(json["revision"], "7");
+ assert_eq!(json["searchChangedBuckets"], serde_json::json!(["note"]));
assert!(json.get("revision_advanced").is_none());
}
}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
index 38e25b8526..df07d6769d 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
@@ -73,6 +73,8 @@ pub struct WriteResultWire {
/// Internal hydration result used to fan out changes before returning only
/// the caller-visible projection across IPC.
pub struct HydrationWriteResultWire {
+ /// Quick Access buckets changed by hydration.
+ pub search_changed_buckets: std::collections::BTreeSet<String>,
/// Cache changes required for host notifications.
pub write_result: WriteResultWire,
/// Fields not marked `@cacheOnly`, or `None` when there are none.
@@ -631,6 +633,7 @@ impl EngineHandle {
)
.await
.map(|result| HydrationWriteResultWire {
+ search_changed_buckets: result.search_changed_buckets,
write_result: wire_write_result(ops, result.write_result),
data: result.data,
})
diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rs
index 8258ffb322..c50082dfd9 100644
--- a/crates/client/cache-core/src/engine.rs
+++ b/crates/client/cache-core/src/engine.rs
@@ -47,7 +47,8 @@ use crate::record_selection::{
use crate::revision::{CacheRevision, Revisioned};
use crate::search::{
SearchCursor, SearchDocument, SearchError, SearchPage, SearchProfile, SearchRequest,
- compare_recent, fuzzy_freshness_score, project_search_documents, validate_search_request,
+ collect_search_changes, compare_recent, fuzzy_freshness_score, project_search_documents,
+ snapshot_search_fields, validate_search_request,
};
use crate::store::{QueueDiagnostics, Storage};
use crate::value::{EntityKey, Record, canonical_json};
@@ -158,6 +159,9 @@ pub struct WriteResult {
/// Result of hydrating a query while returning only non-`@cacheOnly` fields.
#[derive(Debug)]
pub struct HydrationWriteResult {
+ /// Quick Access buckets whose searchable or materialized fields changed.
+ /// An empty set proves that search-backed consumers need no refresh.
+ pub search_changed_buckets: BTreeSet<String>,
/// Cache changes used by hosts for invalidation fan-out.
pub write_result: WriteResult,
/// Small caller-visible projection, or `None` when every field is cache-only.
@@ -1099,6 +1103,7 @@ impl<S: Storage> Engine<S> {
) -> Result<WriteResult, EngineError<S::Error>> {
self.write_network(origin_op, registration, input, projections, true)
.await
+ .map(|(result, _)| result)
}
async fn write_network(
@@ -1108,7 +1113,7 @@ impl<S: Storage> Engine<S> {
input: NetworkWrite<'_>,
projections: Vec<ProjectionMutation>,
retain_pages: bool,
- ) -> Result<WriteResult, EngineError<S::Error>> {
+ ) -> Result<(WriteResult, BTreeSet<String>), EngineError<S::Error>> {
self.ensure_revision_can_advance()?;
let NetworkWrite {
query,
@@ -1169,7 +1174,7 @@ impl<S: Storage> Engine<S> {
let before = effective_records(&bases, &self.optimistic, &candidates);
Some((candidates, before))
};
- let (changed, mut revision, mut revision_advanced) =
+ let (changed, mut revision, mut revision_advanced, mut search_changed_buckets) =
self.persist_updates(updates, projections).await?;
if reset && !revision_advanced {
revision = self.advance_revision()?;
@@ -1186,6 +1191,17 @@ impl<S: Storage> Engine<S> {
candidates.extend(layer_keys(&self.optimistic));
let bases_after = self.load_bases(&candidates).await?;
let after = effective_records(&bases_after, &self.optimistic, &candidates);
+ // Compare the composed view: a hydration hidden beneath a pending
+ // edit must not invalidate the search projection it did not change.
+ search_changed_buckets.clear();
+ for key in &candidates {
+ collect_search_changes(
+ key,
+ before.get(key).and_then(Option::as_ref),
+ after.get(key).and_then(Option::as_ref),
+ &mut search_changed_buckets,
+ );
+ }
candidates
.into_iter()
.filter(|key| before.get(key) != after.get(key))
@@ -1213,14 +1229,17 @@ impl<S: Storage> Engine<S> {
self.deps.set_op_broad(registration.op_id);
}
}
- Ok(WriteResult {
- revision,
- revision_advanced,
- changed,
- affected_ops,
- reset,
- revalidations: Vec::new(),
- })
+ Ok((
+ WriteResult {
+ revision,
+ revision_advanced,
+ changed,
+ affected_ops,
+ reset,
+ revalidations: Vec::new(),
+ },
+ search_changed_buckets,
+ ))
}
/// Stores a network response and returns only fields not marked
@@ -1270,7 +1289,7 @@ impl<S: Storage> Engine<S> {
}
project_hydration_response(op, data)?
};
- let write_result = self
+ let (write_result, search_changed_buckets) = self
.write_network(
None,
None,
@@ -1287,6 +1306,7 @@ impl<S: Storage> Engine<S> {
.await?;
Ok(HydrationWriteResult {
write_result,
+ search_changed_buckets,
data: projected,
})
}
@@ -1297,7 +1317,15 @@ impl<S: Storage> Engine<S> {
&mut self,
updates: RecordUpdates,
projections: Vec<ProjectionMutation>,
- ) -> Result<(BTreeSet<EntityKey<'static>>, CacheRevision, bool), EngineError<S::Error>> {
+ ) -> Result<
+ (
+ BTreeSet<EntityKey<'static>>,
+ CacheRevision,
+ bool,
+ BTreeSet<String>,
+ ),
+ EngineError<S::Error>,
+ > {
// Load current values (hot tier, then storage) so merges detect real
// changes. Merges are staged in a plain map, NOT the LRU: a batch
// larger than the hot capacity would otherwise evict its own
@@ -1326,15 +1354,30 @@ impl<S: Storage> Engine<S> {
}
let mut changed = BTreeSet::new();
+ let mut search_changed_buckets = BTreeSet::new();
let mut to_persist: Vec<(EntityKey<'static>, Record)> = Vec::new();
let mut touched = Vec::with_capacity(updates.len());
for (key, update) in updates {
let (merged, did_change) = match staging.remove(&key) {
Some(mut existing) => {
+ // Compare only fields supplied by this partial response,
+ // overlaid onto the existing row, without cloning its body.
+ let before = snapshot_search_fields(&key, &existing);
let did_change = existing.merge(update);
+ if did_change {
+ collect_search_changes(
+ &key,
+ before.as_ref(),
+ Some(&existing),
+ &mut search_changed_buckets,
+ );
+ }
(existing, did_change)
}
- None => (update, true),
+ None => {
+ collect_search_changes(&key, None, Some(&update), &mut search_changed_buckets);
+ (update, true)
+ }
};
if did_change {
changed.insert(key.clone());
@@ -1366,7 +1409,7 @@ impl<S: Storage> Engine<S> {
for (key, record) in touched {
self.hot.put(key, record);
}
- Ok((changed, revision, revision_advanced))
+ Ok((changed, revision, revision_advanced, search_changed_buckets))
}
async fn projection_mutations_change(
@@ -2440,7 +2483,7 @@ impl<S: PredicateIndexStorage> Engine<S> {
for (key, record) in entries {
updates.entry(key).or_default().merge(record);
}
- let (changed, revision, revision_advanced) =
+ let (changed, revision, revision_advanced, _) =
self.persist_updates(updates, projections).await?;
let mut affected_ops = self.deps.ops_for_keys(changed.iter());
if let Some(origin_op) = origin_op {
diff --git a/crates/client/cache-core/src/engine/test.rs b/crates/client/cache-core/src/engine/test.rs
index 36eb6c14d5..67a7ea77e2 100644
--- a/crates/client/cache-core/src/engine/test.rs
+++ b/crates/client/cache-core/src/engine/test.rs
@@ -1,6 +1,8 @@
use super::*;
use crate::store::InMemoryStorage;
+mod hydration_search_changes;
+
#[test]
fn storage_generation_survives_reopening_and_preserves_existing_records() {
pollster::block_on(async {
diff --git a/crates/client/cache-core/src/engine/test/hydration_search_changes.graphql b/crates/client/cache-core/src/engine/test/hydration_search_changes.graphql
new file mode 100644
index 0000000000..62f68b7889
--- /dev/null
+++ b/crates/client/cache-core/src/engine/test/hydration_search_changes.graphql
@@ -0,0 +1,22 @@
+query HydrationChanges {
+ user {
+ id
+ soup(input: { initial: { limit: 10 } }) {
+ items @cacheOnly {
+ __typename
+ id
+ ... on GraphqlSoupDocument {
+ name
+ fileType
+ subType {
+ __typename
+ ... on GraphqlTaskSubType { isCompleted }
+ }
+ ownerId
+ properties { id }
+ }
+ ... on GraphqlSoupEmailThread { name }
+ }
+ }
+ }
+}
diff --git a/crates/client/cache-core/src/engine/test/hydration_search_changes.rs b/crates/client/cache-core/src/engine/test/hydration_search_changes.rs
new file mode 100644
index 0000000000..16173d4a8d
--- /dev/null
+++ b/crates/client/cache-core/src/engine/test/hydration_search_changes.rs
@@ -0,0 +1,136 @@
+use super::*;
+use crate::record_selection::RecordSelection;
+use crate::value::CacheValue;
+use serde_json::json;
+
+const QUERY: &str = include_str!("hydration_search_changes.graphql");
+
+async fn hydrate(engine: &mut Engine<InMemoryStorage>, item: Json) -> HydrationWriteResult {
+ engine
+ .hydrate_query(
+ QUERY,
+ None,
+ &serde_json::Map::new(),
+ &json!({"user": {"id": "viewer", "soup": {"items": [item]}}}),
+ None,
+ )
+ .await
+ .unwrap()
+}
+
+#[test]
+fn nested_task_completion_hydration_invalidates_task_searches() {
+ pollster::block_on(async {
+ for cold in [false, true] {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ let task = json!({
+ "__typename": "GraphqlSoupDocument", "id": "task", "name": "Task",
+ "fileType": "md", "ownerId": "viewer", "properties": [],
+ "subType": { "__typename": "GraphqlTaskSubType", "isCompleted": false }
+ });
+ hydrate(&mut engine, task).await;
+ let document_key = EntityKey::entity("GraphqlSoupDocument", &["task"]);
+ let records = engine
+ .storage()
+ .get_batch(&[document_key.clone()])
+ .await
+ .unwrap();
+ // Task subtypes have no id: normalization embeds the object in
+ // its document rather than creating a GraphqlTaskSubType ref.
+ assert!(
+ crate::meta::type_meta("GraphqlTaskSubType")
+ .unwrap()
+ .key_fields
+ .is_none()
+ );
+ let CacheValue::Object(subtype) = &records[0].as_ref().unwrap().fields["subType"]
+ else {
+ panic!("task subtype must stay embedded in its document");
+ };
+ assert_eq!(subtype["isCompleted"], CacheValue::Bool(false));
+ let selection =
+ RecordSelection::parse(include_str!("task_completion.graphql"), "TaskCompletion")
+ .unwrap();
+ if cold {
+ engine = Engine::new(engine.into_storage());
+ }
+ for completed in [true, false] {
+ // No title, owner, timestamp, or other parent field changes.
+ let patch = json!({
+ "__typename": "GraphqlSoupDocument", "id": "task",
+ "subType": { "__typename": "GraphqlTaskSubType", "isCompleted": completed }
+ });
+ let result = hydrate(&mut engine, patch.clone()).await;
+ assert_eq!(
+ result.write_result.changed,
+ BTreeSet::from([document_key.clone()])
+ );
+ assert_eq!(
+ result.search_changed_buckets,
+ BTreeSet::from(["task".into()]),
+ "cold={cold}"
+ );
+ // History/Quick Access materialize through fragment-rooted reads.
+ let items = engine
+ .read_records_by_keys(&selection, std::slice::from_ref(&document_key))
+ .await
+ .unwrap();
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].record["subType"]["isCompleted"], json!(completed));
+ let duplicate = hydrate(&mut engine, patch).await;
+ assert!(
+ duplicate.search_changed_buckets.is_empty(),
+ "identical completion must not refresh"
+ );
+ }
+ }
+ });
+}
+
+#[test]
+fn hydration_reports_search_changes_without_needing_a_loaded_search_catalog() {
+ pollster::block_on(async {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ let mut document = json!({
+ "__typename": "GraphqlSoupDocument", "id": "doc", "name": "Note",
+ "fileType": "md", "ownerId": "viewer", "properties": []
+ });
+ assert_eq!(
+ hydrate(&mut engine, document.clone())
+ .await
+ .search_changed_buckets,
+ BTreeSet::from(["note".into()])
+ );
+ assert!(
+ hydrate(&mut engine, document.clone())
+ .await
+ .search_changed_buckets
+ .is_empty()
+ );
+
+ // The before state can come from cold storage as well as the hot tier.
+ let mut engine = Engine::new(engine.into_storage());
+ document["properties"] = json!([{"id": "property-1"}]);
+ let result = hydrate(&mut engine, document.clone()).await;
+ assert!(result.write_result.revision_advanced);
+ assert!(!result.write_result.changed.is_empty());
+ assert!(result.search_changed_buckets.is_empty());
+
+ document["ownerId"] = json!("new-owner");
+ assert_eq!(
+ hydrate(&mut engine, document).await.search_changed_buckets,
+ BTreeSet::from(["note".into()])
+ );
+ assert_eq!(
+ hydrate(
+ &mut engine,
+ json!({
+ "__typename": "GraphqlSoupEmailThread", "id": "thread", "name": "Mail"
+ })
+ )
+ .await
+ .search_changed_buckets,
+ BTreeSet::from(["email".into()])
+ );
+ });
+}
diff --git a/crates/client/cache-core/src/engine/test/task_completion.graphql b/crates/client/cache-core/src/engine/test/task_completion.graphql
new file mode 100644
index 0000000000..9ea19233ed
--- /dev/null
+++ b/crates/client/cache-core/src/engine/test/task_completion.graphql
@@ -0,0 +1,6 @@
+fragment TaskCompletion on GraphqlSoupDocument {
+ subType {
+ __typename
+ ... on GraphqlTaskSubType { isCompleted }
+ }
+}
diff --git a/crates/client/cache-core/src/search.rs b/crates/client/cache-core/src/search.rs
index 6b4c3e2fe0..f9d5e118a5 100644
--- a/crates/client/cache-core/src/search.rs
+++ b/crates/client/cache-core/src/search.rs
@@ -12,6 +12,9 @@ use std::cmp::Ordering;
use std::collections::BTreeSet;
use thiserror::Error;
+mod changes;
+pub(crate) use changes::{collect_search_changes, snapshot_search_fields};
+
/// Current compact projection profile used by Quick Access, Cmd-K and entity
/// mention pickers. Profile names are persisted and therefore versioned.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -178,7 +181,10 @@ pub fn project_search_documents(key: &EntityKey<'static>, record: &Record) -> Ve
project_quick_access(key, record).into_iter().collect()
}
-fn project_quick_access(key: &EntityKey<'static>, record: &Record) -> Option<SearchDocument> {
+fn quick_access_fields<'a>(
+ key: &'a EntityKey<'_>,
+ record: &'a Record,
+) -> Option<(&'a str, &'static str, &'static [&'static str])> {
if key.is_root() || key.as_ref().starts_with("__meta:") || !is_present(record) {
return None;
}
@@ -200,6 +206,14 @@ fn project_quick_access(key: &EntityKey<'static>, record: &Record) -> Option<Sea
_ => return None,
};
+ text_fields
+ .iter()
+ .any(|field| record.fields.contains_key(*field))
+ .then_some((typename, bucket, text_fields))
+}
+
+fn project_quick_access(key: &EntityKey<'static>, record: &Record) -> Option<SearchDocument> {
+ let (typename, bucket, text_fields) = quick_access_fields(key, record)?;
let search_text = normalize_search_text(
text_fields
.iter()
@@ -209,14 +223,6 @@ fn project_quick_access(key: &EntityKey<'static>, record: &Record) -> Option<Sea
.join(" | ")
.as_str(),
);
- if search_text.is_empty()
- && !text_fields
- .iter()
- .any(|field| record.fields.contains_key(*field))
- {
- return None;
- }
-
Some(SearchDocument {
profile: SearchProfile::QuickAccessV1,
record_key: key.clone(),
diff --git a/crates/client/cache-core/src/search/changes.rs b/crates/client/cache-core/src/search/changes.rs
new file mode 100644
index 0000000000..b957e7b11a
--- /dev/null
+++ b/crates/client/cache-core/src/search/changes.rs
@@ -0,0 +1,77 @@
+//! Hydration invalidation for Quick Access, without loading search catalogs or
+//! hashing unrelated record fields. Keep materialization fields aligned with
+//! the Quick Access fragments in history.graphql and crm.graphql.
+
+use super::quick_access_fields;
+use crate::value::{EntityKey, Record};
+use std::collections::BTreeSet;
+
+// Text fields and bucket eligibility come from the projection itself. These
+// additional fields affect ordering or the rows materialized from search hits.
+const PRESENTATION_FIELDS: &[&str] = &[
+ "ownerId",
+ "teamId",
+ "createdAt",
+ "updatedAt",
+ "viewedAt",
+ "interactedAt",
+ "sortTs",
+ "lastInteraction",
+ "fileType",
+ "subType",
+ "channelType",
+ "participants",
+];
+
+/// Retains only the projection/row fields needed for a before/after comparison.
+/// Large unrelated fields (email bodies, properties, cached Soup pages) are
+/// never cloned just to decide whether a consumer needs refreshing.
+pub(crate) fn snapshot_search_fields(key: &EntityKey<'_>, record: &Record) -> Option<Record> {
+ let (_, _, text_fields) = quick_access_fields(key, record)?;
+ let fields = text_fields
+ .iter()
+ .chain(PRESENTATION_FIELDS)
+ .chain(["__typename", "deletedAt", "hidden"].iter())
+ .filter_map(|field| {
+ record
+ .fields
+ .get(*field)
+ .map(|value| ((*field).to_owned(), value.clone()))
+ })
+ .collect();
+ Some(Record { fields })
+}
+
+/// Adds both old and new buckets when hydration changes a searchable row.
+/// Membership transitions (creation, hiding, deletion, subtype changes) must
+/// wake the old bucket too. Missing optional fields becoming available count
+/// as changes even when they do not affect fuzzy text or recency.
+pub(crate) fn collect_search_changes(
+ key: &EntityKey<'_>,
+ before: Option<&Record>,
+ after: Option<&Record>,
+ buckets: &mut BTreeSet<String>,
+) {
+ let previous = before.and_then(|record| quick_access_fields(key, record));
+ let next = after.and_then(|record| quick_access_fields(key, record));
+ let changed = match (previous, next) {
+ (None, None) => false,
+ (Some((old_type, old_bucket, _)), Some((new_type, new_bucket, text_fields)))
+ if old_type == new_type && old_bucket == new_bucket =>
+ {
+ text_fields.iter().chain(PRESENTATION_FIELDS).any(|field| {
+ before.and_then(|record| record.fields.get(*field))
+ != after.and_then(|record| record.fields.get(*field))
+ })
+ }
+ _ => true,
+ };
+ if changed {
+ for (_, bucket, _) in previous.into_iter().chain(next) {
+ buckets.insert(bucket.to_owned());
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/client/cache-core/src/search/changes/test.rs b/crates/client/cache-core/src/search/changes/test.rs
new file mode 100644
index 0000000000..e164b8807d
--- /dev/null
+++ b/crates/client/cache-core/src/search/changes/test.rs
@@ -0,0 +1,114 @@
+use super::*;
+use crate::value::CacheValue;
+
+fn record(typename: &str) -> Record {
+ Record {
+ fields: [
+ ("__typename".into(), CacheValue::String(typename.into())),
+ ("name".into(), CacheValue::String("Example".into())),
+ ]
+ .into(),
+ }
+}
+
+fn changes(typename: &str, before: Option<&Record>, after: Option<&Record>) -> BTreeSet<String> {
+ let mut buckets = BTreeSet::new();
+ collect_search_changes(
+ &EntityKey::entity(typename, &["one"]),
+ before,
+ after,
+ &mut buckets,
+ );
+ buckets
+}
+
+#[test]
+fn new_rows_and_deletions_report_only_their_projection_bucket() {
+ for (typename, bucket) in [
+ ("GraphqlSoupDocument", "document"),
+ ("GraphqlSoupEmailThread", "email"),
+ ("GraphqlSoupChannel", "channel"),
+ ("GraphqlSoupChat", "chat"),
+ ("GraphqlSoupProject", "project"),
+ ("GraphqlSoupCrmCompany", "crm_company"),
+ ] {
+ let value = record(typename);
+ let expected = BTreeSet::from([bucket.to_owned()]);
+ assert_eq!(changes(typename, None, Some(&value)), expected);
+ assert_eq!(changes(typename, Some(&value), None), expected);
+ assert!(changes(typename, Some(&value), Some(&value)).is_empty());
+ }
+}
+
+#[test]
+fn unrelated_fields_do_not_refresh_search_and_are_not_snapshotted() {
+ let typename = "GraphqlSoupDocument";
+ let before = record(typename);
+ let mut after = before.clone();
+ for field in ["properties", "notifications", "content", "comments"] {
+ after
+ .fields
+ .insert(field.into(), CacheValue::String("unrelated".into()));
+ }
+ assert!(changes(typename, Some(&before), Some(&after)).is_empty());
+ let snapshot = snapshot_search_fields(&EntityKey::entity(typename, &["one"]), &after).unwrap();
+ assert_eq!(snapshot, before);
+ assert!(changes("GraphqlProperty", None, Some(&record("GraphqlProperty"))).is_empty());
+}
+
+#[test]
+fn materialized_fields_and_newly_available_fields_trigger_refreshes() {
+ for typename in [
+ "GraphqlSoupDocument",
+ "GraphqlSoupChannel",
+ "GraphqlSoupCrmCompany",
+ ] {
+ let before = record(typename);
+ for field in [
+ "name",
+ "ownerId",
+ "createdAt",
+ "updatedAt",
+ "viewedAt",
+ "participants",
+ "teamId",
+ ] {
+ let mut after = before.clone();
+ after
+ .fields
+ .insert(field.into(), CacheValue::String("changed".into()));
+ assert!(
+ !changes(typename, Some(&before), Some(&after)).is_empty(),
+ "{typename}.{field}"
+ );
+ }
+ }
+}
+
+#[test]
+fn bucket_moves_and_hidden_rows_invalidate_the_old_bucket_too() {
+ let typename = "GraphqlSoupDocument";
+ let before = record(typename);
+ let mut after = before.clone();
+ after
+ .fields
+ .insert("fileType".into(), CacheValue::String("md".into()));
+ assert_eq!(
+ changes(typename, Some(&before), Some(&after)),
+ BTreeSet::from(["document".into(), "note".into()])
+ );
+ let visible = after.clone();
+ after.fields.insert("hidden".into(), CacheValue::Bool(true));
+ assert_eq!(
+ changes(typename, Some(&visible), Some(&after)),
+ BTreeSet::from(["note".into()])
+ );
+ after.fields.remove("hidden");
+ after
+ .fields
+ .insert("deletedAt".into(), CacheValue::String("2026-09-29".into()));
+ assert_eq!(
+ changes(typename, Some(&visible), Some(&after)),
+ BTreeSet::from(["note".into()])
+ );
+}
diff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.toml
index bb9290d17e..51adbe3bae 100644
--- a/crates/client/cache-wasm/Cargo.toml
+++ b/crates/client/cache-wasm/Cargo.toml
@@ -2,10 +2,9 @@
edition = "2024"
name = "cache-wasm"
publish = false
-# Rebuild for entity-only Soup hydration, bounded page retention,
-# storage-version database names, stale-database cleanup, and waiting out
-# files a departing worker holds.
-version = "0.6.31"
+# Rebuild for bucket-scoped Quick Access hydration notifications.
+# Retains the storage-lifecycle fixes shipped in 0.6.31.
+version = "0.6.32"
[features]
default = []
diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rs
index dc026e5d59..fc0c55d5bc 100644
--- a/crates/client/cache-wasm/src/shell.rs
+++ b/crates/client/cache-wasm/src/shell.rs
@@ -160,6 +160,7 @@ struct JsWriteResult {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct JsHydrationWriteResult {
+ search_changed_buckets: std::collections::BTreeSet<String>,
revision: String,
revision_advanced: bool,
changed: Vec<String>,
@@ -1557,6 +1558,7 @@ impl CacheEngine {
.await;
let result = state.engine_result(result)?;
to_js(&JsHydrationWriteResult {
+ search_changed_buckets: result.search_changed_buckets,
revision: result.write_result.revision.to_string(),
revision_advanced: result.write_result.revision_advanced,
changed: result
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 078168bcce..fbb028a286 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -478,7 +478,11 @@ 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
+updates an already-open menu only when a bucket it uses changes. Email/body/tag-only
+hydration must not reread History or the cached channel list; a newly hydrated note
+refreshes History and matching menus, and a channel/DM refreshes channel consumers.
+Renames, ownership/recency changes, and moves between buckets must still appear
+without retyping. Older cache runtimes without bucket metadata refresh conservatively. 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