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/perf/limit churn from other tabs (#6836)

Sean Ayecb6222078139
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 cd60535421..8b75a17ce0 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
@@ -168,6 +168,7 @@ function page(start: number, count: number, more = false): SearchCachePage {
}
beforeEach(() => {
vi.clearAllMocks();
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
mocks.history = [];
mocks.companies = [];
mocks.crmEnabled = () => true;
@@ -187,7 +188,12 @@ beforeEach(() => {
}
);
});
-afterEach(() => dispose?.());
+afterEach(() => {
+ dispose?.();
+ dispose = undefined;
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
const cachedCompany = {
__typename: 'GraphqlSoupCrmCompany',
@@ -650,6 +656,35 @@ describe('Quick Access source integration', () => {
expect(mocks.unsubscribe).toHaveBeenCalledOnce();
});
+ it('keeps hidden lists stable and refreshes their latest state once on visibility', async () => {
+ vi.useFakeTimers();
+ const visibility = vi.spyOn(document, 'visibilityState', 'get');
+ mocks.search.mockResolvedValue(page(0, 1));
+ const list = setup((source) => source.useList({ buckets: ['note'] }));
+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));
+ expect(list.items().map((item) => item.id)).toEqual(['0']);
+ const initialCalls = mocks.search.mock.calls.length;
+
+ visibility.mockReturnValue('hidden');
+ document.dispatchEvent(new Event('visibilitychange'));
+ mocks.search.mockResolvedValue(page(1, 1));
+ mocks.changed?.();
+ mocks.changed?.();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.search).toHaveBeenCalledTimes(initialCalls);
+ expect(mocks.channelRefetch).not.toHaveBeenCalled();
+ expect(list.items().map((item) => item.id)).toEqual(['0']);
+
+ visibility.mockReturnValue('visible');
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.waitFor(() =>
+ expect(list.items().map((item) => item.id)).toEqual(['1'])
+ );
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.search).toHaveBeenCalledTimes(initialCalls + 1);
+ expect(mocks.channelRefetch).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),
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
index af50348a4e..6fc65a1ec0 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
@@ -32,11 +32,11 @@ import { useQuickAccessSkillsQuery } from '@queries/soup/quick-access-skills';
import { useQuickAccessSnippetsQuery } from '@queries/soup/quick-access-snippets';
import { useRecentlyViewedSoupQuery } from '@queries/soup/recently-viewed';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
+import { subscribeToVisibleCacheChanges } from '@queries/subscribe-to-visible-cache-changes';
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';
@@ -324,24 +324,14 @@ export function createQuickAccessValue(): QuickAccessContextValue {
const cacheHost = graphqlCacheHost?.disabled ? undefined : graphqlCacheHost;
const [cacheRevision, setCacheRevision] = createSignal(0);
const cachedChannelsQuery = useCachedGraphqlChannelsQuery(cacheHost);
- const refreshCachedLists = leadingAndTrailing(
- throttle,
- () => {
- setCacheRevision((revision) => revision + 1);
- void cachedChannelsQuery.refetch();
- },
- 250
- );
- const unsubscribeCacheChanges = cacheHost?.onCacheChanged(
- refreshCachedLists,
- {
- includeHydration: true,
- }
- );
- onCleanup(() => {
- unsubscribeCacheChanges?.();
- refreshCachedLists.clear();
- });
+ if (cacheHost) {
+ onCleanup(
+ subscribeToVisibleCacheChanges(cacheHost, () => {
+ setCacheRevision((revision) => revision + 1);
+ void cachedChannelsQuery.refetch();
+ })
+ );
+ }
const instructionsIdQuery = useInstructionsMdIdQuery();
const { query: crmCompaniesQuery, companies: crmCompaniesAccessor } =
useQuickAccessCrmCompaniesQuery();
diff --git a/apps/web/src/lib/graphql-cache/exchange/deferred-query-rereads.test.ts b/apps/web/src/lib/graphql-cache/exchange/deferred-query-rereads.test.ts
new file mode 100644
index 0000000000..35a354245f
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/exchange/deferred-query-rereads.test.ts
@@ -0,0 +1,118 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createDeferredQueryRereads } from './deferred-query-rereads';
+
+let visibility: DocumentVisibilityState;
+function setVisibility(value: DocumentVisibilityState) {
+ visibility = value;
+ document.dispatchEvent(new Event('visibilitychange'));
+}
+
+beforeEach(() => {
+ visibility = 'visible';
+ vi.spyOn(document, 'visibilityState', 'get').mockImplementation(
+ () => visibility
+ );
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+ setVisibility('visible');
+ vi.restoreAllMocks();
+});
+
+describe('deferred query rereads', () => {
+ it('runs immediately without a listener when visible', () => {
+ const listen = vi.spyOn(document, 'addEventListener');
+ const run = vi.fn();
+ const queue = createDeferredQueryRereads(run);
+ queue.request(1);
+ queue.request(2, true);
+ expect(run.mock.calls).toEqual([
+ [1, false],
+ [2, true],
+ ]);
+ expect(listen).not.toHaveBeenCalled();
+ });
+
+ it('coalesces hidden updates per operation and unregisters after catch-up', () => {
+ setVisibility('hidden');
+ const listen = vi.spyOn(document, 'addEventListener');
+ const unlisten = vi.spyOn(document, 'removeEventListener');
+ const run = vi.fn();
+ const queue = createDeferredQueryRereads(run);
+ for (let i = 0; i < 20; i++) queue.request(1);
+ queue.request(2, true);
+ expect(run).not.toHaveBeenCalled();
+ expect(listen).toHaveBeenCalledOnce();
+ setVisibility('hidden');
+ expect(run).not.toHaveBeenCalled();
+
+ setVisibility('visible');
+ expect(run.mock.calls).toEqual([
+ [1, false],
+ [2, true],
+ ]);
+ expect(unlisten).toHaveBeenCalledOnce();
+ setVisibility('visible');
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([
+ [true, false],
+ [false, true],
+ ])('keeps ordinary invalidation across %s then %s', (first, second) => {
+ setVisibility('hidden');
+ const run = vi.fn();
+ const queue = createDeferredQueryRereads(run);
+ queue.request(1, first);
+ queue.request(1, second);
+ setVisibility('visible');
+ expect(run).toHaveBeenCalledExactlyOnceWith(1, false);
+ });
+
+ it('consumes pending work if a visible push arrives before visibilitychange', () => {
+ setVisibility('hidden');
+ const run = vi.fn();
+ const queue = createDeferredQueryRereads(run);
+ queue.request(1);
+ visibility = 'visible';
+ queue.request(1, true);
+ expect(run).toHaveBeenCalledExactlyOnceWith(1, false);
+ setVisibility('visible');
+ expect(run).toHaveBeenCalledOnce();
+ });
+
+ it('forgets unmounted operations and their registration intent', () => {
+ setVisibility('hidden');
+ const unlisten = vi.spyOn(document, 'removeEventListener');
+ const run = vi.fn();
+ const queue = createDeferredQueryRereads(run);
+ queue.request(1);
+ queue.forget(1);
+ expect(unlisten).toHaveBeenCalledOnce();
+ setVisibility('visible');
+ expect(run).not.toHaveBeenCalled();
+ queue.request(1, true);
+ expect(run).toHaveBeenCalledExactlyOnceWith(1, true);
+ });
+
+ it('leaves later operations pending if the page hides during catch-up', () => {
+ setVisibility('hidden');
+ const run = vi.fn((key: number) => {
+ if (key === 1) setVisibility('hidden');
+ });
+ const queue = createDeferredQueryRereads(run);
+ queue.request(1);
+ queue.request(2);
+ setVisibility('visible');
+ expect(run).toHaveBeenCalledExactlyOnceWith(1, false);
+ setVisibility('visible');
+ expect(run).toHaveBeenLastCalledWith(2, false);
+ });
+
+ it('runs without browser visibility in non-page environments', () => {
+ vi.stubGlobal('document', undefined);
+ const run = vi.fn();
+ createDeferredQueryRereads(run).request(1);
+ expect(run).toHaveBeenCalledExactlyOnceWith(1, false);
+ });
+});
diff --git a/apps/web/src/lib/graphql-cache/exchange/deferred-query-rereads.ts b/apps/web/src/lib/graphql-cache/exchange/deferred-query-rereads.ts
new file mode 100644
index 0000000000..768f234e7d
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/exchange/deferred-query-rereads.ts
@@ -0,0 +1,55 @@
+/**
+ * Coalesces dependency-driven query rereads while this page is hidden. Initial
+ * queries, explicit refetches, writes, and worker recovery never enter this
+ * queue. Its visibility listener exists only while there is deferred work;
+ * teardown must forget an operation before its key can be reused.
+ */
+export function createDeferredQueryRereads(
+ run: (key: number, registrationOnly: boolean) => void
+) {
+ const page = typeof document === 'undefined' ? undefined : document;
+ const pending = new Map<number, boolean>();
+ let listening = false;
+
+ const stopListening = () => {
+ if (!listening) return;
+ page?.removeEventListener('visibilitychange', flush);
+ listening = false;
+ };
+
+ function request(key: number, registrationOnly = false): void {
+ // An ordinary invalidation must not be weakened by a later recovery-only
+ // registration request, which is forbidden from falling back to the API.
+ const onlyRegister = (pending.get(key) ?? true) && registrationOnly;
+ pending.delete(key);
+ if (page?.visibilityState === 'hidden') {
+ pending.set(key, onlyRegister);
+ if (!listening) {
+ page.addEventListener('visibilitychange', flush);
+ listening = true;
+ }
+ return;
+ }
+ if (pending.size === 0) stopListening();
+ run(key, onlyRegister);
+ }
+
+ function flush(): void {
+ if (page?.visibilityState === 'hidden') return;
+ const entries = [...pending];
+ pending.clear();
+ stopListening();
+ // Use request again in case the page hides during a catch-up callback.
+ for (const [key, registrationOnly] of entries) {
+ request(key, registrationOnly);
+ }
+ }
+
+ return {
+ request,
+ forget(key: number) {
+ pending.delete(key);
+ if (pending.size === 0) stopListening();
+ },
+ };
+}
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
index 3c8bd525f6..5e37d6ea6f 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
@@ -15,7 +15,7 @@ import {
type OperationResult,
stringifyDocument,
} from '@urql/core';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
makeSubject,
map,
@@ -1564,6 +1564,228 @@ describe('normalizedCacheExchange', () => {
expect(vi.mocked(client.reexecuteOperation)).not.toHaveBeenCalled();
});
+ describe('hidden-page affected rereads', () => {
+ let visibility: DocumentVisibilityState;
+ const setVisibility = (value: DocumentVisibilityState) => {
+ visibility = value;
+ document.dispatchEvent(new Event('visibilitychange'));
+ };
+ beforeEach(() => {
+ visibility = 'visible';
+ vi.spyOn(document, 'visibilityState', 'get').mockImplementation(
+ () => visibility
+ );
+ });
+ afterEach(() => {
+ setVisibility('visible');
+ vi.restoreAllMocks();
+ });
+
+ it('keeps previous results while hidden and catches up only mounted operations', async () => {
+ host.scriptRead({ kind: 'hit', data: { status: 'old' } });
+ const { ops, results, client } = controlledQueryHarness(host);
+ const first = makeOp(71);
+ const second = makeOp(72, 'cache-only');
+ ops.next(first);
+ ops.next(second);
+ await tick();
+ setVisibility('hidden');
+ host.scriptRead({ kind: 'hit', data: { status: 'latest' } });
+ host.pushAffected([71, 72, 999]);
+ host.pushAffected([71, 72]);
+ ops.next(teardownOf(second));
+ await tick();
+ expect(host.reads).toHaveLength(2);
+ expect(results.map((result) => result.data)).toEqual([
+ { status: 'old' },
+ { status: 'old' },
+ ]);
+ expect(client.reexecuteOperation).not.toHaveBeenCalled();
+
+ setVisibility('visible');
+ await tick();
+ expect(client.reexecuteOperation).toHaveBeenCalledOnce();
+ expect(host.reads).toHaveLength(3);
+ expect(host.reads.at(-1)).toMatchObject({
+ opKey: 71,
+ priority: 'user-visible',
+ });
+ expect(results.at(-1)?.data).toEqual({ status: 'latest' });
+ setVisibility('visible');
+ await tick();
+ expect(host.reads).toHaveLength(3);
+ });
+
+ it('allows initial queries, explicit refetches, saves, and subscription writes while hidden', async () => {
+ setVisibility('hidden');
+ host.scriptRead({ kind: 'hit', data: { status: 'old' } });
+ const { ops, results, forwarded, client } = harness(host);
+ ops.next(makeOp(71));
+ await tick();
+ host.pushAffected([71]);
+ ops.next(makeOp(71, 'network-only'));
+ ops.next(makeMutationOp(73, { setEntityProperty: { id: 'prop-1' } }));
+ ops.next(makeSubscriptionOp(74));
+ await tick();
+ expect(host.reads).toHaveLength(1);
+ expect(client.reexecuteOperation).not.toHaveBeenCalled();
+ expect(forwarded.map((op) => op.kind)).toContain('query');
+ expect(host.begins).toHaveLength(1);
+ expect(host.commits).toHaveLength(1);
+ expect(host.writes).toHaveLength(1);
+ expect(
+ results.find((result) => result.operation.kind === 'mutation')
+ ).toMatchObject({
+ extensions: {
+ normalizedCacheMutationDisposition: { kind: 'committed' },
+ },
+ });
+ // An actual subscription payload must also write through, not just pass
+ // its operation down the transport while hidden.
+ const subscription = harness(host, () => ({ data: { live: true } }));
+ subscription.ops.next(makeSubscriptionOp(75));
+ await tick();
+ expect(host.writes.at(-1)?.data).toEqual({ live: true });
+ });
+
+ it.each([false, true])(
+ 'preserves an authoritative request across catch-up (already pending=%s)',
+ async (alreadyPending) => {
+ host.scriptRead({ kind: 'hit', data: { status: 'old' } });
+ const { ops, network, results, forwarded, client } =
+ controlledQueryHarness(host);
+ ops.next(
+ makeOp(71, alreadyPending ? 'cache-and-network' : 'cache-first')
+ );
+ await tick();
+ setVisibility('hidden');
+ host.scriptRead({ kind: 'hit', data: { status: 'optimistic' } });
+ host.pushAffected([71]);
+ host.pushAffected([71]);
+ if (!alreadyPending) ops.next(makeOp(71, 'network-only'));
+ await tick();
+ expect(host.reads).toHaveLength(1);
+ expect(results).toHaveLength(1);
+ expect(forwarded).toHaveLength(1);
+
+ setVisibility('visible');
+ await tick();
+ expect(host.reads).toHaveLength(2);
+ expect(results.at(-1)).toMatchObject({
+ data: { status: 'optimistic' },
+ stale: true,
+ });
+ expect(client.reexecuteOperation).not.toHaveBeenCalled();
+ expect(forwarded).toHaveLength(1);
+ network.next({
+ operation: forwarded[0]!,
+ data: { status: 'committed' },
+ stale: false,
+ hasNext: false,
+ });
+ await tick();
+ expect(results.at(-1)?.data).toEqual({ status: 'committed' });
+ expect(host.writes).toHaveLength(1);
+ expect(forwarded).toHaveLength(1);
+ }
+ );
+
+ it('keeps cache-only catch-up misses off the network', async () => {
+ const { ops, forwarded, client } = controlledQueryHarness(host);
+ ops.next(makeOp(71, 'cache-only'));
+ await tick();
+ setVisibility('hidden');
+ host.pushAffected([71]);
+ expect(host.reads).toHaveLength(1);
+ setVisibility('visible');
+ await tick();
+ expect(host.reads).toHaveLength(2);
+ expect(forwarded).toHaveLength(0);
+ expect(client.reexecuteOperation).toHaveBeenCalledOnce();
+ expect(
+ vi.mocked(client.reexecuteOperation).mock.calls[0]?.[0].context
+ .requestPolicy
+ ).toBe('cache-only');
+ });
+
+ it('defers a network-completion reread without losing its registration-only policy', async () => {
+ const read = host.readQuery.bind(host);
+ host.readQuery = async (args) => {
+ const result = await read(args);
+ if (host.reads.length === 1) {
+ throw Object.assign(new Error('old owner lost'), {
+ errorCode: 'owner-epoch-lost',
+ });
+ }
+ return result;
+ };
+ const { ops, network, forwarded, client } = controlledQueryHarness(host);
+ ops.next(makeOp(71));
+ await tick();
+ setVisibility('hidden');
+ host.pushAffected([71]);
+ network.next({
+ operation: forwarded[0]!,
+ data: undefined,
+ stale: false,
+ hasNext: false,
+ });
+ await tick();
+ expect(host.reads).toHaveLength(1);
+ expect(client.reexecuteOperation).not.toHaveBeenCalled();
+ setVisibility('visible');
+ await tick();
+ expect(host.reads).toHaveLength(2);
+ expect(forwarded).toHaveLength(1);
+ expect(
+ vi.mocked(client.reexecuteOperation).mock.calls[0]?.[0].context
+ ).toMatchObject({ normalizedCacheReplacementRegistrationOnly: true });
+
+ host.pushAffected([71]);
+ await tick();
+ expect(forwarded).toHaveLength(2);
+ expect(
+ vi.mocked(client.reexecuteOperation).mock.calls[1]?.[0].context
+ ).toMatchObject({ normalizedCacheReplacementRegistrationOnly: false });
+ });
+
+ it('continues restoring retained network data into a replacement worker while hidden', async () => {
+ const read = host.readQuery.bind(host);
+ host.readQuery = async (args) => {
+ await read(args);
+ throw Object.assign(new Error('old owner lost'), {
+ errorCode: 'owner-epoch-lost',
+ });
+ };
+ const write = host.writeQuery.bind(host);
+ host.writeQuery = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('replacement not ready'))
+ .mockImplementation(write);
+ const { ops, network, forwarded, client } = controlledQueryHarness(host);
+ ops.next(makeOp(71));
+ await tick();
+ setVisibility('hidden');
+ network.next({
+ operation: forwarded[0]!,
+ data: { status: 'committed' },
+ stale: false,
+ hasNext: false,
+ });
+ await tick();
+ host.pushAffected([71]);
+ await tick();
+ expect(host.writeQuery).toHaveBeenCalledTimes(2);
+ expect(host.writes.at(-1)).toMatchObject({
+ data: { status: 'committed' },
+ registerDependencies: true,
+ });
+ expect(host.reads).toHaveLength(1);
+ expect(forwarded).toHaveLength(1);
+ expect(client.reexecuteOperation).not.toHaveBeenCalled();
+ });
+ });
+
describe('mutations', () => {
const optimistic = { setEntityProperty: { id: 'prop-1' } };
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
index 6bc4ea1177..01eba051d0 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
@@ -70,6 +70,7 @@ import {
isOwnerEpochLostError,
type QueryRevalidationWire,
} from '../protocol';
+import { createDeferredQueryRereads } from './deferred-query-rereads';
import {
compileEntityResolvers,
type EntityResolverConfig,
@@ -627,6 +628,23 @@ export function normalizedCacheExchange(
.catch((error) => options.onCacheError?.(error, operation));
};
+ const affectedRereads = createDeferredQueryRereads(
+ (key, registrationOnly) => {
+ if (!activeOps.has(key)) return;
+ const state = queryStates.get(key);
+ // A request or worker replacement may have started while this read was
+ // deferred. Re-check current state instead of replaying a stale action.
+ if (state?.retainedReplacementFallback) {
+ recoverRetainedReplacementFallback(key);
+ } else if (state && state.networkBoundQueries > 0) {
+ state.deferredAffected = true;
+ if (!state.replacementFallback) emitAffectedWhileNetworkBound(key);
+ } else {
+ reexecuteAffected(key, registrationOnly);
+ }
+ }
+ );
+
const unsubscribePush = host.onOpsAffected((opKeys) => {
for (const key of opKeys) {
if (!activeOps.has(key)) continue;
@@ -637,7 +655,7 @@ export function normalizedCacheExchange(
!state.replacementFallback &&
!state.retainedReplacementFallback
) {
- emitAffectedWhileNetworkBound(key);
+ affectedRereads.request(key);
}
continue;
}
@@ -648,7 +666,7 @@ export function normalizedCacheExchange(
recoverRetainedReplacementFallback(key);
continue;
}
- reexecuteAffected(key, registrationOnly);
+ affectedRereads.request(key, registrationOnly);
}
});
@@ -684,8 +702,8 @@ export function normalizedCacheExchange(
if (!replacementRegistrationSatisfied) {
if (state.retainedReplacementFallback) {
recoverRetainedReplacementFallback(key);
- } else {
- reexecuteAffected(key, true);
+ } else if (activeOps.has(key)) {
+ affectedRereads.request(key, true);
}
}
} else if (replacementFallback) {
@@ -1374,6 +1392,7 @@ export function normalizedCacheExchange(
if (op.kind === 'teardown') {
activeOps.delete(op.key);
queryStates.delete(op.key);
+ affectedRereads.forget(op.key);
host.teardown(op.key).catch(() => undefined);
}
})
diff --git a/apps/web/src/lib/queries/history/history.ts b/apps/web/src/lib/queries/history/history.ts
index 693d824b3f..2d0a2599c8 100644
--- a/apps/web/src/lib/queries/history/history.ts
+++ b/apps/web/src/lib/queries/history/history.ts
@@ -4,7 +4,6 @@ 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,
@@ -15,6 +14,7 @@ import {
} from '@tanstack/solid-query';
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 { historyKeys } from './keys';
import { transformHistoryItem, transformHistoryResponse } from './transforms';
@@ -25,7 +25,6 @@ export type { HistoryItem } from './types';
const HISTORY_STALE_TIME = 5 * 60 * 1000;
const HISTORY_GC_TIME = 10 * 60 * 1000;
-const HISTORY_CACHE_REFRESH_INTERVAL_MS = 250;
type HistoryQueryFnResult = HistoryItem[];
@@ -104,22 +103,13 @@ export function useHistoryQuery() {
createEffect(() => {
const host = graphqlCacheHost();
if (!host) return;
- const refresh = leadingAndTrailing(
- throttle,
- () => {
+ onCleanup(
+ subscribeToVisibleCacheChanges(host, () => {
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<
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 11952ef222..43d6c84765 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,7 +1,7 @@
import type { CacheChangeOptions } from '@graphql-cache/host/types';
-import { render, waitFor } from '@solidjs/testing-library';
+import { cleanup, render, waitFor } from '@solidjs/testing-library';
import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useHistoryQuery } from '../history';
const mocks = vi.hoisted(() => ({
@@ -32,7 +32,68 @@ vi.mock('@queries/history/graphql', () => ({
vi.mock('@queries/client', () => ({ queryClient: {} }));
vi.mock('@queries/utils', () => ({ withCallbacks: vi.fn() }));
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.readHistory.mockReset();
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
+});
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
describe('cache-backed history refresh', () => {
+ it('coalesces hidden cache changes without hiding the previous history', async () => {
+ const visibility = vi.spyOn(document, 'visibilityState', 'get');
+ let notify: (() => void) | undefined;
+ mocks.subscribe.mockImplementation((callback: () => void) => {
+ notify = callback;
+ return mocks.unsubscribe;
+ });
+ const original = {
+ id: 'original',
+ name: 'Original task',
+ type: 'document',
+ ownerId: 'owner',
+ };
+ const latest = { ...original, name: 'Updated task' };
+ mocks.readHistory.mockResolvedValue([original]);
+ 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));
+ const initialCalls = mocks.readHistory.mock.calls.length;
+ vi.useFakeTimers();
+ visibility.mockReturnValue('hidden');
+ document.dispatchEvent(new Event('visibilitychange'));
+ mocks.readHistory.mockResolvedValue([latest]);
+ notify?.();
+ notify?.();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.readHistory).toHaveBeenCalledTimes(initialCalls);
+ expect(query?.data).toEqual([original]);
+
+ visibility.mockReturnValue('visible');
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.readHistory).toHaveBeenCalledTimes(initialCalls + 1);
+ expect(query?.data).toEqual([latest]);
+ expect(mocks.fetchHistory).not.toHaveBeenCalled();
+ view.unmount();
+ client.clear();
+ });
+
it('opts into hydration, refreshes only local history, and unsubscribes on disposal', async () => {
let notify: (() => void) | undefined;
mocks.subscribe.mockImplementation(
diff --git a/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.test.ts b/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.test.ts
new file mode 100644
index 0000000000..3791efc108
--- /dev/null
+++ b/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.test.ts
@@ -0,0 +1,138 @@
+import type { CacheHost } from '@graphql-cache/host/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { subscribeToVisibleCacheChanges } from './subscribe-to-visible-cache-changes';
+
+let visibility: DocumentVisibilityState;
+let dispose: (() => void) | undefined;
+
+function setVisibility(value: DocumentVisibilityState) {
+ visibility = value;
+ document.dispatchEvent(new Event('visibilitychange'));
+}
+
+function setup() {
+ let notify = () => {};
+ const unsubscribe = vi.fn();
+ const host = {
+ onCacheChanged: vi.fn((callback: () => void) => {
+ notify = callback;
+ return unsubscribe;
+ }),
+ } satisfies Pick<CacheHost, 'onCacheChanged'>;
+ const refresh = vi.fn();
+ dispose = subscribeToVisibleCacheChanges(host, refresh);
+ return { host, notify, refresh, unsubscribe };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ visibility = 'visible';
+ vi.spyOn(document, 'visibilityState', 'get').mockImplementation(
+ () => visibility
+ );
+});
+afterEach(() => {
+ dispose?.();
+ dispose = undefined;
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe('subscribeToVisibleCacheChanges', () => {
+ it('retains leading/trailing throttling and hydration updates when visible', () => {
+ const { host, notify, refresh } = setup();
+ expect(host.onCacheChanged).toHaveBeenCalledWith(expect.any(Function), {
+ includeHydration: true,
+ });
+ notify();
+ expect(refresh).toHaveBeenCalledOnce();
+ notify();
+ notify();
+ vi.advanceTimersByTime(249);
+ expect(refresh).toHaveBeenCalledOnce();
+ vi.advanceTimersByTime(1);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it('coalesces hidden notifications into one immediate catch-up on visibility', () => {
+ setVisibility('hidden');
+ const { notify, refresh } = setup();
+ for (let i = 0; i < 20; i++) notify();
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersByTime(1000);
+ expect(refresh).not.toHaveBeenCalled();
+
+ setVisibility('visible');
+ expect(refresh).toHaveBeenCalledOnce();
+ vi.advanceTimersByTime(1000);
+ expect(refresh).toHaveBeenCalledOnce();
+ setVisibility('hidden');
+ setVisibility('visible');
+ expect(refresh).toHaveBeenCalledOnce();
+ });
+
+ it('retains a pending trailing refresh when the tab becomes hidden', () => {
+ const { notify, refresh } = setup();
+ notify();
+ notify();
+ setVisibility('hidden');
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersByTime(1000);
+ expect(refresh).toHaveBeenCalledOnce();
+
+ setVisibility('visible');
+ expect(refresh).toHaveBeenCalledTimes(2);
+ vi.advanceTimersByTime(1000);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it('checks visibility again when a scheduled callback runs', () => {
+ const { notify, refresh } = setup();
+ notify();
+ notify();
+ // Model the visibility event arriving after the timer fires.
+ visibility = 'hidden';
+ vi.advanceTimersByTime(250);
+ expect(refresh).toHaveBeenCalledOnce();
+ setVisibility('visible');
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps changes arriving after a catch-up refresh', () => {
+ const { notify, refresh } = setup();
+ setVisibility('hidden');
+ notify();
+ setVisibility('visible');
+ notify();
+ vi.advanceTimersByTime(250);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not refresh a clean tab when it becomes visible', () => {
+ const { refresh } = setup();
+ setVisibility('hidden');
+ setVisibility('visible');
+ vi.advanceTimersByTime(1000);
+ expect(refresh).not.toHaveBeenCalled();
+ });
+
+ it.each(['hidden', 'visible'] as const)(
+ 'disposes notifications, visibility handling, and timers while %s',
+ (state) => {
+ const { notify, refresh, unsubscribe } = setup();
+ setVisibility(state);
+ notify();
+ notify();
+ dispose?.();
+ dispose = undefined;
+ expect(unsubscribe).toHaveBeenCalledOnce();
+ const count = refresh.mock.calls.length;
+ notify();
+ setVisibility('hidden');
+ setVisibility('visible');
+ vi.advanceTimersByTime(1000);
+ expect(refresh).toHaveBeenCalledTimes(count);
+ expect(vi.getTimerCount()).toBe(0);
+ }
+ );
+});
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
new file mode 100644
index 0000000000..443eee6ce9
--- /dev/null
+++ b/apps/web/src/lib/queries/subscribe-to-visible-cache-changes.ts
@@ -0,0 +1,57 @@
+import type { CacheHost } from '@graphql-cache/host/types';
+import { makeEventListener } from '@solid-primitives/event-listener';
+import { leadingAndTrailing, throttle } from '@solid-primitives/scheduled';
+
+const CACHE_REFRESH_INTERVAL_MS = 250;
+
+/**
+ * Throttles cache-driven UI refreshes while visible. Hidden tabs retain one
+ * dirty bit instead of repeatedly reading the shared cache; becoming visible
+ * refreshes once against its latest state. This does not pause cache ingestion,
+ * mutations, or explicit/initial query requests.
+ *
+ * The caller must unsubscribe on disposal.
+ */
+export function subscribeToVisibleCacheChanges(
+ host: Pick<CacheHost, 'onCacheChanged'>,
+ refresh: () => void
+): () => void {
+ let dirty = false;
+ let disposed = false;
+ const isVisible = () => document.visibilityState === 'visible';
+ const scheduled = leadingAndTrailing(
+ throttle,
+ () => {
+ // Visibility can change between scheduling and the trailing callback.
+ if (disposed || !dirty || !isVisible()) return;
+ dirty = false;
+ refresh();
+ },
+ CACHE_REFRESH_INTERVAL_MS
+ );
+ const unsubscribe = host.onCacheChanged(
+ () => {
+ if (disposed) return;
+ dirty = true;
+ if (isVisible()) scheduled();
+ },
+ { includeHydration: true }
+ );
+ const removeVisibilityListener = makeEventListener(
+ document,
+ 'visibilitychange',
+ () => {
+ // Cancel pending background work without losing its dirty state. Reset
+ // the throttle so a visible tab catches up immediately, not on a timer.
+ scheduled.clear();
+ if (dirty && !disposed && isVisible()) scheduled();
+ }
+ );
+
+ return () => {
+ disposed = true;
+ unsubscribe();
+ removeVisibilityListener();
+ scheduled.clear();
+ };
+}
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.md
index 034ef7e034..1e28ac8c3d 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/AGENT_GUIDE/tasks.md
@@ -99,6 +99,17 @@ it during that delay should not let the earlier save close the new picker.
A failed save uses the mutation's rollback/error handling; it must not reopen
the picker or trigger a success refresh.
+For multi-tab status checks, open the same task in several browser tabs
+and change status repeatedly in the visible tab. Hidden tabs defer cache-change
+refreshes for Quick Access searches, its channel list, and history, plus
+cache-triggered GraphQL query rereads. Switching back catches up each affected
+reader once against the latest cache state; closed readers must not restart.
+Existing rows remain available while hidden. Initial loads, explicit requests,
+saves, realtime cache writes, worker recovery, and the shared cache worker still
+run. A query already fetching from the server must finish normally rather than
+be canceled/reissued on return. Verify task status, mention search, and history
+catch up after switching tabs, including when the cache-owning tab is hidden.
+
## Messages as tasks
In any channel composer, toggle the `Task` switch before sending to create a task from the