Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(graphql-soup): gate cache sessions and defer draft recovery (#7923)

teoff1a00124a47
diff --git a/apps/web/src/lib/core/auth/logout.test.ts b/apps/web/src/lib/core/auth/logout.test.ts
index 8b45185d22..d915843ed5 100644
--- a/apps/web/src/lib/core/auth/logout.test.ts
+++ b/apps/web/src/lib/core/auth/logout.test.ts
@@ -32,9 +32,6 @@ vi.mock('@queries/email/local-drafts', () => ({
vi.mock('@core/constant/servers', () => ({
SERVER_HOSTS: { 'auth-logout': 'https://auth.example.com/oauth2/logout' },
}));
-vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
- isNativeMobilePlatform: vi.fn(() => false),
-}));
vi.mock('@core/util/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('@core/util/platform')>()),
isTauri,
@@ -43,6 +40,9 @@ vi.mock('@core/util/cookies', () => ({ syncLoginStorage: vi.fn() }));
vi.mock('@graphql-cache/lifecycle', () => ({
clearRegisteredCaches: vi.fn(async () => {}),
}));
+vi.mock('@service-storage/graphql-soup', () => ({
+ setGraphqlSoupSessionActive: vi.fn(),
+}));
vi.mock('@queries/auth/user-info', () => ({
authKeys: {
userInfo: { queryKey: ['auth', 'user-info'] },
@@ -59,15 +59,34 @@ vi.mock('./push-registration-lifecycle', () => ({
unregisterPushRegistrationsForLogout: vi.fn(async () => {}),
}));
+import { clearRegisteredCaches } from '@graphql-cache/lifecycle';
import {
clearLocalDrafts,
flushLocalDrafts,
listLocalDrafts,
} from '@queries/email/local-drafts';
import { authServiceClient } from '@service-auth/client';
+import { setGraphqlSoupSessionActive } from '@service-storage/graphql-soup';
import { confirmDialog } from '@ui';
import { clearLocalAuthSession, useLogout } from './logout';
+describe('logout GraphQL session teardown', () => {
+ it('ends the GraphQL session only after the cache wipe', async () => {
+ client.current = new QueryClient();
+ const order: string[] = [];
+ vi.mocked(clearRegisteredCaches).mockImplementationOnce(async () => {
+ order.push('wipe');
+ });
+ vi.mocked(setGraphqlSoupSessionActive).mockImplementationOnce(() => {
+ order.push('teardown');
+ });
+ await clearLocalAuthSession();
+ expect(order).toEqual(['wipe', 'teardown']);
+ expect(setGraphqlSoupSessionActive).toHaveBeenCalledWith(false);
+ client.current.clear();
+ });
+});
+
describe('logout notification cache isolation', () => {
it('retires pending Done buckets and rotates the display-intent session', async () => {
const queryClient = new QueryClient();
diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.ts
index a0a092699c..8ed8c9f855 100644
--- a/apps/web/src/lib/core/auth/logout.ts
+++ b/apps/web/src/lib/core/auth/logout.ts
@@ -18,6 +18,7 @@ import { resetGraphqlSoupDoneSession } from '@queries/soup/graphql/done-session'
import { clearDocumentQueryCache } from '@queries/storage/document-cache';
import { clearOfflineDocumentContexts } from '@queries/storage/documentLoad/offline-context-runtime';
import { authServiceClient } from '@service-auth/client';
+import { setGraphqlSoupSessionActive } from '@service-storage/graphql-soup';
import { raceTimeout } from '@solid-primitives/promise';
import { createCallback } from '@solid-primitives/rootless';
import { useNavigate } from '@solidjs/router';
@@ -61,6 +62,8 @@ export async function clearLocalAuthSession() {
if (results.some((result) => result.status === 'rejected')) {
await rotateCacheScope();
}
+ // Only after the wipes: clearing the cache needs its registered host.
+ setGraphqlSoupSessionActive(false);
resetGraphqlSoupDoneSession();
queryClient.setQueryData(authKeys.userInfo.queryKey, unauthenticatedUserInfo);
clearMcpAuthAttempts();
diff --git a/apps/web/src/lib/graphql-cache/exchange/mutation-queue-runner.ts b/apps/web/src/lib/graphql-cache/exchange/mutation-queue-runner.ts
index 5f8a6f700b..0f17662348 100644
--- a/apps/web/src/lib/graphql-cache/exchange/mutation-queue-runner.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/mutation-queue-runner.ts
@@ -64,6 +64,9 @@ const QUEUE_ATTEMPT_CONTEXT_KEY = 'normalizedCacheQueueAttempt';
export const QUEUE_REQUEST_TIMEOUT_MS = 60_000;
export const QUEUE_LEASE_MS = 5 * 60_000;
const EMPTY_QUEUE_POLL_MS = 30_000;
+// A deferred admission usually waits on user info, which lands within a
+// second or two of the cache client at startup.
+const DEFERRED_ADMISSION_RETRY_MS = 1_000;
const MAX_MUTATION_SERVER_FAILURES = 10;
const MUTATION_LIFECYCLE_TIMEOUT_MS = 2_000;
@@ -341,6 +344,7 @@ export function createMutationQueueRunner(
let head: HeadState = IDLE;
// Pump state: wakeups and the retry hint are independent of the head.
let queuePreparation: Promise<void> | undefined;
+ const reportedRecoveryFailures = new Set<string>();
let drainRunning = false;
let drainRequested = false;
let deferredUntil: number | undefined;
@@ -421,12 +425,16 @@ export function createMutationQueueRunner(
if (!transition(attempt, PREPARING)) return;
try {
if (options.prepareMutationQueue) await prepareQueueRecovery();
- if (
- options.beforeMutationAttempt &&
- !(await boundedMutationLifecycle(() =>
- options.beforeMutationAttempt!(claimed)
- ))
- ) {
+ const admission = options.beforeMutationAttempt
+ ? await boundedMutationLifecycle(() =>
+ options.beforeMutationAttempt!(claimed)
+ )
+ : true;
+ if (admission === 'defer') {
+ await deferAdmission(claimed, attempt);
+ return;
+ }
+ if (!admission) {
// preparing → settling → idle: discard obsolete local intent.
if (!transition(attempt, SETTLING)) return;
await host.rollbackOptimisticWrite(
@@ -528,6 +536,29 @@ export function createMutationQueueRunner(
resolveLiveOperationsAsQueued();
}
+ /** preparing → settling → idle, keeping a head its admission cannot judge yet. */
+ async function deferAdmission(
+ claimed: ClaimedMutation,
+ attempt: QueueAttemptContext
+ ): Promise<void> {
+ try {
+ if (!transition(attempt, SETTLING)) return;
+ await host.deferOptimisticWrite(
+ claimed.transactionId,
+ claimOf(attempt),
+ Date.now() + DEFERRED_ADMISSION_RETRY_MS,
+ 'Admission deferred'
+ );
+ } catch {
+ // The lease expires and the head is claimed again; nothing is lost.
+ } finally {
+ if (transition(attempt, IDLE)) {
+ resolveLiveOperationsAsQueued();
+ scheduleDrain(DEFERRED_ADMISSION_RETRY_MS);
+ }
+ }
+ }
+
/** preparing → settling → idle for a head whose recovery state failed. */
async function failPreparation(
claimed: ClaimedMutation,
@@ -590,6 +621,12 @@ export function createMutationQueueRunner(
}
async function drainQueue(): Promise<void> {
+ // A retired host stays disabled for good: stop polling instead of failing
+ // every 30 seconds against the no-op host.
+ if (host.disabled) {
+ resolveLiveOperationsAsQueued();
+ return;
+ }
if (isActive(head)) {
// Every newly enqueued operation is behind the claimed head. Its
// caller can stop waiting; durable replay now owns the mutation.
@@ -646,12 +683,19 @@ export function createMutationQueueRunner(
async function prepareQueueRecovery(): Promise<void> {
try {
- queuePreparation ??= boundedMutationLifecycle(() =>
- options.prepareMutationQueue!()
- );
+ queuePreparation ??= (async () => {
+ const prepared = await boundedMutationLifecycle(() =>
+ options.prepareMutationQueue!()
+ );
+ if (prepared === false) queuePreparation = undefined;
+ })();
await queuePreparation;
} catch (error) {
queuePreparation = undefined;
+ // A stuck tab retries every poll; one warning per cause is enough.
+ const cause = error instanceof Error ? error.message : String(error);
+ if (reportedRecoveryFailures.has(cause)) return;
+ reportedRecoveryFailures.add(cause);
console.warn(
'[graphql-cache] Unable to prepare mutation recovery',
error
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 59543ab739..6b1b2582da 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
@@ -34,6 +34,7 @@ import {
import { soupOptimisticResolvers } from '../../queries/optimistic-resolvers';
import { createUrqlQuery } from '../../urql-solid/create-urql-query';
import { CacheNavigationError } from '../host/navigation-error';
+import { createRetirableCacheHost } from '../host/retirable-host';
import type {
AffectedOperationsListener,
CacheGenerationChange,
@@ -3133,6 +3134,175 @@ describe('normalizedCacheExchange', () => {
}
);
+ it('warns once per recovery failure while the queue keeps polling', async () => {
+ vi.useFakeTimers();
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const prepareMutationQueue = vi.fn(async () => {
+ throw new Error('Queue inspection is unavailable');
+ });
+ harness(host, undefined, { prepareMutationQueue });
+ await vi.advanceTimersByTimeAsync(90_010);
+ expect(prepareMutationQueue).toHaveBeenCalledTimes(4);
+ expect(warning).toHaveBeenCalledOnce();
+ } finally {
+ warning.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
+ it('retries deferred recovery quietly until it can run', async () => {
+ vi.useFakeTimers();
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ let signedIn = false;
+ const prepareMutationQueue = vi.fn(async () =>
+ signedIn ? undefined : false
+ );
+ harness(host, undefined, { prepareMutationQueue });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(prepareMutationQueue).toHaveBeenCalledOnce();
+ signedIn = true;
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(prepareMutationQueue).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(prepareMutationQueue).toHaveBeenCalledTimes(2);
+ expect(warning).not.toHaveBeenCalled();
+ } finally {
+ warning.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
+ /** Like the draft lifecycle: drafts cannot be judged until user info loads. */
+ function signedInDraftLifecycle(): {
+ signIn(): void;
+ options: NormalizedCacheExchangeOptions;
+ } {
+ let signedIn = false;
+ return {
+ signIn: () => {
+ signedIn = true;
+ },
+ options: {
+ prepareMutationQueue: async () => (signedIn ? undefined : false),
+ beforeMutationAttempt: async (mutation) =>
+ signedIn || mutation.operationName !== 'SaveEmailDraft'
+ ? true
+ : 'defer',
+ },
+ };
+ }
+
+ function draftOp(key: number): Operation {
+ return makeOperation(
+ 'mutation',
+ createRequest(SaveEmailDraftDocument, {
+ input: { draftId: 'draft', subject: 'Draft' },
+ }),
+ makeMutationOp(key, optimistic).context
+ );
+ }
+
+ it('keeps a restored draft queued until sign-in instead of rolling it back', async () => {
+ vi.useFakeTimers();
+ try {
+ host.seedQueued({
+ uuid: 'draft',
+ query: stringifyDocument(SaveEmailDraftDocument),
+ operationName: 'SaveEmailDraft',
+ variables: { input: { draftId: 'draft' } },
+ data: optimistic,
+ clientMetadata: { kind: 'email-draft' },
+ });
+ const lifecycle = signedInDraftLifecycle();
+ const { forwarded } = harness(host, undefined, lifecycle.options);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(host.defers.length).toBeGreaterThan(1);
+ expect(host.rollbacks).toHaveLength(0);
+ expect(forwarded).toHaveLength(0);
+
+ lifecycle.signIn();
+ await vi.advanceTimersByTimeAsync(1_010);
+ expect(host.rollbacks).toHaveLength(0);
+ expect(forwarded).toHaveLength(1);
+ expect(host.commits).toMatchObject([{ transactionId: 'restored-1' }]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('sends other mutations while draft recovery waits for sign-in', async () => {
+ vi.useFakeTimers();
+ try {
+ host.seedQueued({
+ uuid: 'unrelated',
+ query: stringifyDocument(MUTATION),
+ operationName: 'SetEntityProperty',
+ variables: { input: {} },
+ data: optimistic,
+ });
+ const { forwarded } = harness(
+ host,
+ undefined,
+ signedInDraftLifecycle().options
+ );
+ await vi.advanceTimersByTimeAsync(10);
+ expect(forwarded).toHaveLength(1);
+ expect(host.defers).toHaveLength(0);
+ expect(host.commits).toMatchObject([{ transactionId: 'restored-1' }]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('defers a draft enqueued before sign-in instead of rolling it back', async () => {
+ vi.useFakeTimers();
+ try {
+ const lifecycle = signedInDraftLifecycle();
+ const { ops, results, forwarded } = harness(
+ host,
+ undefined,
+ lifecycle.options
+ );
+ ops.next(draftOp(1));
+ await vi.advanceTimersByTimeAsync(10);
+ expect(host.claims).toEqual(['txn-1']);
+ expect(host.defers).toMatchObject([{ transactionId: 'txn-1' }]);
+ expect(host.rollbacks).toHaveLength(0);
+ expect(forwarded).toHaveLength(0);
+ expect(results).toHaveLength(1);
+ expect(results[0]?.error).toBeUndefined();
+
+ lifecycle.signIn();
+ await vi.advanceTimersByTimeAsync(1_010);
+ expect(host.rollbacks).toHaveLength(0);
+ expect(forwarded).toHaveLength(1);
+ expect(host.commits).toMatchObject([{ transactionId: 'txn-1' }]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stops polling once its host is retired', async () => {
+ vi.useFakeTimers();
+ try {
+ const retirable = createRetirableCacheHost(host);
+ const drained = vi.spyOn(retirable, 'currentRevision');
+ harness(retirable);
+ await vi.advanceTimersByTimeAsync(10);
+ expect(drained).toHaveBeenCalledOnce();
+
+ retirable.dispose();
+ await vi.advanceTimersByTimeAsync(120_000);
+ dispatchEvent(new Event('online'));
+ await vi.advanceTimersByTimeAsync(10);
+ expect(drained).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it.each([
{ failure: 'rejects', legacy: false },
{ failure: 'hangs', legacy: false },
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 d3763746ec..382caab4ce 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
@@ -375,10 +375,19 @@ function uncertainEnqueueResult(op: Operation, error: Error): OperationResult {
}
export interface NormalizedCacheExchangeOptions {
- /** Best-effort startup recovery before per-mutation admission. */
- prepareMutationQueue?: () => Promise<void>;
- /** False discards obsolete client intent without sending it to the server. */
- beforeMutationAttempt?: (mutation: ClaimedMutation) => Promise<boolean>;
+ /**
+ * Best-effort startup recovery before per-mutation admission. Resolve
+ * `false` when it cannot run yet; the next drain asks again.
+ */
+ prepareMutationQueue?: () => Promise<boolean | void>;
+ /**
+ * False discards obsolete client intent without sending it to the server.
+ * `'defer'` keeps the mutation queued and asks again shortly, for intent
+ * that cannot be judged yet (a draft before its account is known).
+ */
+ beforeMutationAttempt?: (
+ mutation: ClaimedMutation
+ ) => Promise<boolean | 'defer'>;
/** Persist domain recovery state for a replayed result, including when its UI is closed. */
onMutationAttemptResult?: (
mutation: ClaimedMutation,
diff --git a/apps/web/src/lib/queries/email/local-drafts.test.ts b/apps/web/src/lib/queries/email/local-drafts.test.ts
index 15c36cfc3a..7a6fdbb80e 100644
--- a/apps/web/src/lib/queries/email/local-drafts.test.ts
+++ b/apps/web/src/lib/queries/email/local-drafts.test.ts
@@ -218,6 +218,37 @@ describe('draft queue recovery', () => {
await runtime.localDraftQueueLifecycle(host).prepareMutationQueue!();
expect((await runtime.readLocalDraft('local'))?.status).toBe('dirty');
});
+ it('defers recovery without a session and reconciles once signed in', async () => {
+ const draft = await runtime.saveLocalDraft(input());
+ const attempt = await runtime.beginDraftAttempt(draft, 'save');
+ await runtime.markDraftAttemptQueued(attempt);
+ const lifecycle = runtime.localDraftQueueLifecycle(host);
+ for (const user of [undefined, { authenticated: false, id: '' }]) {
+ auth.user = user as never;
+ await expect(lifecycle.prepareMutationQueue!()).resolves.toBe(false);
+ }
+ auth.user = { authenticated: true, id: 'owner' };
+ expect((await runtime.readLocalDraft('local'))?.status).toBe('queued');
+ await expect(lifecycle.prepareMutationQueue!()).resolves.toBeUndefined();
+ expect((await runtime.readLocalDraft('local'))?.status).toBe('unconfirmed');
+ });
+ it('defers a queued draft without a session instead of rejecting it', async () => {
+ const draft = await runtime.saveLocalDraft(input());
+ const attempt = await runtime.beginDraftAttempt(draft, 'save');
+ const lifecycle = runtime.localDraftQueueLifecycle(host);
+ for (const mutation of [claimed(attempt), claimed(undefined)]) {
+ for (const user of [undefined, { authenticated: false, id: '' }]) {
+ auth.user = user as never;
+ await expect(lifecycle.beforeMutationAttempt!(mutation)).resolves.toBe(
+ 'defer'
+ );
+ }
+ }
+ auth.user = { authenticated: true, id: 'owner' };
+ await expect(
+ lifecycle.beforeMutationAttempt!(claimed(attempt))
+ ).resolves.toBe(true);
+ });
it('marks an abandoned queued intent recoverable after restart', async () => {
const draft = await runtime.saveLocalDraft(input());
const attempt = await runtime.beginDraftAttempt(draft, 'save');
diff --git a/apps/web/src/lib/queries/email/local-drafts.ts b/apps/web/src/lib/queries/email/local-drafts.ts
index 2359a3e462..2d29a70864 100644
--- a/apps/web/src/lib/queries/email/local-drafts.ts
+++ b/apps/web/src/lib/queries/email/local-drafts.ts
@@ -718,8 +718,17 @@ export function localDraftQueueLifecycle(
throw new Error('Queued email draft disappeared before recovery');
return await preserveLegacy(queued);
}
+ const accountKnown = () => {
+ const user = queryClient.getQueryData<UserInfoData>(
+ authKeys.userInfo.queryKey
+ );
+ return !!user?.authenticated && !!user.id;
+ };
return {
async prepareMutationQueue() {
+ // Signed-out tabs have no drafts, and a signed-in tab's first drain
+ // can run before user info loads. Retry later instead of failing.
+ if (!accountKnown()) return false;
try {
initialized ??= prepare();
await initialized;
@@ -729,6 +738,16 @@ export function localDraftQueueLifecycle(
}
},
async beforeMutationAttempt(mutation) {
+ // Without the account, a draft cannot be checked against its working
+ // copy; rejecting it here would roll back the saved intent.
+ if (
+ !accountKnown() &&
+ (attemptOf(mutation) ||
+ legacy.has(mutation.transactionId) ||
+ mutation.operationName === 'SaveEmailDraft' ||
+ mutation.operationName === 'DeleteEmailDraft')
+ )
+ return 'defer';
const attempt = await resolveAttempt(mutation);
if (!attempt) return true;
const owner = await session();
diff --git a/apps/web/src/lib/queries/persistence.test.ts b/apps/web/src/lib/queries/persistence.test.ts
index bbd59bad02..b64995871e 100644
--- a/apps/web/src/lib/queries/persistence.test.ts
+++ b/apps/web/src/lib/queries/persistence.test.ts
@@ -1,4 +1,8 @@
-import { partialMatchKey } from '@tanstack/query-core';
+import {
+ keepPreviousData,
+ partialMatchKey,
+ QueryObserver,
+} from '@tanstack/query-core';
import { QueryClient } from '@tanstack/solid-query';
import { describe, expect, it, vi } from 'vitest';
import { authKeys } from './auth/keys';
@@ -654,6 +658,111 @@ describe('account persistence reset', () => {
queryClient.clear();
});
+ it('keeps mounted observers receiving query updates across a reset', async () => {
+ const queryClient = new QueryClient();
+ const persistence = setupQueryPersistence({
+ queryClient,
+ scopes: [createScope(['private'], createMockStore())],
+ });
+ const queryKey = ['session', 'user'];
+ queryClient.setQueryData(queryKey, { owner: 'alice' });
+ queryClient.setQueryData(['session', 'unobserved'], { owner: 'alice' });
+ const observer = new QueryObserver(queryClient, {
+ queryKey,
+ queryFn: () => new Promise<never>(() => {}),
+ enabled: false,
+ });
+ const results: unknown[] = [];
+ const unsubscribe = observer.subscribe((result) => {
+ results.push(result.data);
+ });
+
+ await persistence.clear();
+ expect(observer.getCurrentResult().data).toBeUndefined();
+ expect(
+ queryClient.getQueryCache().find({ queryKey: ['session', 'unobserved'] })
+ ).toBeUndefined();
+
+ queryClient.setQueryData(queryKey, { owner: 'bob' });
+ expect(observer.getCurrentResult().data).toEqual({ owner: 'bob' });
+ expect(results.at(-1)).toEqual({ owner: 'bob' });
+ unsubscribe();
+ persistence.dispose();
+ queryClient.clear();
+ });
+
+ it('removes account seeds without refetching or stranding mounted observers', async () => {
+ const queryClient = new QueryClient();
+ const persistence = setupQueryPersistence({
+ queryClient,
+ scopes: [createScope(['private'], createMockStore())],
+ });
+ const queryKey = ['private', 'seeded'];
+ const queryFn = vi.fn(async () => ({ owner: 'bob' }));
+ const observer = new QueryObserver(queryClient, {
+ queryKey,
+ queryFn,
+ initialData: { owner: 'alice' },
+ placeholderData: { owner: 'alice' },
+ staleTime: Infinity,
+ });
+ const unsubscribe = observer.subscribe(() => {});
+ expect(observer.getCurrentResult().data).toEqual({ owner: 'alice' });
+
+ await persistence.clear();
+ expect(observer.getCurrentResult().data).toBeUndefined();
+ expect(queryFn).not.toHaveBeenCalled();
+ observer.setOptions(observer.options);
+ expect(observer.getCurrentResult().data).toBeUndefined();
+ observer.setOptions({
+ ...observer.options,
+ placeholderData: keepPreviousData,
+ });
+ expect(observer.getCurrentResult().data).toBeUndefined();
+
+ // A later ordinary reset must not restore the old constructor's seed.
+ observer.setOptions({ ...observer.options, enabled: false });
+ await queryClient.resetQueries({ queryKey });
+ expect(observer.getCurrentResult().data).toBeUndefined();
+
+ queryClient.setQueryData(queryKey, { owner: 'bob' });
+ expect(observer.getCurrentResult().data).toEqual({ owner: 'bob' });
+ unsubscribe();
+ persistence.dispose();
+ queryClient.clear();
+ });
+
+ it('keeps periodic refetches working after clearing an observed query', async () => {
+ vi.useFakeTimers();
+ const queryClient = new QueryClient();
+ const persistence = setupQueryPersistence({
+ queryClient,
+ scopes: [createScope(['private'], createMockStore())],
+ });
+ const queryFn = vi.fn(async () => ({ owner: 'bob' }));
+ const observer = new QueryObserver(queryClient, {
+ queryKey: ['private', 'polling'],
+ queryFn,
+ initialData: { owner: 'alice' },
+ staleTime: Infinity,
+ refetchInterval: 1_000,
+ refetchIntervalInBackground: true,
+ });
+ const unsubscribe = observer.subscribe(() => {});
+ try {
+ await persistence.clear();
+ expect(queryFn).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(queryFn).toHaveBeenCalledOnce();
+ expect(observer.getCurrentResult().data).toEqual({ owner: 'bob' });
+ } finally {
+ unsubscribe();
+ persistence.dispose();
+ queryClient.clear();
+ vi.useRealTimers();
+ }
+ });
+
it('attempts every durable wipe even when one store fails', async () => {
const failing = createMockStore();
failing.clear = vi.fn(async () => {
diff --git a/apps/web/src/lib/queries/persistence.ts b/apps/web/src/lib/queries/persistence.ts
index f37c02f206..de29d24619 100644
--- a/apps/web/src/lib/queries/persistence.ts
+++ b/apps/web/src/lib/queries/persistence.ts
@@ -2,7 +2,12 @@ import {
type ParsedDuration,
parsedDurationToMilliseconds,
} from '@core/util/dateSearch/dateParser';
-import type { Query, QueryClient, QueryKey } from '@tanstack/query-core';
+import {
+ notifyManager,
+ type Query,
+ type QueryClient,
+ type QueryKey,
+} from '@tanstack/query-core';
import type {
ClearablePerQueryPersistence,
PersistedQueryEntry,
@@ -107,6 +112,63 @@ async function handleRestore(
});
}
+/**
+ * Drops account data and rebinds mounted observers to fresh queries. Resetting
+ * a query would restore its old initialData; removing it alone would strand
+ * observers on the retired query instead of delivering the next account's data.
+ */
+function clearQueryMemory(queryClient: QueryClient): void {
+ const queryCache = queryClient.getQueryCache();
+ notifyManager.batch(() => {
+ for (const query of queryCache.getAll()) {
+ const observers = query.observers.map((observer) => ({
+ observer,
+ options: {
+ ...observer.options,
+ initialData: undefined,
+ initialDataUpdatedAt: undefined,
+ placeholderData: undefined,
+ },
+ }));
+ for (const { observer, options } of observers) {
+ observer.setOptions(options);
+ }
+ // Observers also retain the last query with data for keepPreviousData.
+ // Empty that retired object, and fence its in-flight response first.
+ void query.cancel({ silent: true });
+ query.setState({
+ data: undefined,
+ dataUpdatedAt: 0,
+ error: null,
+ errorUpdatedAt: 0,
+ status: 'pending',
+ fetchStatus: 'idle',
+ });
+ queryCache.remove(query);
+
+ let rebinding = true;
+ for (const { observer, options } of observers) {
+ observer.setOptions({
+ ...options,
+ enabled: (current) =>
+ !rebinding &&
+ (typeof options.enabled === 'function'
+ ? options.enabled(current)
+ : options.enabled !== false),
+ });
+ }
+ // Restore the original enabled policy without starting a fetch while
+ // auth is being cleared. The prior callback now resolves the same way.
+ rebinding = false;
+ for (const { observer, options } of observers) {
+ observer.setOptions(options);
+ observer.onQueryUpdate();
+ }
+ }
+ });
+ queryClient.getMutationCache().clear();
+}
+
/**
* Persists a query's current data to IDB when the query updates successfully.
*/
@@ -219,7 +281,7 @@ export function setupQueryPersistence(
clearing = true;
restores = new WeakMap();
// Clear memory synchronously; removed-query events cannot race the reset.
- queryClient.clear();
+ clearQueryMemory(queryClient);
try {
const results = await Promise.allSettled(
scopes.map((scope) => scope.store.clear())
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
index 4044869a0d..e5481a9a6a 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
@@ -192,6 +192,7 @@ const mocks = vi.hoisted(() => {
let enabled = true;
let graphqlEnabled = true;
let tauri = false;
+ let signedIn = true;
let releaseApi: (() => void) | undefined;
let markApiStarted: (() => void) | undefined;
const apiStarted = () =>
@@ -250,6 +251,12 @@ const mocks = vi.hoisted(() => {
set tauri(value: boolean) {
tauri = value;
},
+ get signedIn() {
+ return signedIn;
+ },
+ set signedIn(value: boolean) {
+ signedIn = value;
+ },
host,
apiCall,
apiStarted,
@@ -310,6 +317,9 @@ vi.mock('@core/constant/featureFlags', () => ({
vi.mock('@core/constant/servers', () => ({
SERVER_HOSTS: { 'document-storage-service': 'http://dss.test' },
}));
+vi.mock('@core/util/cookies', () => ({
+ hasLoginCookie: () => mocks.signedIn,
+}));
vi.mock('@core/util/fetchWithToken', () => ({ fetchToken: vi.fn() }));
vi.mock('@core/util/reloadForNewerBuild', () => ({
reloadForNewerBuild: mocks.reloadForNewerBuild,
@@ -658,6 +668,7 @@ describe('GraphQL Soup browser cache session gate', () => {
mocks.enabled = true;
mocks.graphqlEnabled = true;
mocks.tauri = false;
+ mocks.signedIn = true;
mocks.resetQueue();
mocks.platformFetch.mockReset();
mocks.telemetryError.mockReset();
@@ -803,6 +814,76 @@ describe('GraphQL Soup browser cache session gate', () => {
);
});
+ it.each([true, false])(
+ 'builds neither the cache nor live updates while signed out (cache rollout: %s)',
+ async (cacheEnabled) => {
+ mocks.enabled = cacheEnabled;
+ mocks.signedIn = false;
+ const soup = await import('./graphql-soup');
+
+ expect(soup.getGraphqlSoupClient()).toBe(mocks.plainClient);
+ expect(soup.getGraphqlSoupCacheHost()).toBeUndefined();
+ expect(soup.graphqlCacheEnabled()).toBe(false);
+ expect(mocks.createWorkerCacheHost).not.toHaveBeenCalled();
+ expect(mocks.replaceSubscriptions).not.toHaveBeenCalled();
+
+ soup.setGraphqlSoupSessionActive(true);
+ expect(soup.getGraphqlSoupClient()).not.toBe(mocks.plainClient);
+ expect(mocks.replaceSubscriptions).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('moves readers that sampled the signed-out host onto the cache at sign-in', async () => {
+ mocks.signedIn = false;
+ const soup = await import('./graphql-soup');
+ const { createMemo, createRoot } = await import('solid-js');
+ const readers = createRoot((dispose) => ({
+ dispose,
+ host: createMemo(() => soup.getGraphqlCacheHost()),
+ gatedHost: createMemo(() =>
+ soup.graphqlCacheEnabled() ? !!soup.getGraphqlCacheHost() : false
+ ),
+ }));
+ expect(readers.host()).toBeUndefined();
+ expect(readers.gatedHost()).toBe(false);
+
+ soup.setGraphqlSoupSessionActive(true);
+
+ expect(readers.host()).toBeDefined();
+ expect(readers.gatedHost()).toBe(true);
+ expect(mocks.createWorkerCacheHost).toHaveBeenCalledOnce();
+ readers.dispose();
+ });
+
+ it.each([true, false])(
+ 'tears down the session clients when the session ends (cache rollout: %s)',
+ async (cacheEnabled) => {
+ mocks.enabled = cacheEnabled;
+ const soup = await import('./graphql-soup');
+ soup.getGraphqlSoupClient();
+ const { createMemo, createRoot } = await import('solid-js');
+ const readers = createRoot((dispose) => ({
+ dispose,
+ enabled: createMemo(() => soup.graphqlCacheEnabled()),
+ host: createMemo(() => soup.getGraphqlSoupCacheHost()),
+ }));
+ expect(readers.enabled()).toBe(cacheEnabled);
+
+ soup.setGraphqlSoupSessionActive(false);
+
+ expect(mocks.cleanupOrder()).toEqual(
+ cacheEnabled ? ['subscriptions', 'host'] : ['subscriptions']
+ );
+ expect(readers.enabled()).toBe(false);
+ expect(readers.host()).toBeUndefined();
+ expect(soup.getGraphqlSoupClient()).toBe(mocks.plainClient);
+ expect(mocks.createWorkerCacheHost).toHaveBeenCalledTimes(
+ cacheEnabled ? 1 : 0
+ );
+ readers.dispose();
+ }
+ );
+
it('latches an activated client through a flag change until navigation', async () => {
const apiStarted = mocks.apiStarted();
const soup = await import('./graphql-soup');
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
index 1b9949a774..95901fce78 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
@@ -5,6 +5,7 @@ import {
isFeatureEnabled,
} from '@core/constant/featureFlags';
import { SERVER_HOSTS } from '@core/constant/servers';
+import { hasLoginCookie } from '@core/util/cookies';
import { fetchToken } from '@core/util/fetchWithToken';
import { isTauri } from '@core/util/platform';
import { platformFetch } from '@core/util/platformFetch';
@@ -67,7 +68,7 @@ import {
createClient as createGraphqlWsClient,
type Client as GraphqlWsClient,
} from 'graphql-ws';
-import { createSignal } from 'solid-js';
+import { batch, createSignal, untrack } from 'solid-js';
import { match } from 'ts-pattern';
import { delegateChannelNotificationRefresh } from '../../queries/channel/notification-refresh';
import { soupOptimisticResolvers } from '../../queries/optimistic-resolvers';
@@ -456,6 +457,46 @@ let cacheInitializationFailed = false;
// Changes when the session abandons its cache so reactive readers of the
// availability getters below (query options, effects) move to network paths.
const [cacheAvailability, setCacheAvailability] = createSignal(0);
+// Signed-out pages (auth routes, shared links, an expired session) can neither
+// authenticate the live-updates websocket nor own a draft queue, so they only
+// get the plain network client.
+const [sessionActive, setSessionActive] = createSignal(hasLoginCookie());
+
+/**
+ * Records whether this tab has a signed-in session. Ending one disposes the
+ * cached and realtime clients, so their websocket and queue runner stop.
+ */
+export function setGraphqlSoupSessionActive(active: boolean): void {
+ if (untrack(sessionActive) === active) return;
+ if (!active) {
+ // Flip first, or a reactive reader woken by the teardown rebuilds the client.
+ setSessionActive(false);
+ disposeSessionClients();
+ return;
+ }
+ // Build before readers wake: getGraphqlCacheHost() only reports an existing
+ // host, so a reader that ran while signed out would otherwise stay uncached.
+ batch(() => {
+ setSessionActive(true);
+ untrack(getGraphqlSoupClient);
+ setCacheAvailability((version) => version + 1);
+ });
+}
+
+function disposeSessionClients(): void {
+ const cleanup = cachedCacheCleanup;
+ cachedCacheCleanup = undefined;
+ cachedCacheHost = undefined;
+ cachedClient = undefined;
+ browserCacheClientActivated = false;
+ disposeUncachedRealtimeClient();
+ try {
+ cleanup?.();
+ } catch {
+ // Teardown failures cannot keep a signed-out tab on the cached client.
+ }
+ setCacheAvailability((version) => version + 1);
+}
/**
* Whether the normalized cache is active for soup GraphQL queries.
@@ -464,6 +505,7 @@ const [cacheAvailability, setCacheAvailability] = createSignal(0);
*/
export function graphqlCacheEnabled(): boolean {
cacheAvailability();
+ if (!sessionActive()) return false;
if (cacheInitializationFailed) return false;
if (!isTauri() && browserCacheClientActivated) return true;
return getBrowserTursoCacheRolloutDecision().enabled;
@@ -524,6 +566,7 @@ export function getGraphqlCacheHost(): CacheHost | undefined {
* a reload or native update can resume the preserved queue.
*/
export function getGraphqlSoupClient(): Client {
+ if (!sessionActive()) return graphqlSoupClient;
const native = isTauri();
// Only the browser Turso client is session-latched. Tauri keeps the prior
// dynamic GraphQL transport behavior and can return to the plain client when
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 365a6286ed..b47dcd3d58 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -43,6 +43,7 @@ import {
prefetchUserInfo,
useUserInfoQuery,
} from '@queries/auth/user-info';
+import { setGraphqlSoupSessionActive } from '@service-storage/graphql-soup';
import { MetaProvider, Title } from '@solidjs/meta';
import {
HashRouter,
@@ -73,6 +74,7 @@ function useSyncLoginCookie() {
const { value, ...options } = getLoginCookieOptions(authenticated);
updateCookie('login', value, options);
syncLoginStorage(authenticated);
+ setGraphqlSoupSessionActive(authenticated);
});
}
diff --git a/apps/web/tests/functional/optimistic-mutations.spec.ts b/apps/web/tests/functional/optimistic-mutations.spec.ts
index 15ad511cf9..dee35e42ec 100644
--- a/apps/web/tests/functional/optimistic-mutations.spec.ts
+++ b/apps/web/tests/functional/optimistic-mutations.spec.ts
@@ -52,6 +52,8 @@ async function mount(page: Page, mode: CacheMode, initial?: string[]) {
let delayNextQuery = false;
const unexpected: string[] = [];
page.on('pageerror', (error) => unexpected.push(error.message));
+ // GraphQL Soup builds its cache only for a signed-in tab.
+ await page.addInitScript(() => localStorage.setItem('macro:login', 'true'));
await page.routeWebSocket('**', (socket) => socket.close());
await page.route('**/*', async (route) => {
const url = new URL(route.request().url());
diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.md
index 51bf90fa5f..d68b6db091 100644
--- a/docs/agent-guide/login.md
+++ b/docs/agent-guide/login.md
@@ -34,6 +34,20 @@ the configured bypass flag. Verify with an authorized test account outside
sign-in still apply. See the [authentication-service configuration guide](../../services/authentication_service/README.md#temporary-open-signup-override)
for restoring allowlist enforcement.
+## GraphQL cache session lifecycle
+
+Signed-out pages use the network client without creating the GraphQL cache,
+draft queue runner, or live-update subscriptions. Signing in activates them in
+the same tab, including after a session expiry. Queued draft writes wait for
+authenticated user info; unrelated mutations can continue draining.
+
+Verify expiry followed by signing into a different account without reloading:
+the new account's lists must load and receive live updates, and the previous
+account's cached data must be absent. Logout wipes local caches before retiring
+their clients. Mounted query observers must receive the next account's data
+after the wipe. Previous account data must not return through initial data,
+placeholder data, or a later query reset.
+
## Hosted-dev proxy SSO
On an allowed OAuth origin such as `https://localhost:<port>`, Google/SSO