Files
PaperClipAI/ui/src/lib/persisted-query-cache.ts
T
2ccc7d37ef feat(ui): retain approved reads across outage reloads (#18825)
## Thinking Path

> - Paperclip lets people manage agent work through the board.
> - The board already retains loaded reads during a temporary server
failure.
> - Reloading the page removes that in-memory data.
> - A deploy can then leave a returning user without the shell or recent
tasks.
> - This pull request saves an explicit, limited set of reads in the
browser.
> - Cached identity supports display while fresh session checks protect
writes.

## Linked Issues or Issue Description

**What happened?**
A reload during an API outage loses the board's loaded reads. An
automatic worker update can also reload a hidden tab while a write is
pending.

**Expected behavior**
Show the cached shell and recent tasks during a temporary outage. Limit
saved content by user, company, age and build. Clear it on sign-out.
Wait for a fresh session before sending account-bound writes. Defer
automatic reloads while work is pending.

**Steps to reproduce**
Open a task and settings while online. Return 503 from the API and
reload. Restore the API. Sign out and confirm that saved query records
are gone. Discover a worker update while offline or during an autosave
and confirm that it waits.

Stacked on Refs #18822. Related durable-write foundation: Refs #17960.
The outage browser suite follows in a separate test PR.

## What Changed

- Persist an exact read allowlist through TanStack Query dehydration and
hydration. Save shell preferences, company/sidebar data, agent/project
lists, plugin UI metadata, the first inbox page, and 20 recent tasks.
Task UUID and identifier reads share one recent-task slot.
- Namespace records by user and company. Retain eligible reads across
normal memory garbage collection, expire each read after 24 hours, and
discard them after a build change. Unstamped builds disable hydration
and persistence while retaining sign-out cleanup. Use the existing
instance-wide plugin contribution query in the user's root record.
- Exclude session credentials and bootstrap data, embedded plan
documents, comments, preview work products, provider credentials and
environment values, browser capabilities, pairing data, other queries,
and mutations. Restore only display identity from session data. Preserve
safe agent provider/model display fields and configuration object
shapes. Apply the projection on save and restore.
- Clear saved reads on sign-out, cross-tab account changes, and
definitive session denial. Keep revocation working on plain HTTP without
crypto.randomUUID. Use per-user revocation revisions to reject delayed
writes and stale records. Preserve a newer account. Remove every
UUID/identifier projection and nested inbox copy of a denied task.
- Detach shared GETs when the account changes or signs out. Load
complete, freshly authorized agents before opening bulk settings from a
display-only roster. Retire a pending bulk-editor result or error when
row, select-all or clear changes the selection, including a
clear/reselect of the same agent.
- Require a fresh server lookup before account-bound writes, pending
task creation, or mounted autosaves resume. This includes automatic task
read receipts, inbox archives, workspace preferences and primary-agent
choices, with optimistic archive changes gated too. Cancel the old write
scope when the verified user changes. Release completed archives through
account-independent cleanup without restoring old cached rows; an old
operation cannot clear a newer hide flag. Retry unconfirmed read
receipts after a fresh session succeeds for the original account, and
remember confirmed receipts across refreshes. Track pending reads per
task so opening another task sends its receipt immediately; revisiting
reuses an outstanding receipt and its original account scope.
- Defer a hidden-tab worker reload until connectivity, mutations,
durable sends, and autosaves are safe. Synchronously count each
unresolved operation across online rate-limit retries. Release a
cancelled target’s unused dirty token when an editor changes tasks; keep
stored drafts, admitted saves and queued retries. Cover autosave
debounce, newer edits, navigation and undo.

## Verification

- Current head `fe4f682c879` is merge-ready: all 54 check runs completed
(52 successful, one skipped, one neutral), the legacy Snyk status is
successful, and both `ci / verify` and `ci / e2e` pass in run
`41752927822`. Greptile Apex reviewed this exact head at 5/5 with zero
unresolved threads; the branch has no merge conflicts. All three PRs now
meet the merge-ready bar; the stack remains unmerged pending operator
approval.
- Greptile Apex reviewed exact current head `fe4f682c879` at 5/5 with no
actionable findings and zero unresolved threads (summary updated
2026-11-04 at 01:24:40 UTC). Both settings-account and pending-selection
findings are fixed, replied to and resolved. The branch has no merge
conflicts. Current-head CI now passes in run `41752927822`.
- Seventeen new cases cover settings restored from actual saved query
records, matching/changed/signed-out identities, denied verification,
late crown responses without overwriting newer reads, and bulk-selection
changes during successful/failed reads. Sixteen fail the preceding
source and one preserves denial compatibility. Both settings paths reuse
the existing account-bound mutation guard; its optional explicit
QueryClient supports the workspace hook’s existing detached-host mode.
Primary-agent optimistic updates begin only after verification and
cleanup checks ownership and the cache revision.
- Earlier CI run `41749456480` on prior head `2cf7516f18c` has one real
server test failure: the owned-runtime case in
`idle-completed-history.test.ts` could not reach its HTTP child on port
34757 within 10 seconds (99 refused probes). Its other 1,829 cases pass
and three skip; the only other unsuccessful job is the downstream
`verify` gate. The exact selected case passes locally, and the entire
75-case file passes in 72.19 seconds on the exact `2cf7516f18c` source
tree with isolated PostgreSQL and a real child process on macOS
arm64/Node 25.6.1. The Linux CI startup cause remains unknown; these
local results are not a fix or CI acceptance. One failed-jobs retry with
debug logging was accepted on that unchanged head, then superseded by
the later settings fixes. Current-head CI remains required; no source
change was made for this failure.
- Current cache head `fe4f682c879`, based on read head `09d1db29dea` and
master `683fa4725e9`, passes all 1,198 focused tests across twenty-eight
files, UI typecheck, token gates and the enforcing query-error guard.
Dependent browser head `228c1b68d30` contains this exact application
source and passes standalone strict checking of all three browser specs.
Current-head CI now passes in run `41752927822`.
- Three new navigation regressions fail the preceding application source
and pass with the fix. They open three cached tasks before any receipt
resolves, leave the page before success or failure, revisit an
outstanding read without duplicating it, and recover an older failed
receipt after a fresh session succeeds while a later task remains
pending.
- The fixture repair passes all seven deadline integration cases and the
complete server typecheck, including the server test layer. The old
assertion deterministically fails at 23:59:06.888 UTC; its
one-second-old run also fails the first-second-of-day probe. The
corrected fixture passes noon and both midnight probes. The permanent
three-case coverage uses seeded 2099 clocks.
- Nine new cases cover archive success/failure after sign-out and
another account takes over, both mounted and unmounted; cleanup
ownership when a newer archive uses the same task; session-check 429
exhaustion followed by matching, changed or signed-out identity; and a
failed read receipt followed by a new session read. They verify no
old-cache restoration, toast or navigation, retained newer hide flags,
no failed-check loop and no duplicate confirmed receipt. Seven fail the
previous implementation; two compatibility cases retain account-change
suppression. Initial test error-constructor and query-notification
timing assumptions were corrected before the passing checks.
- The inherited skills/app error-priority fix passes all 60 affected
tests and UI typecheck on both application branches. Its twelve new
regression cases fail the preceding read implementation. The
persisted-cache suite includes 48 cases.
- Six new regressions fail against the preceding application source and
pass with the fix. Actual worker-update and mutation-cache listeners
cannot reload a hidden tab between online 429 retries; the original
create key survives, and the update reloads once after a receipt. Real
self-hosted and Cloud sign-out work without crypto.randomUUID, with
stamped and unstamped builds. Saved reads are removed and account write
scopes are invalidated. An initial test-fixture type annotation error
was corrected before the passing typecheck.
- The 48 cache tests cover actual five-minute memory GC, the 20-task
bound across saved and live reads, original 24-hour expiry, denial
before session verification, unstamped cleanup, cross-tab revocation and
delayed flushes. Private GETs cannot cross account transitions. Bulk
edits require complete current agent data. Undo releases the update
blocker while preserving the Saved indicator.
- All 23 built-UI outage/write/loading cases pass in 4.5 minutes on
exact integrated head `228c1b68d30`, containing current cache revision
`fe4f682c879`: ten outage, six durable-write and seven loading cases.
The run uses bundled Chromium, the built UI, a fresh local-trusted
server and isolated embedded PostgreSQL on macOS arm64/Node 25.6.1. All
three specs pass standalone strict TypeScript checking. Owned temporary
server and database stopped.
- Earlier browser runs exposed and fixed cached-header, native Storage
cleanup and replay/session defects. A prior run passed 21/22 because
real WebSockets contradicted the simulated HTTP outage; the fixture now
closes existing socket pairs and holds new sockets through the same
outage deadline. An older CI run exposed a disposed response in the
Inbox route callback; pre-navigation snapshots remove that lifetime, and
the current full run includes that repair. Earlier failures and their
diagnosis remain in the discussion. The current full run passes. Broader
historical workspace failures remain documented in Refs #18822; this
does not claim a clean full workspace suite.
- Current-head CI passes on `fe4f682c879`. Controlled local outages do
not complete hosted authentication or a real Cloud restart/deploy
acceptance.

Commands for the current cache change and inherited read fix (the
current focused run also includes src/lib/inboxArchiveCache.test.ts and
src/pages/Inbox.test.ts):

```sh
pnpm --filter @paperclipai/ui exec vitest run src/pages/CompanySkills.test.tsx src/pages/apps/AppNotConnected.test.tsx
pnpm --filter @paperclipai/ui exec vitest run src/hooks/useDurableSubmit.test.tsx src/hooks/useDurableAutosave.test.tsx src/hooks/useSignOut.test.tsx src/lib/persisted-query-cache.test.ts src/lib/service-worker-updates.test.ts src/lib/service-worker-cache-policy.test.ts src/lib/pending-send.test.ts src/lib/issue-execution-policy.test.ts src/components/InlineEditor.test.tsx src/components/MarkdownEditor.test.tsx src/components/NewIssueDialog.test.tsx
pnpm --filter @paperclipai/ui exec vitest run src/components/agents/AgentBulkRoster.test.tsx src/components/agents/AgentBulkSettingsSheet.test.tsx src/hooks/useAccountBoundMutation.test.tsx src/pages/IssueDetail.test.tsx src/components/TaskChatThread.test.tsx src/components/TaskChatThread.task-creation-order.test.tsx src/api/client.test.ts src/api/agents.test.ts
pnpm --filter @paperclipai/ui exec vitest run src/hooks/useCoordinatorWorkspaceEnabled.test.tsx src/context/PrimaryAgentProvider.test.tsx src/components/CoordinatorWorkspaceSetting.test.tsx src/components/primary-agent/PrimaryAgentPresentation.test.tsx src/components/MobileBottomNav.coordinator.test.tsx src/components/CoordinatorSidebar.test.tsx src/pages/Issues.coordinator-routing.test.tsx
pnpm --filter @paperclipai/ui typecheck
pnpm check:token-gates
node scripts/check-query-error-rendering.mjs --enforce --summary
```

## Risks

This deliberately saves task content on the local browser for up to 24
hours. The allowlist excludes credentials and ephemeral capabilities.
Local storage can be disabled or full; persistence then fails without
blocking the app. Restored data can be stale and never grants server
access. A user or access change clears cached account reads and
invalidates pending writes. The browser outage suite and real hosted
deploy acceptance remain release requirements. There are no migrations
or new dependencies.

## Model Used

OpenAI `gpt-6.1-sol` through Codex, with xhigh reasoning effort, tool
use, and code execution. The context window size is not exposed.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR following the bug report template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id
- [x] The focused local tests for this change pass
- [x] I have added tests and updated relevant documentation
- [x] I have considered and documented risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Bender (Fable) <bender@agents.paperclip.ing>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-04 15:40:30 -08:00

480 lines
28 KiB
TypeScript

import { dehydrate, hashKey, hydrate, type DehydratedState, type Query, type QueryClient } from "@tanstack/react-query";
import { classifyError, isTransientError } from "@/api/errors";
import { detachInflightGets } from "@/api/client";
import { markCachedSession, verifyCachedSession, hasUnverifiedSession } from "./cached-session";
import { queryKeys } from "./queryKeys";
import { createUuid } from "./uuid";
export const QUERY_CACHE_PREFIX = "paperclip:query-cache:v1:";
export const QUERY_CACHE_ACTIVE = `${QUERY_CACHE_PREFIX}active`;
export const QUERY_CACHE_CLEARED = "paperclip:query-cache-cleared";
export const QUERY_CACHE_MAX_AGE = 24 * 60 * 60 * 1000;
export const QUERY_CACHE_MAX_ISSUES = 20;
const MAX_RECORD_BYTES = 2 * 1024 * 1024;
const REVISION_PREFIX = "paperclip:query-cache-revision:";
const controllers = new WeakMap<QueryClient, { clear: () => void }>();
type CacheStorage = Pick<Storage, "getItem" | "setItem" | "removeItem" | "key" | "length">;
type Envelope = { version: 1; userId: string; companyId: string | null; buildId: string; revision: string | null; savedAt: number; state: DehydratedState };
const object = (value: unknown): Record<string, unknown> | null => value != null && typeof value === "object" ? value as Record<string, unknown> : null;
const userIdOf = (value: unknown) => {
const id = object(object(value)?.user)?.id;
return typeof id === "string" && id ? id : null;
};
const recordKey = (userId: string, companyId: string | null) => `${QUERY_CACHE_PREFIX}${encodeURIComponent(userId)}:${companyId === null ? "root" : encodeURIComponent(companyId)}`;
const issueIdentity = (query: { queryKey: readonly unknown[]; state: { data: unknown } }) => String(object(query.state.data)?.id ?? query.queryKey[2]).toLowerCase();
const issueRefs = (query: { queryKey: readonly unknown[]; state: { data: unknown } }) => [query.queryKey[2], object(query.state.data)?.id, object(query.state.data)?.identifier]
.filter((id): id is string => typeof id === "string").map(id => id.toLowerCase());
const excludedFields = new Set(["planDocument", "legacyPlanDocument", "documentSummaries", "documents", "comments", "workProducts", "browsers", "pairingCode", "viewerUrl", "accessToken", "refreshToken", "sessionToken", "token", "password", "apiKey", "privateKey", "authorization", "access_token", "refresh_token", "id_token", "clientSecret", "client_secret", "api_key", "private_key", "credentials", "env"].map(key => key.toLowerCase()));
function displayData(value: unknown, denied: ReadonlySet<string>): unknown {
if (Array.isArray(value)) return value.map(item => displayData(item, denied)).filter(item => item !== undefined);
if (!value || typeof value !== "object" || value instanceof Date) return value;
const row = value as Record<string, unknown>;
if (typeof row.id === "string" && denied.has(row.id.toLowerCase())) return undefined;
return Object.fromEntries(Object.entries(row).filter(([key]) => !excludedFields.has(key.toLowerCase()))
.map(([key, item]) => {
if (key === "runtimeConfig") return [key, {}];
if (key === "adapterConfig") {
const config = object(item);
return [key, Object.fromEntries(["provider", "model", "agent", "acpxAgent", "effort", "modelReasoningEffort", "reasoningEffort", "thinking", "variant"]
.filter(field => typeof config?.[field] === "string").map(field => [field, config![field]]).concat(typeof config?.fastMode === "boolean" ? [["fastMode", config.fastMode]] : []))];
}
return [key, displayData(item, denied)];
}));
}
function isLegacyInboxQuery(key: readonly unknown[]): boolean {
const suffix = key[2] === "mine-by-me" || key[2] === "touched-by-me" ? key.slice(3) : key.slice(2);
return key[0] === "issues" && suffix.length === 4 && suffix[0] === "compact"
&& suffix[1] === "with-routine-executions" && suffix[2] === "live-descendant-summary" && suffix[3] === 500;
}
function queryDisplayData(key: readonly unknown[], data: unknown, denied: ReadonlySet<string>): unknown {
return displayData(isLegacyInboxQuery(key) && Array.isArray(data) ? data.slice(0, 100) : data, denied);
}
function browserStorage(): CacheStorage | null {
try { return typeof window === "undefined" ? null : window.localStorage; } catch { return null; }
}
// Native Storage can change enumeration order after a deletion.
const storageKeys = (storage: CacheStorage) => Array.from({ length: storage.length }, (_, i) => storage.key(i))
.filter((key): key is string => key !== null);
function removeRecords(storage: CacheStorage) {
for (const key of storageKeys(storage)) {
if (key.startsWith(QUERY_CACHE_PREFIX)) storage.removeItem(key);
}
}
function removeUserRecords(storage: CacheStorage, userId: string, keepRevision?: string | null) {
const prefix = `${QUERY_CACHE_PREFIX}${encodeURIComponent(userId)}:`;
for (const key of storageKeys(storage)) {
if (!key.startsWith(prefix)) continue;
if (keepRevision !== undefined) {
try { if ((JSON.parse(storage.getItem(key) ?? "null")?.revision ?? null) === keepRevision) continue; } catch {}
}
storage.removeItem(key);
}
if (storage.getItem(QUERY_CACHE_ACTIVE) === userId && !storage.getItem(recordKey(userId, null))) storage.removeItem(QUERY_CACHE_ACTIVE);
}
export function clearPersistedQueryCache(client: QueryClient) {
controllers.get(client)?.clear();
}
function companyIdsFor(client: QueryClient, userId: string): string[] {
const result = client.getQueryData<{ companies?: Array<{ id: string }> }>(queryKeys.companies.list(userId));
return (result?.companies ?? []).map(company => company.id).filter(id => typeof id === "string" && id.length > 0);
}
export function persistedQueryScope(key: readonly unknown[], data: unknown, userId: string, companyIds: readonly string[]): string | null | undefined {
const [root, second, third] = key;
if (hashKey(key) === hashKey(queryKeys.auth.session)) return userIdOf(data) === userId ? null : undefined;
if (key.length === 1 && root === "health") return null;
if (root === "companies" && second === "list" && third === userId && key.length === 3) return null;
if (root === "access" && second === "current-board-access" && third === userId && key.length === 3 && object(data)?.userId === userId) return null;
if (root === "instance" && key.length === 2 && ["experimental-settings", "general-settings"].includes(String(second))) return null;
if (root === "workspace-preferences" && second === userId && key.length === 2 && object(data)?.userId === userId) return null;
if (root === "sidebar-preferences" && second === "company-order" && third === userId && key.length === 3) return null;
if (root === "plugins" && second === "ui-contributions" && key.length === 2) return null;
if (root === "issues" && second === "detail" && (key.length === 3 || (key.length === 4 && key[3] === "core"))) {
const companyId = object(data)?.companyId;
return typeof companyId === "string" && companyIds.includes(companyId) ? companyId : undefined;
}
if (typeof second !== "string" || !companyIds.includes(second)) return undefined;
if (isLegacyInboxQuery(key) && Array.isArray(data)) return second;
if (["sidebar-badges", "agents", "built-in-agents"].includes(String(root)) && key.length === 2) return second;
if (root === "projects" && key.length <= 3) return second;
if (root === "agent-chats" && key.length === 3 && third === userId) return second;
if (root === "primary-agent" && third === userId && key.length === 3) return second;
if (root === "issues" && third === "mine-context" && key.length === 4 && key[3] === userId && object(data)?.userId === userId) return second;
if (root === "issues" && ["mine-by-me", "touched-by-me"].includes(String(third))
&& key[3] === "index" && key[4] === "with-routine-executions" && key[5] === "live-descendant-summary"
&& key[6] === 100 && (third === "mine-by-me" ? key.length === 8 && key[7] === userId : key.length === 7)) return second;
return undefined;
}
function clearAccountData(client: QueryClient) {
detachInflightGets();
const keep = (query: Query) => hashKey(query.queryKey) === hashKey(queryKeys.health) || hashKey(query.queryKey) === hashKey(queryKeys.auth.session);
void client.cancelQueries({ predicate: query => !keep(query) }, { revert: false });
for (const query of client.getQueryCache().getAll()) {
if (keep(query)) continue;
query.setState({ data: undefined, dataUpdatedAt: 0, error: null, status: "pending", fetchStatus: "idle", dataUpdateCount: 0 });
client.getQueryCache().remove(query);
}
}
export function startPersistedQueryCache(client: QueryClient, options: {
buildId: string | null;
storage?: CacheStorage | null;
now?: () => number;
eventTarget?: Window | null;
debounceMs?: number;
}): { flush: () => void; clear: () => void; dispose: () => void } {
const storage = options.storage === undefined ? browserStorage() : options.storage;
const buildId = options.buildId;
const now = options.now ?? Date.now;
const target = options.eventTarget === undefined ? (typeof window === "undefined" ? null : window) : options.eventTarget;
let owner: string | null = null;
let ownerRevision: string | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
let suspended = false;
let disposed = false;
let sessionEpoch = 0;
const sessionReads = new WeakMap<Query, { epoch: number; clear: string | null; userId: string | null; revisions: Map<string, string | null> }>();
const visits = new Map<string, number>();
const deniedIssues = new Set<string>();
const blockedQueries = new Set<string>();
const clearToken = () => { try { return storage?.getItem(QUERY_CACHE_CLEARED) ?? null; } catch { return null; } };
let observedClear = clearToken();
const revisionKey = (userId: string) => `${REVISION_PREFIX}${encodeURIComponent(userId)}`;
const revisionFor = (userId: string) => { try { return storage?.getItem(revisionKey(userId)) ?? null; } catch { return null; } };
const captureSessionRead = (query: Query) => {
const userId = owner ?? userIdOf(query.state.data);
const revisions = new Map<string, string | null>();
try {
if (storage) for (let i = 0; i < storage.length; i += 1) {
const key = storage.key(i);
if (key?.startsWith(REVISION_PREFIX)) revisions.set(key, storage.getItem(key));
}
} catch {}
sessionReads.set(query, { epoch: sessionEpoch, clear: clearToken(), userId, revisions });
};
const safeRemove = () => { try { if (storage) removeRecords(storage); } catch {} };
const removeUser = (userId: string | null, preserveCurrent = false) => {
try { if (storage && userId) removeUserRecords(storage, userId, preserveCurrent ? revisionFor(userId) : undefined); } catch {}
};
const cancelTimer = () => { if (timer !== undefined) clearTimeout(timer); timer = undefined; };
const clear = () => {
detachInflightGets();
sessionEpoch += 1;
cancelTimer();
const previous = owner ?? userIdOf(client.getQueryData(queryKeys.auth.session));
const token = createUuid();
const publish = () => {
if (previous) storage?.setItem(revisionKey(previous), token);
observedClear = JSON.stringify({ token, userId: previous });
storage?.setItem(QUERY_CACHE_CLEARED, observedClear);
};
try { publish(); }
catch {
if (previous) removeUser(previous);
else safeRemove();
try { publish(); } catch {}
}
if (previous) removeUser(previous, revisionFor(previous) === token);
else safeRemove();
suspended = true;
owner = null;
ownerRevision = null;
verifyCachedSession(client);
};
// Unstamped bundles do not hydrate or save reads, but sign-out still uses
// the same revocation and cleanup path as a stamped bundle.
if (!buildId?.trim()) {
controllers.set(client, { clear });
return { flush: () => {}, clear, dispose: () => { controllers.delete(client); } };
}
const suspendAccount = () => {
sessionEpoch += 1;
removeUser(owner, true);
suspended = true;
cancelTimer();
owner = null;
ownerRevision = null;
verifyCachedSession(client);
clearAccountData(client);
client.setQueryData(queryKeys.auth.session, null);
void client.refetchQueries({ queryKey: queryKeys.auth.session, type: "active" });
};
const observeStorage = () => {
const token = clearToken();
if (token !== observedClear) {
observedClear = token;
let clearedUser: string | null = null;
try { const id = object(JSON.parse(token ?? "null"))?.userId; clearedUser = typeof id === "string" ? id : null; } catch {}
removeUser(clearedUser, true);
if (!clearedUser) { removeUser(owner); suspendAccount(); return true; }
if (clearedUser === owner && ownerRevision !== revisionFor(clearedUser)) { suspendAccount(); return true; }
}
try {
const active = storage?.getItem(QUERY_CACHE_ACTIVE);
if (owner && active && active !== owner) { suspendAccount(); return true; }
} catch {}
return false;
};
const read = (userId: string, companyId: string | null): Envelope | null => {
if (!storage) return null;
try {
const key = recordKey(userId, companyId);
const raw = storage.getItem(key);
if (!raw) return null;
const entry = JSON.parse(raw) as Envelope;
if (raw.length > MAX_RECORD_BYTES || entry.version !== 1 || entry.userId !== userId || entry.companyId !== companyId
|| entry.buildId !== buildId || (entry.revision ?? null) !== revisionFor(userId) || !Number.isFinite(entry.savedAt) || now() - entry.savedAt < 0
|| now() - entry.savedAt > QUERY_CACHE_MAX_AGE || !Array.isArray(entry.state?.queries)) {
storage.removeItem(key);
return null;
}
return entry;
} catch { return null; }
};
const fresh = (updatedAt: number) => Number.isFinite(updatedAt) && now() - updatedAt >= 0 && now() - updatedAt <= QUERY_CACHE_MAX_AGE;
const savedQueries = (entry: Envelope, companyIds: string[]) => entry.state.queries.filter(query => query?.state?.data !== undefined && query.state.status === "success"
&& fresh(query.state.dataUpdatedAt) && Array.isArray(query.queryKey) && !blockedQueries.has(hashKey(query.queryKey))
&& persistedQueryScope(query.queryKey, query.state.data, entry.userId, companyIds) === entry.companyId);
const readSaved = (userId: string): Envelope[] => {
if (!storage) return [];
const prefix = `${QUERY_CACHE_PREFIX}${encodeURIComponent(userId)}:`;
try {
return storageKeys(storage).flatMap(key => {
if (!key.startsWith(prefix)) return [];
try {
const suffix = key.slice(prefix.length);
const entry = read(userId, suffix === "root" ? null : decodeURIComponent(suffix));
return entry ? [entry] : [];
} catch { return []; }
});
} catch { return []; }
};
const approvedCompanies = (userId: string, entries: Envelope[]) => {
const key = queryKeys.companies.list(userId);
const live = client.getQueryState(key);
if (blockedQueries.has(hashKey(key)) || (live?.status === "error" && !isTransientError(live.error))) return [];
const saved = entries.find(entry => entry.companyId === null);
const cached = saved && savedQueries(saved, []).find(query => hashKey(query.queryKey) === hashKey(key));
const data = live?.data === undefined ? cached?.state.data : live.data;
const companies = object(data)?.companies;
return Array.isArray(companies) ? companies.flatMap(company => {
const id = object(company)?.id;
return typeof id === "string" && id ? [id] : [];
}) : [];
};
type SavedQuery = DehydratedState["queries"][number];
const projectQuery = (query: SavedQuery, userId: string): SavedQuery => {
let data = queryDisplayData(query.queryKey, query.state.data, deniedIssues);
if (hashKey(query.queryKey) === hashKey(queryKeys.auth.session)) {
const user = object(object(data)?.user)!;
data = { session: { userId }, user: { id: userId, name: user.name, email: user.email, image: user.image }, sentryDsn: null };
} else if (Array.isArray(object(data)?.pages)) {
const value = object(data)!;
data = { ...value, pages: (value.pages as unknown[]).slice(0, 1), pageParams: (value.pageParams as unknown[] | undefined)?.slice(0, 1) };
}
return { queryKey: query.queryKey, queryHash: hashKey(query.queryKey), state: { ...query.state, data, error: null, status: "success", fetchStatus: "idle", fetchFailureReason: null, fetchMeta: null } };
};
const allowedIssue = (query: { queryKey: readonly unknown[]; state: { data: unknown } }) => !(query.queryKey[0] === "issues" && query.queryKey[1] === "detail"
&& issueRefs(query).some(id => deniedIssues.has(id)));
const scrubSaved = (userId: string, entries: Envelope[]) => {
if (!storage || ownerRevision !== revisionFor(userId)) return;
const companies = approvedCompanies(userId, entries);
for (const entry of entries) {
if (ownerRevision !== revisionFor(userId)) return;
const key = recordKey(userId, entry.companyId);
const queries = savedQueries(entry, companies).filter(allowedIssue).map(query => projectQuery(query, userId)).filter(query => query.state.data !== undefined);
try { storage.setItem(key, JSON.stringify({ ...entry, state: { mutations: [], queries } })); }
catch { try { storage.removeItem(key); } catch {} }
}
};
const restoreState = (entry: Envelope, companyIds: string[]) => {
const queries = savedQueries(entry, companyIds)
.map(query => ({ queryKey: query.queryKey, queryHash: hashKey(query.queryKey), state: {
data: queryDisplayData(query.queryKey, query.state.data, deniedIssues), dataUpdatedAt: query.state.dataUpdatedAt, dataUpdateCount: 1,
error: null, errorUpdateCount: 0, errorUpdatedAt: 0, fetchFailureCount: 0, fetchFailureReason: null,
fetchMeta: null, isInvalidated: true, status: "success" as const, fetchStatus: "idle" as const,
} }));
hydrate(client, { mutations: [], queries });
};
try {
const current = client.getQueryState(queryKeys.auth.session);
const active = current?.status === "success" ? userIdOf(current.data) : storage?.getItem(QUERY_CACHE_ACTIVE);
const entry = active ? read(active, null) : null;
if (!entry) safeRemove();
const cachedSession = entry?.state.queries.find(query => hashKey(query.queryKey) === hashKey(queryKeys.auth.session));
if (entry && cachedSession?.state.status === "success" && fresh(cachedSession.state.dataUpdatedAt) && userIdOf(cachedSession.state.data) === active) {
owner = active!;
ownerRevision = entry.revision ?? null;
if (current?.data === undefined) markCachedSession(client);
restoreState(entry, []);
const companyIds = companyIdsFor(client, owner);
for (const companyId of companyIds) {
const company = read(owner, companyId);
if (company) restoreState(company, companyIds);
}
} else if (entry) safeRemove();
} catch {}
const pendingSession = client.getQueryCache().find({ queryKey: queryKeys.auth.session, exact: true });
if (pendingSession && pendingSession.state.fetchStatus !== "idle") captureSessionRead(pendingSession);
const flush = () => {
cancelTimer();
if (observeStorage()) return;
if (!storage || disposed || suspended || hasUnverifiedSession(client)) return;
const session = client.getQueryData(queryKeys.auth.session);
const userId = userIdOf(session);
if (!userId) return;
if (owner !== userId) { owner = userId; ownerRevision = revisionFor(userId); }
if (ownerRevision !== revisionFor(userId)) { suspendAccount(); return; }
const entries = readSaved(userId);
const companies = approvedCompanies(userId, entries);
const eligible = (query: Query) => query.state.data !== undefined
&& (query.state.status === "success" || isTransientError(query.state.error))
&& !blockedQueries.has(hashKey(query.queryKey))
&& fresh(query.state.dataUpdatedAt)
&& persistedQueryScope(query.queryKey, query.state.data, userId, companies) !== undefined;
// Memory GC is independent of the on-disk lifetime. Retain valid saved
// reads, prefer newer data, and apply the same limits to the merged set.
const merged = new Map<string, SavedQuery>();
for (const entry of entries) for (const query of savedQueries(entry, companies)) merged.set(hashKey(query.queryKey), query);
for (const query of client.getQueryCache().getAll()) {
if (query.state.status === "error" && !isTransientError(query.state.error)) merged.delete(hashKey(query.queryKey));
}
const state = dehydrate(client, { shouldDehydrateMutation: () => false, shouldDehydrateQuery: eligible });
for (const query of state.queries) {
const key = hashKey(query.queryKey);
if (!merged.has(key) || merged.get(key)!.state.dataUpdatedAt <= query.state.dataUpdatedAt) merged.set(key, query);
}
const recent = [...merged.values()].filter(query => query.queryKey[0] === "issues" && query.queryKey[1] === "detail" && allowedIssue(query))
.sort((a, b) => (visits.get(hashKey(b.queryKey)) ?? b.state.dataUpdatedAt) - (visits.get(hashKey(a.queryKey)) ?? a.state.dataUpdatedAt));
const issueIds = new Set<string>();
for (const query of recent) if (issueIds.size < QUERY_CACHE_MAX_ISSUES) issueIds.add(issueIdentity(query));
const queries = [...merged.values()].filter(query => allowedIssue(query)
&& !(query.queryKey[0] === "issues" && query.queryKey[1] === "detail" && !issueIds.has(issueIdentity(query))))
.map(query => projectQuery(query, userId)).filter(query => query.state.data !== undefined);
try {
const expected = new Set([QUERY_CACHE_ACTIVE]);
for (const companyId of [null, ...companies]) {
const key = recordKey(userId, companyId);
expected.add(key);
const envelope: Envelope = { version: 1, userId, companyId, buildId, revision: ownerRevision, savedAt: now(),
state: { mutations: [], queries: queries.filter(query => persistedQueryScope(query.queryKey, query.state.data, userId, companies) === companyId) } };
const serialized = JSON.stringify(envelope);
if (serialized.length <= MAX_RECORD_BYTES) storage.setItem(key, serialized);
else storage.removeItem(key);
}
const userPrefix = `${QUERY_CACHE_PREFIX}${encodeURIComponent(userId)}:`;
for (const key of storageKeys(storage)) {
if (key.startsWith(userPrefix) && !expected.has(key)) storage.removeItem(key);
}
const active = storage.getItem(QUERY_CACHE_ACTIVE);
if (ownerRevision !== revisionFor(userId) || (active && active !== userId)) { suspendAccount(); return; }
if (active !== userId) storage.setItem(QUERY_CACHE_ACTIVE, userId);
} catch {}
};
const unsubscribe = client.getQueryCache().subscribe(event => {
if (disposed) return;
const sessionEvent = hashKey(event.query.queryKey) === hashKey(queryKeys.auth.session);
const completedRead = sessionEvent && event.type === "updated" && event.action.type === "success" && !event.action.manual
? sessionReads.get(event.query) : undefined;
if (sessionEvent && event.type === "updated" && event.action.type === "fetch") captureSessionRead(event.query);
if (sessionEvent && event.type === "updated" && event.action.type === "success" && !event.action.manual) {
const read = completedRead;
sessionReads.delete(event.query);
// A delayed response cannot verify identity across sign-out, including
// before another tab's storage event has reached this event loop.
if (observeStorage()) return;
let clearedUser: string | null = null;
try { const id = object(JSON.parse(clearToken() ?? "null"))?.userId; clearedUser = typeof id === "string" ? id : null; } catch {}
const next = userIdOf(event.query.state.data);
if (read && (read.epoch !== sessionEpoch
|| [read.userId, next].some(id => id && (read.revisions.get(revisionKey(id)) ?? null) !== revisionFor(id))
|| (read.clear !== clearToken() && (!clearedUser || clearedUser === read.userId || clearedUser === userIdOf(event.query.state.data))))) {
suspendAccount(); return;
}
}
if (sessionEvent && event.type === "updated" && event.action.type === "error"
&& ["auth", "forbidden"].includes(classifyError(event.action.error))) {
clearAccountData(client);
clear();
client.setQueryData(queryKeys.auth.session, null);
return;
}
if (suspended) {
if (!sessionEvent || event.type !== "updated" || event.action.type !== "success" || event.action.manual || !userIdOf(event.query.state.data)) return;
suspended = false;
}
if (sessionEvent && event.type === "updated" && event.action.type === "success") {
if (!event.action.manual) { observedClear = completedRead ? completedRead.clear : clearToken(); verifyCachedSession(client); }
const next = userIdOf(event.query.state.data);
if (owner && next !== owner) {
if (next) removeUser(owner);
clearAccountData(client);
}
if (!next) { clear(); return; }
if (next && (!event.action.manual || next !== owner)) ownerRevision = completedRead
? completedRead.revisions.get(revisionKey(next)) ?? null : revisionFor(next);
owner = next;
}
if (event.type === "observerAdded" && event.query.queryKey[0] === "issues" && event.query.queryKey[1] === "detail") visits.set(event.query.queryHash, now());
const issueDetail = event.query.queryKey[0] === "issues" && event.query.queryKey[1] === "detail";
if (event.type === "updated" && event.action.type === "success" && !event.action.manual) {
blockedQueries.delete(hashKey(event.query.queryKey));
if (issueDetail) for (const id of issueRefs(event.query)) deniedIssues.delete(id);
}
if (event.type === "updated" && event.action.type === "error" && !isTransientError(event.action.error)) {
blockedQueries.add(hashKey(event.query.queryKey));
const userId = owner ?? userIdOf(client.getQueryData(queryKeys.auth.session));
const saved = userId ? readSaved(userId) : [];
if (issueDetail && ["auth", "forbidden", "not_found"].includes(classifyError(event.action.error))) {
const ids = new Set(issueRefs(event.query));
const matches = (query: Query) => query.queryKey[0] === "issues" && query.queryKey[1] === "detail"
&& issueRefs(query).some(id => ids.has(id));
for (const query of [...client.getQueryCache().getAll(), ...saved.flatMap(entry => entry.state.queries)].filter(query => Array.isArray(query?.queryKey) && query.queryKey[0] === "issues" && query.queryKey[1] === "detail" && issueRefs(query).some(id => ids.has(id)))) {
for (const id of issueRefs(query)) ids.add(id);
}
for (const id of ids) deniedIssues.add(id);
void client.cancelQueries({ predicate: matches }, { revert: false });
for (const query of client.getQueryCache().getAll().filter(matches)) query.setState({ data: undefined, dataUpdatedAt: 0,
error: event.action.error, status: "error", fetchStatus: "idle" });
}
if (userId) scrubSaved(userId, saved);
flush(); return;
}
cancelTimer();
timer = setTimeout(flush, options.debounceMs ?? 250);
});
const onStorage = (event: StorageEvent) => {
if (owner && event.key === revisionKey(owner) && event.newValue !== ownerRevision) { suspendAccount(); return; }
if (event.key !== QUERY_CACHE_CLEARED && !(event.key === QUERY_CACHE_ACTIVE && event.newValue !== owner)) return;
if (event.key === QUERY_CACHE_CLEARED && event.newValue !== clearToken()) return;
if (event.key === QUERY_CACHE_CLEARED) {
try { const id = object(JSON.parse(event.newValue ?? "null"))?.userId; if (typeof id === "string") removeUser(id, true); } catch {}
}
observeStorage();
};
const onPageHide = () => flush();
target?.addEventListener("storage", onStorage);
target?.addEventListener("pagehide", onPageHide);
const dispose = () => {
disposed = true;
cancelTimer();
unsubscribe();
target?.removeEventListener("storage", onStorage);
target?.removeEventListener("pagehide", onPageHide);
controllers.delete(client);
};
controllers.set(client, { clear });
return { flush, clear, dispose };
}