Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(verify): move the acceptance bundle and subject attachment onto @lobechat/replica (#20611)

Arvin Xu18ed0290b983
diff --git a/apps/workbench/app/entry.client.tsx b/apps/workbench/app/entry.client.tsx
index 71b73f5686c..87b7ced0201 100644
--- a/apps/workbench/app/entry.client.tsx
+++ b/apps/workbench/app/entry.client.tsx
@@ -2,6 +2,14 @@ import { startTransition, StrictMode } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { HydratedRouter } from 'react-router/dom';
+import { setReplicaPersistedHydration } from '@/libs/replica';
+
+// The Workbench runtime never mounts the user store, so a replica's cache scope
+// would stay the last-known user's partition β€” hydrating it would paint a
+// previous (possibly server-invalidated) session's private rows. Reads here are
+// network-only; authorization is whatever the server answers.
+setReplicaPersistedHydration(false);
+
// RR suffixes dynamically-shared route CSS hrefs with `#`, so the vite preload
// helper re-requests them with `crossorigin` β€” against our cross-origin CDN the
// browser reuses the plain-cached (ACAO-less) response and fails the CORS
diff --git a/apps/workbench/app/routes/acceptanceDetail.tsx b/apps/workbench/app/routes/acceptanceDetail.tsx
index c84cf0b3e5c..e1c7f296d5d 100644
--- a/apps/workbench/app/routes/acceptanceDetail.tsx
+++ b/apps/workbench/app/routes/acceptanceDetail.tsx
@@ -2,9 +2,9 @@ import { BRANDING_NAME } from '@lobechat/business-const';
import { lazy, Suspense } from 'react';
import type { LoaderFunctionArgs, MetaFunction } from 'react-router';
import { useLoaderData, useRouteLoaderData } from 'react-router';
-import { SWRConfig, unstable_serialize } from 'swr';
-import { verifyKeys } from '@/libs/swr/keys';
+import { extractUuid } from '@/features/Acceptance/utils';
+import { AcceptanceInitialBundle } from '@/features/Acceptance/Viewer/AcceptanceInitialBundle';
import WorkbenchLoading from '../../src/shell/WorkbenchLoading';
import { cloudflareContext } from '../lib/cloudflareContext';
@@ -17,7 +17,9 @@ const AcceptanceDetail = lazy(() => import('../../src/features/acceptance/Accept
const AcceptanceEmbed = lazy(() => import('../../src/features/acceptance/AcceptanceEmbed'));
export const loader = async ({ context, params, request }: LoaderFunctionArgs) => {
- const acceptanceId = params.acceptanceId!;
+ // Normalize the same way the rendered viewer does, so the id the loader
+ // fetches for is the id the render tree reads its bundle under.
+ const acceptanceId = extractUuid(params.acceptanceId)!;
const apiBase = context.get(cloudflareContext).env.WORKBENCH_API_BASE as string | undefined;
// SSR data is best-effort: on any backend failure fall back to CSR, where
@@ -45,20 +47,21 @@ export const meta: MetaFunction<typeof loader> = ({ loaderData }) => {
};
export default function AcceptanceDetailRoute() {
- const { acceptanceId, bundle } = useLoaderData<typeof loader>();
const root = useRouteLoaderData<typeof rootLoader>('root');
+ const { acceptanceId, bundle } = useLoaderData<typeof loader>();
+ // The loader already fetched an authorized bundle. The Workbench runtime never
+ // hydrates the persisted replica, so hand the bundle to the tree as
+ // request-local context data β€” the gate paints it on the first frame instead
+ // of a spinner. It must NOT go into the replica store: that store is a module
+ // singleton shared by every request the server handles, so a render-time write
+ // would leak one request's authorized entry into a later (or concurrent)
+ // request whose loader returned null.
return (
- <SWRConfig
- value={{
- fallback: bundle
- ? { [unstable_serialize(verifyKeys.acceptanceBundle(acceptanceId))]: bundle }
- : {},
- }}
- >
+ <AcceptanceInitialBundle acceptanceId={acceptanceId} bundle={bundle}>
<Suspense fallback={<WorkbenchLoading />}>
{root?.embedConfig.embed ? <AcceptanceEmbed /> : <AcceptanceDetail />}
</Suspense>
- </SWRConfig>
+ </AcceptanceInitialBundle>
);
}
diff --git a/apps/workbench/src/entry.tsx b/apps/workbench/src/entry.tsx
index 8bee0adf204..abee04b3d90 100644
--- a/apps/workbench/src/entry.tsx
+++ b/apps/workbench/src/entry.tsx
@@ -4,10 +4,17 @@ import { RouterProvider } from 'react-router/dom';
import BootErrorBoundary from '@/components/BootErrorBoundary';
import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
+import { setReplicaPersistedHydration } from '@/libs/replica';
import { createSPABrowserRouter, createSPARoot } from '@/spa/runtime';
import { workbenchRoutes } from './router';
+// The Workbench runtime never mounts the user store, so a replica's cache scope
+// would stay the last-known user's partition β€” hydrating it would paint a
+// previous (possibly server-invalidated) session's private rows. Reads here are
+// network-only; authorization is whatever the server answers.
+setReplicaPersistedHydration(false);
+
const router = createSPABrowserRouter(workbenchRoutes);
createSPARoot(document.getElementById('root')!).render(
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.ts
index 030751cb804..5f3ce0ab9cf 100644
--- a/packages/replica/src/core/engine.ts
+++ b/packages/replica/src/core/engine.ts
@@ -16,6 +16,7 @@ import {
} from './paging';
import type { ReplicaAction, ReplicaEffect, ReplicaViewWrite } from './reducer';
import { replicaReducer } from './reducer';
+import { createTombstones } from './tombstones';
import type { ReplicaResource, ReplicaState } from './types';
import { ReplicaWriteQueue } from './writeQueue';
@@ -69,6 +70,14 @@ export interface ReplicaEngineOptions<TParams, TData, TFetched> {
isClientOnly?: (item: any) => boolean;
/** Reject a persisted value that cannot serve these params. Rarely needed: rows are stored per query. */
isHydratable?: (cached: TData, params: TParams) => boolean;
+ /**
+ * Non-paged: whether a head response means the entry no longer exists. Such a
+ * response is applied as an explicit removal (memory + persisted row) instead
+ * of through `merge` β€” otherwise a `null` would fall back to the confirmed
+ * value (the reducer resolves `action.data(confirmed) ?? confirmed`), so a
+ * deleted aggregate would be retained and re-persisted.
+ */
+ isMissing?: (incoming: TFetched) => boolean;
/**
* Non-paged: fold a server response into the confirmed value. Return
* `undefined` to keep the current value. Defaults to "the response is the value".
@@ -140,6 +149,32 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
/** Keys with a `loadMore` request in flight (the only valid `isLoadingMore`). */
const loadingMore = new Set<string>();
+ // ---- removal guard ----------------------------------------------------
+ // An explicit removal (a deleted / unauthorized aggregate, or a subject whose
+ // attachment is gone) drops the entry AND its persisted row β€” but a read of
+ // that row that started before the removal still holds the old value, and a
+ // removal leaves no trace in the slots for the `hydrate` guard to see. So a
+ // scope+key is remembered as removed and refuses hydration until a server
+ // value supersedes it, otherwise the late read resurrects the exact value the
+ // removal just dropped.
+ const removedEntries = createTombstones();
+ /**
+ * Keys whose persisted row delete was actually queued. `runEffects` refuses to
+ * write while the scope is untrusted, so a removal made on a cold boot can arm
+ * the guard without clearing the row. The guard alone must therefore not turn
+ * a later removal into a no-op, or the stale row would survive and hydrate
+ * again once the scope becomes trusted.
+ */
+ const purgedEntries = createTombstones();
+ const markRemoved = (scope: string, key: string) => removedEntries.add(scope, key);
+ const clearRemoved = (scope: string, key: string) => {
+ removedEntries.clear(scope, key);
+ purgedEntries.clear(scope, key);
+ };
+ const isRemoved = (scope: string, key: string) => removedEntries.has(scope, key);
+ const markPurged = (scope: string, key: string) => purgedEntries.add(scope, key);
+ const isPurged = (scope: string, key: string) => purgedEntries.has(scope, key);
+
const getSlot = port.getState;
const storageKey = (key: string, query?: string) => ({
queryKey: replicaStorageKey(key, query),
@@ -188,7 +223,14 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
if (!resource.persistKey(effect.key)) continue;
const key = { ...storageKey(effect.key, effect.query), scope: effect.scope };
if (effect.type === 'remove') {
- writeQueue.remove(key);
+ // A repeated removal for this key can be a real no-op (see `remove`) β€”
+ // but only once the row delete actually landed. A storage that rejects
+ // the delete (a closed IndexedDB, a quota error) must leave the key
+ // unpurged, so the next terminal answer retries it instead of letting a
+ // stale row survive to hydrate again.
+ void writeQueue.remove(key).then((removed) => {
+ if (removed) markPurged(effect.scope, effect.key);
+ });
trackStorageKey(effect.scope, key.queryKey, false);
continue;
}
@@ -221,6 +263,15 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
// An action captured under another identity is stale β€” drop it.
if (action.scope !== activeScope) return false;
+ // Every removal path (explicit `remove`, a missing response, an entity that
+ // takes its whole value with it) arms the hydration guard for this key.
+ if (action.type === 'remove') markRemoved(action.scope, action.key);
+ // A replacement that reaches the active scope supersedes an earlier removal,
+ // so the key may hydrate again. A response captured under another scope is
+ // dropped below and must NOT clear its guard: the removal still stands for
+ // its own scope, whose row delete may be pending or may have failed.
+ if (action.type === 'replace') clearRemoved(action.scope, action.key);
+
const initial = getSlot();
let slot = initial;
const writes: ReplicaViewWrite<TData>[] = [];
@@ -258,11 +309,20 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const hydrate = async (params: TParams, scope = resource.scope.get()) => {
if (!resource.storage) return false;
+ // An identity-less runtime reads network-only: its scope is a guess, so
+ // hydrating it could paint another session's private rows.
+ if (resource.scope.canHydrate && !resource.scope.canHydrate()) return false;
const key = resource.key(params);
if (!resource.persistKey(key)) return false;
+ // A removed entry is not read back: only a later server value supersedes
+ // the removal (see `replace`), so a stale row can never repaint it.
+ if (isRemoved(scope, key)) return false;
const query = resource.query(params);
const cached = await resource.storage.get({ ...storageKey(key, query), scope });
if (!cached) return false;
+ // Re-check after the read: a removal that landed while it was in flight must
+ // not resurrect the row it just dropped.
+ if (isRemoved(scope, key)) return false;
if (options.isHydratable && !options.isHydratable(cached.data, params)) return false;
return dispatch({
data: cached.data,
@@ -310,6 +370,15 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
? options.prepareHead(fetched, port.read(key), params)
: fetched;
if (incoming === undefined) return false;
+ // A response that says the entry is gone clears it outright: the merge path
+ // would keep β€” and re-persist β€” the confirmed value it is replacing. It also
+ // arms the hydration guard, so a persisted read still in flight cannot bring
+ // the dropped value back.
+ if (!paging && options.isMissing?.(incoming)) {
+ // Route through `remove` so a repeated "missing" is a no-op and a response
+ // captured under another scope is dropped rather than applied here.
+ return remove(key, scope);
+ }
const query = resource.query(params);
const entry = getSlot().entries[key];
// A different query (filters, sort) must not merge with loaded pages. A
@@ -339,7 +408,61 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
{ persist = true }: { persist?: boolean } = {},
) => dispatch({ apply, key, persist, scope: resource.scope.get(), type: 'update' });
- const remove = (key: string) => dispatch({ key, scope: resource.scope.get(), type: 'remove' });
+ /**
+ * Purge a removal that belongs to a scope which is no longer active.
+ *
+ * The in-memory view is not ours to touch β€” the active scope owns it β€” but the
+ * guard and the persisted row both belong to THAT scope. Arming the one and
+ * deleting the other keeps a switch back from hydrating a value the server
+ * just deleted or denied. `dispatch` would reject the off-scope action
+ * outright (see `replace`'s stale-scope guard), so the row would otherwise
+ * survive untouched.
+ *
+ * Like `remove`, the delete only counts as done once it was actually queued:
+ * an untrusted scope refuses writes, so the guard stays armed as `unpurged`
+ * and a later removal retries instead of reporting a no-op that never deletes.
+ */
+ const purge = (key: string, scope: string): boolean => {
+ if (isRemoved(scope, key) && isPurged(scope, key)) return false;
+ markRemoved(scope, key);
+ // Nothing persisted (no storage, or a key this resource never persists) is
+ // already "cleared": the guard alone is the whole purge.
+ if (!writeQueue || !resource.persistKey(key)) {
+ markPurged(scope, key);
+ return false;
+ }
+ if (!resource.scope.canPersist()) return false;
+ const target = { ...storageKey(key), scope };
+ trackStorageKey(scope, target.queryKey, false);
+ void writeQueue.remove(target).then((removed) => {
+ if (removed) markPurged(scope, key);
+ });
+ return true;
+ };
+
+ /**
+ * Drop an entry and its persisted row.
+ *
+ * A removal is a no-op only once there is genuinely nothing left to do: the
+ * key is guarded, its value is gone, AND its stale row was already scheduled
+ * for deletion (or there is no persisted row to clear). A subject with no
+ * acceptance polls `null` every couple of seconds, and re-emitting the same
+ * delete on every tick would only churn storage. But a removal whose delete
+ * was skipped β€” an untrusted scope refuses writes β€” keeps retrying, so the row
+ * cannot survive to hydrate again once the scope is trusted.
+ *
+ * A removal captured under another identity (a late NOT_FOUND arriving after a
+ * workspace switch) is routed to {@link purge}: it must not touch the scope on
+ * screen, yet its own scope's row still has to go.
+ */
+ const remove = (key: string, scope: string = resource.scope.get()): boolean => {
+ if (scope !== resource.scope.get()) return purge(key, scope);
+ // Nothing persisted (no storage, or a key this resource never persists) is
+ // already "cleared"; otherwise the row delete must have been queued.
+ const rowCleared = !writeQueue || !resource.persistKey(key) || isPurged(scope, key);
+ if (rowCleared && isRemoved(scope, key) && port.read(key) === undefined) return false;
+ return dispatch({ key, scope, type: 'remove' });
+ };
/**
* Persist the confirmed value of an entry as it is now β€” the flush after a
diff --git a/packages/replica/src/core/tombstones.test.ts b/packages/replica/src/core/tombstones.test.ts
new file mode 100644
index 00000000000..d6363dda8a2
--- /dev/null
+++ b/packages/replica/src/core/tombstones.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+import { createTombstones } from './tombstones';
+
+describe('createTombstones', () => {
+ it('tracks keys per scope, so a scope switch keeps each identity guarded', () => {
+ const tombstones = createTombstones();
+ tombstones.add('user-1:personal', 'a');
+ tombstones.add('user-2:personal', 'a');
+
+ expect(tombstones.has('user-1:personal', 'a')).toBe(true);
+ expect(tombstones.has('user-2:personal', 'a')).toBe(true);
+ expect(tombstones.has('user-1:personal', 'b')).toBe(false);
+ });
+
+ it('is idempotent and drops an emptied scope bucket', () => {
+ const tombstones = createTombstones();
+ tombstones.add('s', 'a');
+ tombstones.add('s', 'a');
+ expect(tombstones.size()).toBe(1);
+
+ tombstones.clear('s', 'a');
+ expect(tombstones.size()).toBe(0);
+ expect(tombstones.has('s', 'a')).toBe(false);
+ });
+
+ it('bounds the tracked keys, evicting the oldest first', () => {
+ const tombstones = createTombstones(3);
+ for (const key of ['a', 'b', 'c', 'd']) tombstones.add('s', key);
+
+ // A long-lived session that visits more subjects than the cap must not keep
+ // growing: the oldest keys fall out first.
+ expect(tombstones.size()).toBe(3);
+ expect(tombstones.has('s', 'a')).toBe(false);
+ expect(tombstones.has('s', 'd')).toBe(true);
+ });
+
+ it('does not evict when re-adding an already-tracked key', () => {
+ const tombstones = createTombstones(2);
+ tombstones.add('s', 'a');
+ tombstones.add('s', 'a');
+ tombstones.add('s', 'b');
+
+ expect(tombstones.size()).toBe(2);
+ expect(tombstones.has('s', 'a')).toBe(true);
+ expect(tombstones.has('s', 'b')).toBe(true);
+ });
+});
diff --git a/packages/replica/src/core/tombstones.ts b/packages/replica/src/core/tombstones.ts
new file mode 100644
index 00000000000..94e4b998baa
--- /dev/null
+++ b/packages/replica/src/core/tombstones.ts
@@ -0,0 +1,65 @@
+/**
+ * How many removal tombstones one engine remembers. The guards exist to win a
+ * race with a hydrate that started around a removal, so a modest window is
+ * plenty; the cap is what keeps a long-lived session from growing forever.
+ */
+export const DEFAULT_REMOVAL_TOMBSTONE_LIMIT = 5000;
+
+export interface ReplicaTombstones {
+ /** Remember `scope`/`key` (idempotent). */
+ add: (scope: string, key: string) => void;
+ /** Forget `scope`/`key`; an emptied scope bucket is dropped too. */
+ clear: (scope: string, key: string) => void;
+ has: (scope: string, key: string) => boolean;
+ /** Tracked key count (observability + tests). */
+ size: () => number;
+}
+
+/**
+ * Scope-keyed removal tombstones with a hard size bound.
+ *
+ * A removal must stay visible until a server value supersedes it β€” including
+ * across a scope switch, so the keys are bucketed per scope rather than in one
+ * flat set. But the engine lives as long as the page: a session that visits tens
+ * of thousands of subjects (a task list full of items that simply have no
+ * acceptance) would otherwise pin one entry per subject forever. So the oldest
+ * keys are evicted once the cap is reached.
+ *
+ * Eviction is safe for what the tombstone is for: it closes a race with a
+ * hydrate that was already in flight when the removal landed. By the time a key
+ * is old enough to be evicted, any such read has long since settled.
+ */
+export const createTombstones = (limit = DEFAULT_REMOVAL_TOMBSTONE_LIMIT): ReplicaTombstones => {
+ const byScope = new Map<string, Set<string>>();
+ let tracked = 0;
+
+ const evictOverflow = () => {
+ while (tracked > limit) {
+ // `Map`/`Set` iterate in insertion order, so the first entry is the oldest.
+ const oldestScope = byScope.keys().next().value as string;
+ const keys = byScope.get(oldestScope)!;
+ keys.delete(keys.values().next().value as string);
+ tracked -= 1;
+ if (keys.size === 0) byScope.delete(oldestScope);
+ }
+ };
+
+ return {
+ add: (scope, key) => {
+ const keys = byScope.get(scope) ?? new Set<string>();
+ byScope.set(scope, keys);
+ if (keys.has(key)) return;
+ keys.add(key);
+ tracked += 1;
+ evictOverflow();
+ },
+ clear: (scope, key) => {
+ const keys = byScope.get(scope);
+ if (!keys?.delete(key)) return;
+ tracked -= 1;
+ if (keys.size === 0) byScope.delete(scope);
+ },
+ has: (scope, key) => byScope.get(scope)?.has(key) ?? false,
+ size: () => tracked,
+ };
+};
diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.ts
index ef28ba8509d..c62686740df 100644
--- a/packages/replica/src/core/types.ts
+++ b/packages/replica/src/core/types.ts
@@ -38,6 +38,14 @@ export type ReplicaSource = 'local' | 'server' | 'storage';
* while the scope is still an optimistic guess (identity not resolved yet).
*/
export interface ReplicaScope {
+ /**
+ * Whether this runtime may read the persisted projection back into memory.
+ * Defaults to `true`. A surface that never resolves an identity (e.g. a
+ * public embed that does not mount the user store) opts out: its scope is
+ * only the last-known guess, so hydrating it could paint a different β€” or a
+ * since-invalidated β€” session's private rows before authorization is checked.
+ */
+ canHydrate?: () => boolean;
canPersist: () => boolean;
get: () => string;
use: () => string;
diff --git a/packages/replica/src/core/writeQueue.test.ts b/packages/replica/src/core/writeQueue.test.ts
index 776e2fda2ef..b840141b2ba 100644
--- a/packages/replica/src/core/writeQueue.test.ts
+++ b/packages/replica/src/core/writeQueue.test.ts
@@ -53,4 +53,26 @@ describe('ReplicaWriteQueue', () => {
await new Promise((resolve) => setTimeout(resolve, 20));
expect(rows.has('list')).toBe(false);
});
+
+ it('reports whether a queued write actually landed', async () => {
+ let fail = false;
+ const storage: ReplicaStorage<number> = {
+ get: vi.fn(),
+ remove: vi.fn(async () => {
+ if (fail) throw new Error('IndexedDB delete failed');
+ }),
+ set: vi.fn(async () => {}),
+ };
+ const queue = new ReplicaWriteQueue(storage);
+ const key = { queryKey: 'list', scope: 'scope' };
+
+ await expect(queue.remove(key)).resolves.toBe(true);
+
+ fail = true;
+ // A rejected delete resolves `false` instead of rejecting: the caller must be
+ // able to keep the removal retryable, and one bad write must not poison the
+ // chain for later writers on the same key.
+ await expect(queue.remove(key)).resolves.toBe(false);
+ await expect(queue.set(key, { data: 1, updatedAt: 1 })).resolves.toBe(true);
+ });
});
diff --git a/packages/replica/src/core/writeQueue.ts b/packages/replica/src/core/writeQueue.ts
index 86141cbef39..5f88552dbb4 100644
--- a/packages/replica/src/core/writeQueue.ts
+++ b/packages/replica/src/core/writeQueue.ts
@@ -14,13 +14,11 @@ export class ReplicaWriteQueue<T> {
#id = ({ queryKey, scope }: ReplicaRowKey) => `${scope}:${queryKey}`;
- remove = (key: ReplicaRowKey): void => {
+ remove = (key: ReplicaRowKey): Promise<boolean> =>
this.#enqueue(key, () => this.#storage.remove(key));
- };
- set = (key: ReplicaRowKey, value: ReplicaRow<T>): void => {
+ set = (key: ReplicaRowKey, value: ReplicaRow<T>): Promise<boolean> =>
this.#enqueue(key, () => this.#storage.set(key, value));
- };
/**
* Serialized read-modify-write: `fn` sees the row as of every earlier queued
@@ -30,23 +28,32 @@ export class ReplicaWriteQueue<T> {
update = (
key: ReplicaRowKey,
fn: (current: ReplicaRow<T> | undefined) => ReplicaRow<T> | null | undefined,
- ): void => {
+ ): Promise<boolean> =>
this.#enqueue(key, async () => {
const next = fn(await this.#storage.get(key));
if (next === null) await this.#storage.remove(key);
else if (next !== undefined) await this.#storage.set(key, next);
});
- };
- #enqueue = (key: ReplicaRowKey, operation: () => Promise<void>): void => {
+ /**
+ * Queue `operation` behind the earlier writes for this key and report whether
+ * it settled successfully. A failed write never rejects the returned promise:
+ * the caller decides what to do (e.g. keep a removal retryable), while a
+ * rejection on the queue itself is already swallowed so one bad write cannot
+ * poison the chain.
+ */
+ #enqueue = (key: ReplicaRowKey, operation: () => Promise<void>): Promise<boolean> => {
const id = this.#id(key);
const previous = this.#pending.get(id) ?? Promise.resolve();
const current = previous.catch(() => undefined).then(operation);
this.#pending.set(id, current);
- void current
- .catch(() => undefined)
- .finally(() => {
- if (this.#pending.get(id) === current) this.#pending.delete(id);
- });
+ const settled = current.then(
+ () => true,
+ () => false,
+ );
+ void settled.finally(() => {
+ if (this.#pending.get(id) === current) this.#pending.delete(id);
+ });
+ return settled;
};
}
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.ts
index 6cee3dabba1..80c0ea24b48 100644
--- a/packages/replica/src/zustand/createReplicaSlice.test.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts
@@ -20,8 +20,9 @@ interface TestState {
listsReplica: ReplicaState<string[]>;
}
-const scopeState = { current: 'user-1:personal', trusted: true };
+const scopeState = { canHydrate: true, current: 'user-1:personal', trusted: true };
const scope: ReplicaScope = {
+ canHydrate: () => scopeState.canHydrate,
canPersist: () => scopeState.trusted,
get: () => scopeState.current,
// The real `use` is `useCacheScope`; a plain getter is enough for these tests.
@@ -88,6 +89,7 @@ const wrapper = ({ children }: PropsWithChildren) =>
createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
beforeEach(() => {
+ scopeState.canHydrate = true;
scopeState.current = 'user-1:personal';
scopeState.trusted = true;
});
@@ -137,7 +139,11 @@ describe('createReplicaSlice', () => {
}),
});
renderHook(() => failing.slice.useSync({ id: 'b' }, { onError }), { wrapper });
- await waitFor(() => expect(onError).toHaveBeenCalledWith(failure));
+ // The callback also receives the key/scope the failing read was captured
+ // under, so a terminal removal can be bound to the right scope.
+ await waitFor(() =>
+ expect(onError).toHaveBeenCalledWith(failure, { key: 'b', scope: 'user-1:personal' }),
+ );
expect(failing.store.getState().lists.b).toBeUndefined();
});
@@ -334,6 +340,171 @@ describe('createReplicaSlice', () => {
expect(store.getState().lists.a).toEqual(['server']);
});
+ it('does not let a slow hydration resurrect an entry removed while it was in flight', async () => {
+ // A NOT_FOUND / FORBIDDEN response removes the entry (and its row) while
+ // the persisted read is still in flight. That read already holds the old
+ // row, so landing it afterwards would repaint the value just dropped.
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
+ const originalGet = storage.storage.get;
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => (release = resolve));
+ storage.storage.get = async (key) => {
+ const row = await originalGet(key);
+ if (key.queryKey === 'a') await held;
+ return row;
+ };
+ const { slice, store } = setup({ storage });
+
+ let hydration!: Promise<boolean>;
+ await act(async () => {
+ hydration = slice.hydrate({ id: 'a' });
+ });
+
+ // The network answers first and drops the entry.
+ act(() => slice.remove('a'));
+ expect(store.getState().lists.a).toBeUndefined();
+
+ // The slow read settles: it must not paint the row the removal dropped.
+ await act(async () => {
+ release();
+ await hydration;
+ });
+
+ expect(store.getState().lists.a).toBeUndefined();
+ expect(store.getState().listsReplica.entries.a).toBeUndefined();
+ });
+
+ it('refuses to hydrate a key that was explicitly removed even if its row is still on disk', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
+ const { slice, store } = setup({ storage });
+
+ act(() => slice.remove('a'));
+ // The delete may not have flushed yet β€” the row must not come back anyway.
+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
+
+ await act(async () => {
+ expect(await slice.hydrate({ id: 'a' })).toBe(false);
+ });
+ expect(store.getState().lists.a).toBeUndefined();
+ });
+
+ it('lets a later server value supersede a removal so the key hydrates again', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
+ const { slice, store } = setup({ storage });
+
+ act(() => slice.remove('a'));
+ // Access restored: the server now answers with a value again.
+ act(() => slice.replace({ id: 'a' }, ['regranted']));
+ expect(store.getState().lists.a).toEqual(['regranted']);
+ // Let the confirmed value reach the persisted row before reading it back.
+ await waitFor(() =>
+ expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['regranted']),
+ );
+
+ // Drop memory the way a scope switch does, then come back: with the
+ // removal superseded, the persisted row may hydrate once more.
+ scopeState.current = 'user-2:personal';
+ act(() => slice.ensureScope('user-2:personal'));
+ scopeState.current = 'user-1:personal';
+ act(() => slice.ensureScope('user-1:personal'));
+
+ await act(async () => {
+ expect(await slice.hydrate({ id: 'a' })).toBe(true);
+ });
+ expect(store.getState().lists.a).toEqual(['regranted']);
+ });
+
+ it('reports a keyless (disabled) read as hydrated, so it never looks loading', () => {
+ const { slice } = setup();
+
+ const { result } = renderHook(() => slice.useSync(null), { wrapper });
+
+ expect(result.current.isHydrated).toBe(true);
+ expect(result.current.isValidating).toBe(false);
+ });
+
+ it('keeps the removal guard when a response captured under another scope is discarded', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
+ // The persisted-row delete is best-effort: simulate it still being pending.
+ storage.storage.remove = async () => {};
+ const { slice, store } = setup({ storage });
+
+ // Scope A removes the entry (and arms its guard).
+ act(() => slice.remove('a'));
+
+ // A response captured under A resolves only after the user switched to B,
+ // so `dispatch` drops it. It must not clear A's guard on the way out.
+ scopeState.current = 'user-2:personal';
+ act(() => slice.replace({ id: 'a' }, ['stale'], 'user-1:personal'));
+
+ // Switching back to A must still refuse to hydrate the stale row.
+ scopeState.current = 'user-1:personal';
+ await act(async () => {
+ expect(await slice.hydrate({ id: 'a' })).toBe(false);
+ });
+ expect(store.getState().lists.a).toBeUndefined();
+ });
+
+ it('purges the captured scope row for a removal that lands after a scope switch', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
+ const { slice, store } = setup({ storage });
+
+ // The active scope has its own entry loaded.
+ scopeState.current = 'user-2:personal';
+ act(() => slice.replace({ id: 'a' }, ['b-value']));
+ expect(store.getState().lists.a).toEqual(['b-value']);
+
+ // A late NOT_FOUND from a request captured under the previous scope must
+ // not delete the entry that is on screen now…
+ act(() => slice.remove('a', 'user-1:personal'));
+ expect(store.getState().lists.a).toEqual(['b-value']);
+
+ // …but that scope's own persisted row still has to go, or switching back
+ // to it would hydrate the value the server just denied.
+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());
+ });
+
+ it('retries an off-scope purge once the captured scope may persist again', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
+ const { slice } = setup({ storage });
+
+ // The terminal answer lands while writes are still refused.
+ scopeState.current = 'user-2:personal';
+ scopeState.trusted = false;
+ act(() => slice.remove('a', 'user-1:personal'));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(storage.rows.get('user-1:personal|a')).toBeDefined();
+
+ // Identity resolves: the next terminal answer must clear the row, not
+ // report a no-op that never deletes it.
+ scopeState.trusted = true;
+ act(() => slice.remove('a', 'user-1:personal'));
+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());
+ });
+
+ it('binds the captured key and scope to the error callback', async () => {
+ const fetcher = vi.fn(async () => {
+ throw new Error('not found');
+ });
+ const { slice } = setup({ fetcher });
+ const contexts: { key: string | undefined; scope: string }[] = [];
+
+ scopeState.current = 'user-1:personal';
+ renderHook(
+ () => slice.useSync({ id: 'a' }, { onError: (_error, context) => contexts.push(context) }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(contexts.length).toBeGreaterThan(0));
+ expect(contexts[0]).toEqual({ key: 'a', scope: 'user-1:personal' });
+ });
+
it('a version bump ignores rows written by the previous version', async () => {
// One backing map shared by every version, keyed by the namespace the
// factory receives β€” like IndexedDB rows of two app releases.
@@ -444,6 +615,22 @@ describe('createReplicaSlice', () => {
expect(store.getState().lists.a).toBeUndefined();
});
+ it('does not hydrate the persisted projection when the runtime opts out', async () => {
+ // An identity-less runtime (e.g. the public Workbench) can only guess the
+ // scope, so it must not read another session's rows back into memory.
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['someone-elses'], updatedAt: 1 });
+ scopeState.canHydrate = false;
+ const { slice, store } = setup({ storage });
+
+ await act(async () => {
+ await slice.hydrate({ id: 'a' });
+ });
+
+ expect(store.getState().lists.a).toBeUndefined();
+ expect(store.getState().listsReplica.entries.a).toBeUndefined();
+ });
+
it('never persists while the scope is untrusted', async () => {
scopeState.trusted = false;
const { slice, storage } = setup();
@@ -453,6 +640,118 @@ describe('createReplicaSlice', () => {
await new Promise((resolve) => setTimeout(resolve, 10));
expect(storage.writes).toEqual([]);
});
+
+ it('retries a removal whose storage delete failed, instead of treating it as purged', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });
+ const { slice } = setup({ storage });
+
+ const original = storage.storage.remove;
+ let attempts = 0;
+ storage.storage.remove = async (key) => {
+ attempts += 1;
+ if (attempts === 1) throw new Error('IndexedDB delete failed');
+ return original(key);
+ };
+
+ // The first delete is rejected by storage: the guard is armed, but the row
+ // is still on disk and must NOT be treated as purged.
+ act(() => slice.remove('a'));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(storage.rows.get('user-1:personal|a')).toBeDefined();
+
+ // A later terminal answer must retry the delete rather than no-op.
+ act(() => slice.remove('a'));
+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());
+ expect(attempts).toBeGreaterThanOrEqual(2);
+ });
+
+ it('retries the storage delete of a removal made while the scope was untrusted', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });
+ const { slice } = setup({ storage });
+
+ // Cold boot: identity is not resolved, so writes are refused and the
+ // delete never reaches storage β€” the hydration guard is armed all the same.
+ scopeState.trusted = false;
+ act(() => slice.remove('a'));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(storage.rows.get('user-1:personal|a')).toBeDefined();
+
+ // Identity resolves: the next removal must clear the row, not no-op.
+ scopeState.trusted = true;
+ act(() => slice.remove('a'));
+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());
+ });
+ });
+
+ describe('missing responses', () => {
+ it('applies a response the resource marks as missing as an explicit removal', () => {
+ // A nullable detail (e.g. the acceptance attached to a subject): the
+ // server answering "none" must clear a previously cached value, not let
+ // the merge fall back to it.
+ type NullableState = {
+ notes: Record<string, string[] | null>;
+ notesReplica: ReplicaState<string[] | null>;
+ };
+ const resource = defineReplica<{ id: string }, string[] | null>({
+ key: ({ id }) => id,
+ name: 'nullableNote',
+ scope,
+ version: 1,
+ });
+ const store = createStore<NullableState>()(() => ({
+ notes: {},
+ notesReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<NullableState, { id: string }, string[] | null>(resource, {
+ driver,
+ get: store.getState,
+ isMissing: (note) => note === null,
+ set: (partial) => store.setState(partial),
+ stateKey: 'notesReplica',
+ view: recordLens('notes'),
+ });
+
+ act(() => slice.replace({ id: 'a' }, ['kept']));
+ expect(store.getState().notes.a).toEqual(['kept']);
+
+ act(() => slice.replace({ id: 'a' }, null));
+ expect(store.getState().notes.a).toBeUndefined();
+ expect(store.getState().notesReplica.entries.a).toBeUndefined();
+ });
+
+ it('treats a repeated missing response as a no-op', () => {
+ type NullableState = {
+ notes: Record<string, string[] | null>;
+ notesReplica: ReplicaState<string[] | null>;
+ };
+ const resource = defineReplica<{ id: string }, string[] | null>({
+ key: ({ id }) => id,
+ name: 'nullableNoteRepeat',
+ scope,
+ version: 1,
+ });
+ const store = createStore<NullableState>()(() => ({
+ notes: {},
+ notesReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<NullableState, { id: string }, string[] | null>(resource, {
+ driver,
+ get: store.getState,
+ isMissing: (note) => note === null,
+ set: (partial) => store.setState(partial),
+ stateKey: 'notesReplica',
+ view: recordLens('notes'),
+ });
+
+ act(() => slice.replace({ id: 'a' }, ['kept']));
+ // The first "missing" drops the entry and clears stale storage…
+ expect(slice.replace({ id: 'a' }, null)).toBe(true);
+ // …a poll that still answers "missing" must not re-emit the removal.
+ expect(slice.replace({ id: 'a' }, null)).toBe(false);
+ expect(store.getState().notes.a).toBeUndefined();
+ });
});
describe('optimistic', () => {
diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.ts
index 0f492194827..de14c89963b 100644
--- a/packages/replica/src/zustand/createReplicaSlice.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.ts
@@ -36,10 +36,27 @@ export interface CreateReplicaSliceOptions<TStore, TParams, TData, TFetched> ext
view: ReplicaLens<TStore, TData>;
}
+/**
+ * What a failed sync read was captured under. `scope` is the cache scope active
+ * when the request was issued, which may differ from the scope active when the
+ * callback runs (an identity / workspace switch in between).
+ */
+export interface ReplicaSyncErrorContext {
+ /** The entry key the read was for; `undefined` for a disabled read. */
+ key: string | undefined;
+ /** The cache scope the read was captured under. */
+ scope: string;
+}
+
export interface ReplicaSyncOptions<TFetched = unknown> extends ReplicaSyncSchedule {
enabled?: boolean;
- /** Side effects of a failed fetch (error side-maps); the store view is left as is. */
- onError?: (error: unknown) => void;
+ /**
+ * Side effects of a failed fetch (error side-maps); the store view is left as is.
+ * Receives the captured {@link ReplicaSyncErrorContext} so a terminal removal
+ * can target the scope the request belonged to rather than the one that is
+ * active once the callback runs.
+ */
+ onError?: (error: unknown, context: ReplicaSyncErrorContext) => void;
/**
* Side effects of a response, run after it is folded into the replica
* (e.g. adopting an active id, or settling a "not found" state).
@@ -159,7 +176,9 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
() => fetcher!(params!, undefined),
{
...schedule,
- onError,
+ // Bind the captured key/scope to the error callback: a late terminal
+ // removal must not land in a scope that became active after the request.
+ onError: onError ? (error: unknown) => onError(error, { key, scope }) : undefined,
onSuccess: (data) => {
// Discard a head response the entry has moved past: the newer query
// owns the view (see `headQuery`).
@@ -172,9 +191,14 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
return {
error: sync.error,
+ // A read with no key has nothing to hydrate, so it counts as hydrated: a
+ // conditional consumer must not show "loading" for an absent id (the
+ // former SWR disabled-key behaviour). A read that is disabled but *has* a
+ // key still waits for its persisted row.
isHydrated:
+ key === undefined ||
!resource.persisted ||
- (key !== undefined && !resource.persistKey(key)) ||
+ !resource.persistKey(key) ||
hydration.data === true,
isValidating: sync.isValidating,
revalidate: () => sync.mutate(),
diff --git a/src/features/Acceptance/Viewer/AcceptanceInitialBundle.tsx b/src/features/Acceptance/Viewer/AcceptanceInitialBundle.tsx
new file mode 100644
index 00000000000..7c97aa3512f
--- /dev/null
+++ b/src/features/Acceptance/Viewer/AcceptanceInitialBundle.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { createContext, type ReactNode, use, useMemo } from 'react';
+
+import type { AcceptanceBundle } from '@/services/verify';
+
+/** A bundle an authorized server fetch already returned, tied to its acceptance id. */
+export interface AcceptanceInitialBundleValue {
+ acceptanceId: string;
+ bundle: AcceptanceBundle;
+}
+
+const AcceptanceInitialBundleContext = createContext<AcceptanceInitialBundleValue | null>(null);
+
+/**
+ * Carry a loader-fetched bundle to the render tree as request-local data.
+ *
+ * The Workbench SSR loader already holds an authorized bundle before the first
+ * render, but the replica store is a module singleton shared by every request
+ * the server handles: writing the bundle into it at render time would leak one
+ * request's authorized entry into a later (or concurrent) request whose loader
+ * returned `null`. A React context is created fresh per render β€” per request on
+ * the server β€” and the same value reaches both the server render and the client
+ * hydration, so the two trees agree and no shared store is mutated.
+ *
+ * It is a fallback only: as soon as the live replica holds a value, that value
+ * wins (see {@link useAcceptanceBundle}).
+ */
+export const AcceptanceInitialBundle = ({
+ acceptanceId,
+ bundle,
+ children,
+}: {
+ acceptanceId: string;
+ bundle: AcceptanceBundle | null | undefined;
+ children: ReactNode;
+}) => {
+ const value = useMemo(() => (bundle ? { acceptanceId, bundle } : null), [acceptanceId, bundle]);
+ return <AcceptanceInitialBundleContext value={value}>{children}</AcceptanceInitialBundleContext>;
+};
+
+/** The loader-provided bundle for this render, if any (`null` in the main app). */
+export const useAcceptanceInitialBundle = () => use(AcceptanceInitialBundleContext);
diff --git a/src/features/Acceptance/Viewer/useAcceptanceBundle.test.ts b/src/features/Acceptance/Viewer/useAcceptanceBundle.test.ts
index 646732558c0..314383b623d 100644
--- a/src/features/Acceptance/Viewer/useAcceptanceBundle.test.ts
+++ b/src/features/Acceptance/Viewer/useAcceptanceBundle.test.ts
@@ -1,49 +1,218 @@
/** @vitest-environment happy-dom */
import { act, renderHook } from '@testing-library/react';
-import { afterEach, expect, it, vi } from 'vitest';
+import type { PropsWithChildren } from 'react';
+import { createElement } from 'react';
+import { beforeEach, expect, it, vi } from 'vitest';
+import { createReplicaState } from '@/libs/replica';
+
+import { AcceptanceInitialBundle } from './AcceptanceInitialBundle';
import { useAcceptanceBundle } from './useAcceptanceBundle';
-const { useClientDataSWR, mutate } = vi.hoisted(() => ({
- useClientDataSWR: vi.fn(),
+const swr = vi.hoisted(() => {
+ const revalidate = vi.fn(async () => undefined);
+ const state: { error: unknown } = { error: undefined };
+ return {
+ revalidate,
+ state,
+ useClientDataSWR: vi.fn(() => ({
+ error: state.error,
+ isValidating: false,
+ mutate: revalidate,
+ })),
+ };
+});
+
+vi.mock('@/libs/swr', () => ({
mutate: vi.fn(),
+ useClientDataSWR: swr.useClientDataSWR,
}));
-vi.mock('@/libs/swr', () => ({ useClientDataSWR }));
vi.mock('@/services/verify', () => ({ verifyService: { getAcceptanceBundle: vi.fn() } }));
-afterEach(() => {
- vi.useRealTimers();
+// Imported after the mocks so the store binds the mocked driver.
+const { useVerifyStore } = await import('@/store/verify');
+
+const seedBundle = (id: string, bundle: unknown) =>
+ useVerifyStore.setState({ acceptanceBundleMap: { [id]: bundle as never } });
+
+/** The config the bundle's `replica:sync` query was registered with. */
+const bundleSyncConfig = async () => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ const call = vi
+ .mocked(useClientDataSWR)
+ .mock.calls.find(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === 'acceptanceBundle',
+ );
+ return call?.[2] as { refreshInterval?: number } | undefined;
+};
+
+beforeEach(() => {
vi.clearAllMocks();
+ swr.state.error = undefined;
+ useVerifyStore.setState({
+ acceptanceBundleMap: {},
+ acceptanceBundleReplica: createReplicaState(),
+ acceptanceBySubjectMap: {},
+ acceptanceBySubjectReplica: createReplicaState(),
+ });
});
-it.each(['accepted', 'closed', 'delivered'])(
- 'does not poll a %s acceptance with unstarted flow definitions',
- (status) => {
- vi.useFakeTimers();
- useClientDataSWR.mockReturnValue({
- data: { acceptance: { status }, flows: [{ versions: [{ runs: [] }] }] },
- mutate,
- });
- const { unmount } = renderHook(() => useAcceptanceBundle('acceptance'));
- act(() => vi.advanceTimersByTime(10000));
- expect(mutate).not.toHaveBeenCalled();
- unmount();
- },
-);
-
-it('polls active verification and stops when the acceptance is accepted', () => {
- vi.useFakeTimers();
- const data = {
- acceptance: { status: 'verifying' },
- flows: [{ versions: [{ runs: [{ status: 'collecting_evidence' }] }] }],
+it('reads the bundle straight from the replica view', () => {
+ seedBundle('acceptance-1', { acceptance: { status: 'verifying' } });
+
+ const { result } = renderHook(() => useAcceptanceBundle('acceptance-1'));
+
+ expect(result.current.data).toMatchObject({ acceptance: { status: 'verifying' } });
+});
+
+it('polls a still-moving acceptance every 5s', async () => {
+ seedBundle('acceptance-1', { acceptance: { status: 'verifying' } });
+
+ renderHook(() => useAcceptanceBundle('acceptance-1'));
+
+ expect((await bundleSyncConfig())?.refreshInterval).toBe(5000);
+});
+
+it.each(['accepted', 'closed'])('stops polling a settled (%s) acceptance', async (status) => {
+ seedBundle('acceptance-1', { acceptance: { status } });
+
+ renderHook(() => useAcceptanceBundle('acceptance-1'));
+
+ expect((await bundleSyncConfig())?.refreshInterval).toBe(0);
+});
+
+it('never polls a detail-only reader, even while the round is live', async () => {
+ seedBundle('acceptance-1', { acceptance: { status: 'verifying' } });
+
+ renderHook(() => useAcceptanceBundle('acceptance-1', { poll: false }));
+
+ expect((await bundleSyncConfig())?.refreshInterval).toBe(0);
+});
+
+it('registers no sync query without an acceptance id', async () => {
+ renderHook(() => useAcceptanceBundle(null));
+
+ expect(await bundleSyncConfig()).toBeUndefined();
+});
+
+it('never reports loading without an acceptance id', () => {
+ const { result } = renderHook(() => useAcceptanceBundle(null));
+
+ expect(result.current.isLoading).toBe(false);
+});
+
+/** Wraps a hook in the request-local initial bundle the Workbench loader provides. */
+const initialBundleWrapper = (acceptanceId: string, bundle: unknown) =>
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(
+ AcceptanceInitialBundle,
+ { acceptanceId, bundle: bundle as never },
+ children,
+ );
};
- useClientDataSWR.mockReturnValue({ data, mutate });
- const { rerender, unmount } = renderHook(() => useAcceptanceBundle('acceptance'));
- act(() => vi.advanceTimersByTime(5000));
- expect(mutate).toHaveBeenCalledTimes(1);
- data.acceptance.status = 'accepted';
+
+it('paints the loader-provided initial bundle on the first render', () => {
+ const bundle = { acceptance: { status: 'verifying' } };
+ const { result } = renderHook(() => useAcceptanceBundle('acceptance-1'), {
+ wrapper: initialBundleWrapper('acceptance-1', bundle),
+ });
+
+ // The gate must paint the authorized bundle instead of a spinner: the
+ // Workbench runtime never hydrates the persisted replica, so without this the
+ // server and the first client render would have no data at all.
+ expect(result.current.data).toBe(bundle);
+ expect(result.current.isLoading).toBe(false);
+});
+
+it('ignores an initial bundle that belongs to another acceptance id', () => {
+ const { result } = renderHook(() => useAcceptanceBundle('acceptance-2'), {
+ wrapper: initialBundleWrapper('acceptance-1', { acceptance: { status: 'verifying' } }),
+ });
+
+ expect(result.current.data).toBeUndefined();
+});
+
+it('stops exposing the initial bundle once the server answers a terminal error', () => {
+ const bundle = { acceptance: { status: 'verifying' } };
+ const { result, rerender } = renderHook(() => useAcceptanceBundle('acceptance-1'), {
+ wrapper: initialBundleWrapper('acceptance-1', bundle),
+ });
+ expect(result.current.data).toBe(bundle);
+
+ // Deleted / access revoked after the loader succeeded: the replica entry is
+ // dropped, and the immutable seed must not be re-exposed behind it β€” the gate
+ // would otherwise keep painting (and polling) a bundle the server no longer
+ // serves instead of its terminal state.
+ swr.state.error = { data: { code: 'NOT_FOUND' } };
rerender();
- act(() => vi.advanceTimersByTime(10000));
- expect(mutate).toHaveBeenCalledTimes(1);
- unmount();
+
+ expect(result.current.data).toBeUndefined();
+});
+
+it('prefers the live replica over the initial bundle', () => {
+ seedBundle('acceptance-1', { acceptance: { status: 'accepted' } });
+
+ const { result } = renderHook(() => useAcceptanceBundle('acceptance-1'), {
+ wrapper: initialBundleWrapper('acceptance-1', { acceptance: { status: 'verifying' } }),
+ });
+
+ expect(result.current.data).toMatchObject({ acceptance: { status: 'accepted' } });
+});
+
+it('mutate revalidates this acceptance and resolves the freshly read value', async () => {
+ seedBundle('acceptance-1', { acceptance: { status: 'verifying' } });
+ const { result } = renderHook(() => useAcceptanceBundle('acceptance-1'));
+
+ const syncKey = vi
+ .mocked(swr.useClientDataSWR)
+ .mock.calls.map(([key]) => key)
+ .find(
+ (key) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === 'acceptanceBundle',
+ ) as unknown[];
+
+ await act(async () => {
+ await result.current.mutate();
+ });
+
+ // The hook's mutate revalidates the entry through its own SWR key.
+ expect(swr.revalidate).toHaveBeenCalled();
+ expect(syncKey[4]).toBe('acceptance-1');
+
+ await expect(result.current.mutate()).resolves.toMatchObject({
+ acceptance: { status: 'verifying' },
+ });
+});
+
+/** The `onError` handler the bundle's sync query was registered with. */
+const bundleSyncOnError = async () => {
+ const config = (await bundleSyncConfig()) as { onError?: (error: unknown) => void } | undefined;
+ return config?.onError;
+};
+
+it('drops a cached bundle when revalidation reports it is gone', async () => {
+ seedBundle('acceptance-1', { acceptance: { status: 'verifying' } });
+
+ renderHook(() => useAcceptanceBundle('acceptance-1'));
+
+ const onError = await bundleSyncOnError();
+ await act(async () => {
+ onError?.({ data: { code: 'NOT_FOUND' } });
+ });
+
+ // The gate must be able to show the terminal state, not a stale decision
+ // surface kept alive by the persisted projection.
+ expect(useVerifyStore.getState().acceptanceBundleMap['acceptance-1']).toBeUndefined();
+});
+
+it('keeps a cached bundle on a retryable revalidation failure', async () => {
+ seedBundle('acceptance-1', { acceptance: { status: 'verifying' } });
+
+ renderHook(() => useAcceptanceBundle('acceptance-1'));
+
+ const onError = await bundleSyncOnError();
+ await act(async () => {
+ onError?.(new Error('offline'));
+ });
+
+ expect(useVerifyStore.getState().acceptanceBundleMap['acceptance-1']).toBeDefined();
});
diff --git a/src/features/Acceptance/Viewer/useAcceptanceBundle.ts b/src/features/Acceptance/Viewer/useAcceptanceBundle.ts
index e0d618788de..b1993dfe60d 100644
--- a/src/features/Acceptance/Viewer/useAcceptanceBundle.ts
+++ b/src/features/Acceptance/Viewer/useAcceptanceBundle.ts
@@ -1,19 +1,33 @@
-import { useEffect } from 'react';
-
-import { useClientDataSWR } from '@/libs/swr';
-import { verifyKeys } from '@/libs/swr/keys';
-import { verifyService } from '@/services/verify';
+import type { AcceptanceBundle } from '@/services/verify';
+import { useVerifyStore } from '@/store/verify';
+import { isTrpcErrorCode } from '@/utils/trpcError';
+import { useAcceptanceInitialBundle } from './AcceptanceInitialBundle';
import { LIVE_ACCEPTANCE_STATUSES } from './verdict';
-const ACCEPTANCE_BUNDLE_SWR_CONFIG = {
- revalidateOnFocus: true,
- revalidateOnReconnect: true,
-} as const;
+/** Poll cadence of a still-moving acceptance round. */
+const ACCEPTANCE_BUNDLE_POLL_INTERVAL = 5000;
+
+/** What `useAcceptanceBundle` hands its readers β€” the former SWR response shape. */
+export interface AcceptanceBundleSync {
+ /** The bundle from the replica view; `undefined` until hydrated or fetched. */
+ data: AcceptanceBundle | undefined;
+ error: unknown;
+ /** Nothing to show yet, and a hydration or fetch is still outstanding. */
+ isLoading: boolean;
+ isValidating: boolean;
+ /** Re-read the bundle and resolve with the freshly read value. */
+ mutate: () => Promise<AcceptanceBundle | undefined>;
+}
/**
- * The acceptance bundle, revalidating on focus/reconnect as a live decision
- * surface.
+ * The acceptance bundle, read from the verify store's replica of
+ * `acceptanceBundleMap[acceptanceId]` β€” the local projection paints on the
+ * first frame, the network confirms behind it.
+ *
+ * The bundle is a LIVE decision surface (rounds run and reviews land while the
+ * reviewer is away), so the sync revalidates on focus/reconnect and polls every
+ * 5s while the aggregate is still moving.
*
* `poll: false` is for a surface that reads a bundle only as a DETAIL view β€”
* the goal result page opens one per task row β€” where the live 5s poll would
@@ -21,26 +35,56 @@ const ACCEPTANCE_BUNDLE_SWR_CONFIG = {
* revalidation (returning to the tab still refreshes) and leaves the always-on
* polling to the acceptance page itself.
*/
-export const useAcceptanceBundle = (acceptanceId: string | null, options?: { poll?: boolean }) => {
+export const useAcceptanceBundle = (
+ acceptanceId: string | null,
+ options?: { poll?: boolean },
+): AcceptanceBundleSync => {
const poll = options?.poll ?? true;
- const swr = useClientDataSWR(
- acceptanceId ? verifyKeys.acceptanceBundle(acceptanceId) : null,
- () => verifyService.getAcceptanceBundle(acceptanceId!),
- ACCEPTANCE_BUNDLE_SWR_CONFIG,
+ const useFetchAcceptanceBundle = useVerifyStore((s) => s.useFetchAcceptanceBundle);
+ const replicaData = useVerifyStore((s) =>
+ acceptanceId ? s.acceptanceBundleMap[acceptanceId] : undefined,
);
+ // The Workbench SSR loader hands its authorized bundle down as request-local
+ // context data; it fills the first paint (server + hydration) until the live
+ // replica holds a value of its own.
+ const initial = useAcceptanceInitialBundle();
+
+ // The poll follows the LIVE replica, not the static loader seed: a snapshot
+ // cannot know whether the round is still moving.
+ const status = replicaData?.acceptance.status;
+ const polling = poll && !!status && LIVE_ACCEPTANCE_STATUSES.has(status);
+
+ const sync = useFetchAcceptanceBundle(acceptanceId, {
+ refreshInterval: polling ? ACCEPTANCE_BUNDLE_POLL_INTERVAL : 0,
+ });
- const status = swr.data?.acceptance.status;
- useEffect(() => {
- if (!poll) return;
- if (!status || !LIVE_ACCEPTANCE_STATUSES.has(status)) return;
- const timer = setInterval(() => void swr.mutate(), 5000);
- return () => clearInterval(timer);
- }, [poll, status, swr.mutate]);
+ /**
+ * A terminal answer supersedes the loader bundle: once the server says the
+ * acceptance is deleted (NOT_FOUND) or no longer ours (FORBIDDEN), the
+ * immutable seed must not be re-exposed behind the entry the replica just
+ * dropped β€” the gate would keep painting (and polling) a bundle the server no
+ * longer serves instead of its terminal state.
+ */
+ const terminal =
+ isTrpcErrorCode(sync.error, 'NOT_FOUND') || isTrpcErrorCode(sync.error, 'FORBIDDEN');
+ const seeded =
+ !terminal && initial && initial.acceptanceId === acceptanceId ? initial.bundle : undefined;
+ const data = replicaData ?? seeded;
- return swr;
+ return {
+ data,
+ error: sync.error,
+ // A read with no id has nothing to load β€” never report it as loading.
+ isLoading: !!acceptanceId && !data && !sync.error && (sync.isValidating || !sync.isHydrated),
+ isValidating: sync.isValidating,
+ mutate: async () => {
+ await sync.revalidate();
+ return acceptanceId ? useVerifyStore.getState().acceptanceBundleMap[acceptanceId] : undefined;
+ },
+ };
};
-type AcceptanceBundleData = Awaited<ReturnType<typeof verifyService.getAcceptanceBundle>>;
+type AcceptanceBundleData = AcceptanceBundle;
/** An evidence's current file URL, wherever in the bundle (a check or its history) it sits. */
export const findEvidenceFileUrl = (
diff --git a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx
index e3a3b707b90..ebe9e1e491c 100644
--- a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx
+++ b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx
@@ -35,12 +35,11 @@ import { useNavigate, useParams } from 'react-router';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { SkeletonList } from '@/features/NavPanel/components/SkeletonList';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
-import { mutate as globalMutate } from '@/libs/swr';
-import { verifyKeys } from '@/libs/swr/keys';
import type { AcceptanceStatusOverride } from '@/services/verify';
import { verifyService } from '@/services/verify';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { useVerifyStore } from '@/store/verify';
import { useAcceptanceList, useAcceptanceListInfinite } from '../hooks';
import { acceptanceHomePath } from '../Viewer/routes';
@@ -433,7 +432,9 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(
failedIds: string[],
) => {
await mutate();
- await Promise.all(changedIds.map((id) => globalMutate(verifyKeys.acceptanceBundle(id))));
+ await Promise.all(
+ changedIds.map((id) => useVerifyStore.getState().refreshAcceptanceBundle(id)),
+ );
const attempted = new Set(attemptedIds);
let remaining: string[] = [];
diff --git a/src/features/Acceptance/Workspace/AcceptanceRow.tsx b/src/features/Acceptance/Workspace/AcceptanceRow.tsx
index f02c259516a..c85207be782 100644
--- a/src/features/Acceptance/Workspace/AcceptanceRow.tsx
+++ b/src/features/Acceptance/Workspace/AcceptanceRow.tsx
@@ -27,10 +27,9 @@ import { useNavigate } from 'react-router';
import { openRenameModal } from '@/components/RenameModal';
import NavItem from '@/features/NavPanel/components/NavItem';
-import { mutate as globalMutate } from '@/libs/swr';
-import { verifyKeys } from '@/libs/swr/keys';
import type { AcceptanceListItem } from '@/services/verify';
import { verifyService } from '@/services/verify';
+import { useVerifyStore } from '@/store/verify';
import { acceptanceListPath } from '../Viewer/routes';
import { getAcceptanceStatusActions } from '../Viewer/statusActions';
@@ -126,7 +125,7 @@ const AcceptanceRow = memo<{
const title = item.subject.title || item.subjectId;
const refresh = () =>
- Promise.all([onChanged(), globalMutate(verifyKeys.acceptanceBundle(item.id))]);
+ Promise.all([onChanged(), useVerifyStore.getState().refreshAcceptanceBundle(item.id)]);
/**
* The shared rename dialog, same as a topic's. An in-place input inside a
@@ -212,7 +211,10 @@ const AcceptanceRow = memo<{
try {
const summary = await verifyService.mergeAcceptance(item.id, targetId);
if (active) navigate(`/acceptance/${targetId}`, { replace: true });
- await Promise.all([onChanged(), globalMutate(verifyKeys.acceptanceBundle(targetId))]);
+ await Promise.all([
+ onChanged(),
+ useVerifyStore.getState().refreshAcceptanceBundle(targetId),
+ ]);
toast.success(t('acceptance.workspace.merge.success', { count: summary.movedChecks }));
return true;
} catch (error) {
diff --git a/src/features/Acceptance/hooks.ts b/src/features/Acceptance/hooks.ts
index 0077134ad33..06b15668d1a 100644
--- a/src/features/Acceptance/hooks.ts
+++ b/src/features/Acceptance/hooks.ts
@@ -7,12 +7,14 @@ import { useClientDataSWR } from '@/libs/swr';
import { verifyKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
import type {
+ AcceptanceBySubject,
AcceptanceListFilter,
AcceptanceListPage,
AcceptanceListQuery,
VerifyReportSummaryPage,
} from '@/services/verify';
import { verifyService } from '@/services/verify';
+import { useVerifyStore } from '@/store/verify';
const VERIFY_REPORT_PAGE_SIZE = 30;
const ACCEPTANCE_PAGE_SIZE = 30;
@@ -69,22 +71,48 @@ export const useVerifyReportBundle = (verifyRunId: string | null) =>
export { useAcceptanceBundle } from './Viewer/useAcceptanceBundle';
-/** The optional acceptance aggregate attached to a task/topic/document subject. */
+/** What `useAcceptanceBySubject` hands its readers β€” the former SWR response shape. */
+export interface AcceptanceBySubjectSync {
+ /** The attachment from the replica view; `undefined` until hydrated or fetched. */
+ data: AcceptanceBySubject | undefined;
+ error: unknown;
+ /** Nothing to show yet, and a hydration or fetch is still outstanding. */
+ isLoading: boolean;
+ isValidating: boolean;
+ /** Re-read the attachment and resolve with the freshly read value. */
+ mutate: () => Promise<AcceptanceBySubject | undefined>;
+}
+
+/**
+ * The optional acceptance aggregate attached to a task/topic/document subject,
+ * read from the verify store's replica of `acceptanceBySubjectMap`. A subject
+ * can mount before its first Verify Run creates the aggregate, so the sync
+ * polls fastest until one exists and then keeps it live until it settles.
+ */
export const useAcceptanceBySubject = (
subjectType: AcceptanceSubjectType,
subjectId: string | null,
-) =>
- useClientDataSWR(
- subjectId ? verifyKeys.acceptanceBySubject(subjectType, subjectId) : null,
- () => verifyService.getAcceptanceBySubject(subjectType, subjectId!),
- {
- ...ACCEPTANCE_BUNDLE_SWR_CONFIG,
- // A task can mount before its first Verify Run creates the aggregate.
- // Discover that server-side transition without requiring focus/reload,
- // then stop polling as soon as the Acceptance exists.
- refreshInterval: getAcceptanceBySubjectRefreshInterval,
+): AcceptanceBySubjectSync => {
+ const useFetchAcceptanceBySubject = useVerifyStore((s) => s.useFetchAcceptanceBySubject);
+ const key = subjectId ? `${subjectType}:${subjectId}` : undefined;
+ const data = useVerifyStore((s) => (key ? s.acceptanceBySubjectMap[key] : undefined));
+
+ const sync = useFetchAcceptanceBySubject(subjectType, subjectId, {
+ refreshInterval: getAcceptanceBySubjectRefreshInterval(data),
+ });
+
+ return {
+ data,
+ error: sync.error,
+ // A read with no subject has nothing to load β€” never report it as loading.
+ isLoading: !!subjectId && !data && !sync.error && (sync.isValidating || !sync.isHydrated),
+ isValidating: sync.isValidating,
+ mutate: async () => {
+ await sync.revalidate();
+ return key ? useVerifyStore.getState().acceptanceBySubjectMap[key] : undefined;
},
- );
+ };
+};
/**
* The caller's recent acceptance aggregates (with subject headers) β€” the list
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx
index 904a5b3d4be..552af7c88b6 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx
@@ -284,7 +284,7 @@ const TaskAcceptance = memo<TaskAcceptanceProps>(({ variant = 'default' }) => {
<Collapsible open={sectionExpanded}>
<Flexbox className={styles.body} gap={14}>
{bundleLoading && <Spin size="middle" />}
- {bundleError && <AcceptanceError onRetry={() => void mutateBundle()} />}
+ {bundleError ? <AcceptanceError onRetry={() => void mutateBundle()} /> : null}
{bundle && (
<>
<GoalRoundTimeline rounds={bundle.rounds} />
diff --git a/src/features/Portal/Acceptance/useMoreMenu.ts b/src/features/Portal/Acceptance/useMoreMenu.ts
index 21753546edf..1c9c1a7fe86 100644
--- a/src/features/Portal/Acceptance/useMoreMenu.ts
+++ b/src/features/Portal/Acceptance/useMoreMenu.ts
@@ -7,9 +7,10 @@ import { openAcceptanceDeleteConfirm } from '@/features/Acceptance/Workspace/Acc
import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
import { usePermission } from '@/hooks/usePermission';
import { mutate as globalMutate } from '@/libs/swr';
-import { isAcceptanceListKey, verifyKeys } from '@/libs/swr/keys';
+import { isAcceptanceListKey } from '@/libs/swr/keys';
import { verifyService } from '@/services/verify';
import { useChatStore } from '@/store/chat';
+import { useVerifyStore } from '@/store/verify';
import { useAcceptancePageUrl } from './usePageUrl';
@@ -30,7 +31,7 @@ export const useAcceptanceMoreMenu = (): PortalMoreMenuConfig | undefined => {
// The workspace list shows the same title, so a rename refreshes both.
const refreshAll = () =>
Promise.all([
- globalMutate(verifyKeys.acceptanceBundle(acceptanceId)),
+ useVerifyStore.getState().refreshAcceptanceBundle(acceptanceId),
globalMutate(isAcceptanceListKey),
]);
@@ -51,7 +52,7 @@ export const useAcceptanceMoreMenu = (): PortalMoreMenuConfig | undefined => {
title,
})
: undefined,
- refresh: () => globalMutate(verifyKeys.acceptanceBundle(acceptanceId)),
+ refresh: () => useVerifyStore.getState().refreshAcceptanceBundle(acceptanceId),
rename: canManage
? () =>
openRenameModal({
diff --git a/src/features/Portal/AcceptanceCheck/useMoreMenu.ts b/src/features/Portal/AcceptanceCheck/useMoreMenu.ts
index 6d458a036a4..46c1371f077 100644
--- a/src/features/Portal/AcceptanceCheck/useMoreMenu.ts
+++ b/src/features/Portal/AcceptanceCheck/useMoreMenu.ts
@@ -1,9 +1,8 @@
import { acceptanceCheckPath } from '@/features/Acceptance/Viewer/routes';
import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
-import { mutate as globalMutate } from '@/libs/swr';
-import { verifyKeys } from '@/libs/swr/keys';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useVerifyStore } from '@/store/verify';
import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import { usePortalShareUrl } from '../components/PortalMoreMenu/shareUrl';
@@ -22,6 +21,6 @@ export const useAcceptanceCheckMoreMenu = (): PortalMoreMenuConfig | undefined =
copyLink: shareUrl,
openInPage: shareUrl ? () => openTrustedExternalUrl(shareUrl) : undefined,
// A check has no cache of its own β€” it is read out of the acceptance bundle.
- refresh: () => globalMutate(verifyKeys.acceptanceBundle(acceptanceId)),
+ refresh: () => useVerifyStore.getState().refreshAcceptanceBundle(acceptanceId),
};
};
diff --git a/src/libs/replica/index.test.ts b/src/libs/replica/index.test.ts
index 83f0734bfaa..0158c179f2b 100644
--- a/src/libs/replica/index.test.ts
+++ b/src/libs/replica/index.test.ts
@@ -1,13 +1,24 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
-import { replicaSWRDriver } from './index';
+import { cacheScope, replicaSWRDriver, setReplicaPersistedHydration } from './index';
// Many suites mock `@/libs/swr` with only the exports they use. The topic store
// imports this module eagerly, so it must not touch `mutate` at import time.
vi.mock('@/libs/swr', () => ({ useClientDataSWR: vi.fn() }));
describe('@/libs/replica', () => {
+ afterEach(() => setReplicaPersistedHydration(true));
+
it('imports under a partial `@/libs/swr` mock', () => {
expect(replicaSWRDriver).toBeDefined();
});
+
+ it('lets an identity-less runtime opt out of persisted hydration', () => {
+ expect(cacheScope.canHydrate?.()).toBe(true);
+
+ // The Workbench runtime turns this off at boot (it never mounts the user
+ // store), so its replicas read network-only instead of a guessed partition.
+ setReplicaPersistedHydration(false);
+ expect(cacheScope.canHydrate?.()).toBe(false);
+ });
});
diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.ts
index 7d3e3d94c19..bd970a96ba0 100644
--- a/src/libs/replica/index.ts
+++ b/src/libs/replica/index.ts
@@ -28,7 +28,26 @@ import { getCacheScope, isScopeTrusted, useCacheScope } from '@/libs/swr/useCach
* fetch through the app's SWR hook (workspace-augmented keys, retry policy).
*/
+/**
+ * Whether this runtime may hydrate replicas from their persisted projection.
+ *
+ * The Workbench runtime renders the public acceptance / verify surfaces and
+ * never mounts the user store, so its cache scope stays the last-known user's
+ * partition. Hydrating there would paint a previous β€” possibly expired or
+ * server-invalidated β€” session's private rows before any authorization is
+ * checked, so the Workbench entry turns hydration off at boot. The main SPA
+ * keeps it on for the instant-from-cache first paint (it hydrates the persisted
+ * partition in parallel with the session check, then resets on a scope change).
+ */
+let replicaHydrationEnabled = true;
+
+/** Enable/disable reads from the persisted projection for this runtime. */
+export const setReplicaPersistedHydration = (enabled: boolean): void => {
+ replicaHydrationEnabled = enabled;
+};
+
export const cacheScope: ReplicaScope = {
+ canHydrate: () => replicaHydrationEnabled,
canPersist: isScopeTrusted,
get: getCacheScope,
use: useCacheScope,
diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.ts
index 12432a29f59..621991a9568 100644
--- a/src/libs/swr/keys.test.ts
+++ b/src/libs/swr/keys.test.ts
@@ -65,7 +65,7 @@ describe('isAcceptanceListKey', () => {
expect(isAcceptanceListKey(['verify:acceptances', '100', 'needle', 'all', 'workspace-1'])).toBe(
true,
);
- expect(isAcceptanceListKey(['verify:acceptanceBundle', 'acceptance-1'])).toBe(false);
+ expect(isAcceptanceListKey(['verify:acceptancePurgePreview', 'acceptance-1'])).toBe(false);
});
it('keeps project-scoped acceptance feeds in separate cache entries', () => {
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 0ed28458cc9..0553ad1d537 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -962,18 +962,6 @@ const acceptanceListKeyParts = ({ filter, projectId, scope, source }: Acceptance
];
export const verifyKeys = {
- acceptanceBundle: def('verify:acceptanceBundle', (acceptanceId: string) => [
- 'verify:acceptanceBundle',
- acceptanceId,
- ]),
- acceptanceBySubject: def(
- 'verify:acceptanceBySubject',
- (subjectType: string, subjectId: string) => [
- 'verify:acceptanceBySubject',
- subjectType,
- subjectId,
- ],
- ),
/** Statuses for a known subject set. Ids are sorted+joined so the key is order-free. */
acceptanceStatuses: def(
'verify:acceptanceStatuses',
diff --git a/src/store/verify/acceptance.test.ts b/src/store/verify/acceptance.test.ts
index fba59ad3bd2..ce830bf57fd 100644
--- a/src/store/verify/acceptance.test.ts
+++ b/src/store/verify/acceptance.test.ts
@@ -1,48 +1,182 @@
+import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { useClientDataSWR } from '@/libs/swr';
+import { cacheScope, createReplicaState } from '@/libs/replica';
+import { verifyService } from '@/services/verify';
import { useVerifyStore } from './index';
-vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));
+vi.mock('@/services/verify', () => ({
+ verifyService: {
+ getAcceptanceBundle: vi.fn(),
+ getAcceptanceBySubject: vi.fn(),
+ },
+}));
+
+// The replica drives its fetches through the app SWR hook; mocking it lets a
+// test hand the engine a server response without a network round trip.
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
beforeEach(() => {
vi.clearAllMocks();
- useVerifyStore.setState({ acceptanceBundleMap: {}, acceptanceBySubjectMap: {} });
+ useVerifyStore.setState({
+ acceptanceBundleMap: {},
+ acceptanceBundleReplica: createReplicaState(),
+ acceptanceBySubjectMap: {},
+ acceptanceBySubjectReplica: createReplicaState(),
+ });
});
-describe('Acceptance store', () => {
- it('normalizes acceptances by subject', () => {
- useVerifyStore.getState().useFetchAcceptanceBySubject('task', 'task-1');
- const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {
- onSuccess: (value: { id: string }) => void;
- };
+/** The `replica:sync` query a resource registered with the SWR driver. */
+const syncCalls = async (name: 'acceptanceBundle' | 'acceptanceBySubject') => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ return vi
+ .mocked(useClientDataSWR)
+ .mock.calls.filter(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ )
+ .map(([key, _fetcher, config]) => ({
+ config: config as { onSuccess?: (data: unknown) => void },
+ key: key as unknown[],
+ }));
+};
+
+/** The matcher functions passed to the scoped SWR `mutate` by a revalidate. */
+const revalidateMatchers = async () => {
+ const { mutate } = await import('@/libs/swr');
+ return vi
+ .mocked(mutate)
+ .mock.calls.map(([arg]) => arg)
+ .filter((arg): arg is (key: unknown) => boolean => typeof arg === 'function');
+};
+
+describe('verify acceptance replica', () => {
+ it('reports an acceptance bundle under the replica sync key of its id', async () => {
+ renderHook(() => useVerifyStore.getState().useFetchAcceptanceBundle('acceptance-1'));
+
+ const calls = await syncCalls('acceptanceBundle');
+ expect(calls).toHaveLength(1);
+ expect(calls[0].key[4]).toBe('acceptance-1');
+ });
+
+ it('paints a fetched bundle into the replica view', async () => {
+ vi.mocked(verifyService.getAcceptanceBundle).mockResolvedValue({
+ acceptance: { id: 'acceptance-1' },
+ checks: [],
+ } as never);
+
+ renderHook(() => useVerifyStore.getState().useFetchAcceptanceBundle('acceptance-1'));
+ const [call] = await syncCalls('acceptanceBundle');
+
+ await act(async () => {
+ call.config.onSuccess?.({ acceptance: { id: 'acceptance-1' }, checks: [] });
+ });
+
+ expect(useVerifyStore.getState().acceptanceBundleMap['acceptance-1']).toMatchObject({
+ acceptance: { id: 'acceptance-1' },
+ checks: [],
+ });
+ });
+
+ it('keys a subject attachment as `<subjectType>:<subjectId>`', async () => {
+ vi.mocked(verifyService.getAcceptanceBySubject).mockResolvedValue({
+ id: 'acceptance-1',
+ status: 'verifying',
+ } as never);
+
+ renderHook(() => useVerifyStore.getState().useFetchAcceptanceBySubject('task', 'task-1'));
+ const [call] = await syncCalls('acceptanceBySubject');
+
+ expect(call.key[4]).toBe('task:task-1');
- options.onSuccess({ id: 'acceptance-1' });
+ await act(async () => {
+ call.config.onSuccess?.({ id: 'acceptance-1', status: 'verifying' });
+ });
- expect(useVerifyStore.getState().acceptanceBySubjectMap['task:task-1']).toEqual({
+ expect(useVerifyStore.getState().acceptanceBySubjectMap['task:task-1']).toMatchObject({
id: 'acceptance-1',
+ status: 'verifying',
});
});
- it('does not poll indefinitely when a subject has no acceptance', () => {
- useVerifyStore.getState().useFetchAcceptanceBySubject('task', 'task-without-acceptance');
- const options = vi.mocked(useClientDataSWR).mock.calls[0][2];
+ it('keeps a subject without an acceptance empty so the poll can discover it', async () => {
+ vi.mocked(verifyService.getAcceptanceBySubject).mockResolvedValue(null);
+
+ renderHook(() => useVerifyStore.getState().useFetchAcceptanceBySubject('task', 'task-2'));
+ const [call] = await syncCalls('acceptanceBySubject');
+
+ await act(async () => {
+ call.config.onSuccess?.(null);
+ });
- expect(options).not.toHaveProperty('refreshInterval');
+ expect(useVerifyStore.getState().acceptanceBySubjectMap['task:task-2']).toBeUndefined();
});
- it('caches bundles by acceptance id', () => {
- useVerifyStore.getState().useFetchAcceptanceBundle('acceptance-1');
- const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {
- onSuccess: (value: { acceptance: { id: string }; checks: never[] }) => void;
- };
+ it('clears a subject attachment the server no longer has', async () => {
+ renderHook(() => useVerifyStore.getState().useFetchAcceptanceBySubject('task', 'task-3'));
+ const [call] = await syncCalls('acceptanceBySubject');
- options.onSuccess({ acceptance: { id: 'acceptance-1' }, checks: [] });
+ // The subject starts with an aggregate, as an earlier poll / hydrate left it.
+ await act(async () => {
+ call.config.onSuccess?.({ id: 'acceptance-1', status: 'verifying' });
+ });
+ expect(useVerifyStore.getState().acceptanceBySubjectMap['task:task-3']).toMatchObject({
+ id: 'acceptance-1',
+ status: 'verifying',
+ });
- expect(useVerifyStore.getState().acceptanceBundleMap['acceptance-1']).toMatchObject({
- acceptance: { id: 'acceptance-1' },
- checks: [],
+ // A later poll reports none (the acceptance was deleted): the previous
+ // aggregate must be removed, not retained by the merge fallback.
+ await act(async () => {
+ call.config.onSuccess?.(null);
});
+ expect(useVerifyStore.getState().acceptanceBySubjectMap['task:task-3']).toBeUndefined();
+ });
+
+ it('revalidates only the refreshed acceptance bundle', async () => {
+ await useVerifyStore.getState().refreshAcceptanceBundle('acceptance-1');
+
+ const matchers = await revalidateMatchers();
+ const matches = (key: unknown[]) => matchers.some((matcher) => matcher(key));
+ const scope = cacheScope.get();
+
+ expect(
+ matches(['replica:sync', 'acceptanceBundle', 1, scope, 'acceptance-1', 'acceptance-1']),
+ ).toBe(true);
+ expect(
+ matches(['replica:sync', 'acceptanceBundle', 1, scope, 'acceptance-2', 'acceptance-2']),
+ ).toBe(false);
+ });
+
+ it('revalidates only the refreshed subject attachment', async () => {
+ await useVerifyStore.getState().refreshAcceptanceBySubject('task', 'task-1');
+
+ const matchers = await revalidateMatchers();
+ const matches = (key: unknown[]) => matchers.some((matcher) => matcher(key));
+ const scope = cacheScope.get();
+
+ expect(
+ matches([
+ 'replica:sync',
+ 'acceptanceBySubject',
+ 1,
+ scope,
+ 'task:task-1',
+ { subjectId: 'task-1', subjectType: 'task' },
+ ]),
+ ).toBe(true);
+ expect(
+ matches([
+ 'replica:sync',
+ 'acceptanceBySubject',
+ 1,
+ scope,
+ 'task:task-2',
+ { subjectId: 'task-2', subjectType: 'task' },
+ ]),
+ ).toBe(false);
});
});
diff --git a/src/store/verify/action.ts b/src/store/verify/action.ts
index a4c844b113d..3e2f6e5b94b 100644
--- a/src/store/verify/action.ts
+++ b/src/store/verify/action.ts
@@ -1,22 +1,33 @@
import type { AcceptanceSubjectType, VerifyRubricConfig } from '@lobechat/types';
import { debounce } from 'es-toolkit/compat';
+import isEqual from 'fast-deep-equal';
import { type StateCreator } from 'zustand';
import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@/const/index';
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { verifyKeys } from '@/libs/swr/keys';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
import { documentService } from '@/services/document';
+import type { AcceptanceBundle, AcceptanceBySubject } from '@/services/verify';
import { verifyService } from '@/services/verify';
import { type StoreSetter } from '@/store/types';
import { flattenActions } from '@/store/utils/flattenActions';
+import { isTrpcErrorCode } from '@/utils/trpcError';
import { initialState, type State, type VerifyCriterionEdit } from './initialState';
+import {
+ acceptanceBundleResource,
+ acceptanceBySubjectKey,
+ acceptanceBySubjectResource,
+} from './projection';
export type Action = Pick<ActionImpl, keyof ActionImpl>;
export type Store = State & Action;
type Setter = StoreSetter<Store>;
+/** `acceptanceBundleMap` / `acceptanceBySubjectMap` are plain `Record<key, value>` views. */
+const acceptanceBundleLens = recordLens<Store, AcceptanceBundle>('acceptanceBundleMap');
+const acceptanceBySubjectLens = recordLens<Store, AcceptanceBySubject>('acceptanceBySubjectMap');
+
/**
* The verify store owns the write-back loop for the delivery-check config
* portal: every control writes through `updateCriterion` / `updateInstruction`,
@@ -26,6 +37,10 @@ type Setter = StoreSetter<Store>;
export class ActionImpl {
readonly #get: () => Store;
readonly #set: Setter;
+ /** The acceptance aggregate replica, behind `acceptanceBundleMap[acceptanceId]`. */
+ readonly #bundle;
+ /** The subject-attachment replica, behind `acceptanceBySubjectMap`. */
+ readonly #bySubject;
/** Pending writes coalesced per id and flushed together on a debounce. */
#pendingCriteria = new Map<string, VerifyCriterionEdit>();
@@ -43,59 +58,90 @@ export class ActionImpl {
maxWait: EDITOR_MAX_WAIT,
trailing: true,
});
+
+ this.#bundle = createReplicaSlice(acceptanceBundleResource, {
+ actionPrefix: 'acceptanceBundle',
+ fetcher: (acceptanceId) => verifyService.getAcceptanceBundle(acceptanceId),
+ get,
+ // A poll that returns the same bundle keeps its reference, so a 5s
+ // revalidation of a settled deliverable does not re-render every reader.
+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),
+ set,
+ stateKey: 'acceptanceBundleReplica',
+ view: acceptanceBundleLens,
+ });
+ this.#bySubject = createReplicaSlice(acceptanceBySubjectResource, {
+ actionPrefix: 'acceptanceBySubject',
+ fetcher: ({ subjectId, subjectType }) =>
+ verifyService.getAcceptanceBySubject(subjectType, subjectId),
+ get,
+ // The server answers `null` for a subject whose acceptance was deleted:
+ // treat it as an explicit removal so the previous aggregate is not kept
+ // (and re-persisted) by the merge.
+ isMissing: (acceptance) => acceptance == null,
+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),
+ set,
+ stateKey: 'acceptanceBySubjectReplica',
+ view: acceptanceBySubjectLens,
+ });
}
+ /** Re-read one acceptance bundle (after a review, merge, delete or status sweep). */
refreshAcceptanceBundle = async (acceptanceId: string): Promise<void> => {
- await mutate(verifyKeys.acceptanceBundle(acceptanceId));
+ await this.#bundle.revalidate(acceptanceId);
};
+ /** Re-read one subject's acceptance (after it is created or settled). */
refreshAcceptanceBySubject = async (
subjectType: AcceptanceSubjectType,
subjectId: string,
): Promise<void> => {
- await mutate(verifyKeys.acceptanceBySubject(subjectType, subjectId));
+ await this.#bySubject.revalidate(acceptanceBySubjectKey({ subjectId, subjectType }));
};
- useFetchAcceptanceBundle = (acceptanceId?: string | null) =>
- useClientDataSWR(
- acceptanceId ? verifyKeys.acceptanceBundle(acceptanceId) : null,
- () => verifyService.getAcceptanceBundle(acceptanceId!),
- {
- onSuccess: (data) => {
- this.#set(
- ({ acceptanceBundleMap }) => ({
- acceptanceBundleMap: { ...acceptanceBundleMap, [acceptanceId!]: data },
- }),
- false,
- 'useFetchAcceptanceBundle/success',
- );
- },
- revalidateOnFocus: true,
- revalidateOnReconnect: true,
- },
- );
-
- useFetchAcceptanceBySubject = (subjectType: AcceptanceSubjectType, subjectId?: string | null) =>
- useClientDataSWR(
- subjectId ? verifyKeys.acceptanceBySubject(subjectType, subjectId) : null,
- () => verifyService.getAcceptanceBySubject(subjectType, subjectId!),
- {
- onSuccess: (data) => {
- const key = `${subjectType}:${subjectId}`;
- const { acceptanceBySubjectMap } = this.#get();
- if (Object.hasOwn(acceptanceBySubjectMap, key) && acceptanceBySubjectMap[key] === data)
- return;
-
- this.#set(
- { acceptanceBySubjectMap: { ...acceptanceBySubjectMap, [key]: data } },
- false,
- 'useFetchAcceptanceBySubject/success',
- );
- },
- revalidateOnFocus: true,
- revalidateOnReconnect: true,
+ /**
+ * Fetch orchestration only; the caller reads the bundle through
+ * `acceptanceBundleMap` (`verifySelectors.acceptanceBundle`). `refreshInterval`
+ * drives the live 5s poll of an in-flight round.
+ */
+ useFetchAcceptanceBundle = (
+ acceptanceId?: string | null,
+ options: { enabled?: boolean; refreshInterval?: number } = {},
+ ): ReplicaSyncResult =>
+ this.#bundle.useSync(acceptanceId || null, {
+ enabled: options.enabled ?? true,
+ onError: (error, { key, scope }) => {
+ // A deleted (NOT_FOUND) or unauthorized (FORBIDDEN) bundle must not keep
+ // rendering from the projection: drop the entry so the gate shows its
+ // terminal state instead of a stale decision surface. Bind the removal to
+ // the scope the failing request was captured under β€” an identity or
+ // workspace switch while it was in flight must not let the error delete
+ // the same id out of the scope that is active now.
+ if (key && (isTrpcErrorCode(error, 'NOT_FOUND') || isTrpcErrorCode(error, 'FORBIDDEN'))) {
+ this.#bundle.remove(key, scope);
+ }
},
- );
+ refreshInterval: options.refreshInterval,
+ revalidateOnFocus: true,
+ revalidateOnReconnect: true,
+ });
+
+ /**
+ * Fetch orchestration only; the caller reads the attachment through
+ * `acceptanceBySubjectMap`. A subject without an acceptance yet keeps polling
+ * so the aggregate a later verify run creates is discovered without a reload.
+ */
+ useFetchAcceptanceBySubject = (
+ subjectType: AcceptanceSubjectType,
+ subjectId?: string | null,
+ options: { enabled?: boolean; refreshInterval?: number } = {},
+ ): ReplicaSyncResult =>
+ this.#bySubject.useSync(subjectId ? { subjectId, subjectType } : null, {
+ enabled: options.enabled ?? true,
+ refreshInterval: options.refreshInterval,
+ revalidateOnFocus: true,
+ revalidateOnReconnect: true,
+ });
#persist = async (): Promise<void> => {
const criteria = [...this.#pendingCriteria.entries()];
diff --git a/src/store/verify/index.ts b/src/store/verify/index.ts
index 8f400b0f422..b81a3f1f19c 100644
--- a/src/store/verify/index.ts
+++ b/src/store/verify/index.ts
@@ -4,6 +4,7 @@ import { shallow } from 'zustand/shallow';
import { createWithEqualityFn } from 'zustand/traditional';
import { createDevtools } from '@/store/middleware/createDevtools';
+import { expose } from '@/store/middleware/expose';
import { type Store, store } from './action';
@@ -13,4 +14,6 @@ const devtools = createDevtools('verify');
export const useVerifyStore = createWithEqualityFn<Store>()(devtools(store), shallow);
+expose('verify', useVerifyStore);
+
export { verifySelectors } from './selectors';
diff --git a/src/store/verify/initialState.ts b/src/store/verify/initialState.ts
index 658d41daf5a..871a0239df8 100644
--- a/src/store/verify/initialState.ts
+++ b/src/store/verify/initialState.ts
@@ -1,5 +1,6 @@
import type { VerifierType, VerifyOnFailStrategy, VerifyRubricConfig } from '@lobechat/types';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
import type { AcceptanceBundle, AcceptanceBySubject } from '@/services/verify';
/** The criterion fields the portal can edit. */
@@ -12,8 +13,14 @@ export interface VerifyCriterionEdit {
}
export interface State {
+ /** Replica view of the acceptance bundles, one entry per acceptance id. */
acceptanceBundleMap: Record<string, AcceptanceBundle>;
+ /** Replica bookkeeping of `acceptanceBundleMap`. */
+ acceptanceBundleReplica: ReplicaState<AcceptanceBundle>;
+ /** Replica view of the subject attachments, one entry per `<subjectType>:<subjectId>`. */
acceptanceBySubjectMap: Record<string, AcceptanceBySubject>;
+ /** Replica bookkeeping of `acceptanceBySubjectMap`. */
+ acceptanceBySubjectReplica: ReplicaState<AcceptanceBySubject>;
/**
* Per-criterion edit overlay, keyed by `verify_criteria.id`. Holds the
* user's in-flight edits so the UI reflects them immediately while they are
@@ -39,7 +46,9 @@ export interface State {
export const initialState: State = {
acceptanceBundleMap: {},
+ acceptanceBundleReplica: createReplicaState(),
acceptanceBySubjectMap: {},
+ acceptanceBySubjectReplica: createReplicaState(),
criterionEdits: {},
instructionEdits: {},
rubricConfigEdits: {},
diff --git a/src/store/verify/projection.ts b/src/store/verify/projection.ts
new file mode 100644
index 00000000000..80de1f1eff0
--- /dev/null
+++ b/src/store/verify/projection.ts
@@ -0,0 +1,47 @@
+import type { AcceptanceSubjectType } from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+import type { AcceptanceBundle, AcceptanceBySubject } from '@/services/verify';
+
+/**
+ * The Acceptance aggregate of one acceptance id (`acceptanceBundleMap[id]`):
+ * the live review surface read by the Acceptance viewer, the task acceptance
+ * tab, the acceptance portal and the workbench embed.
+ *
+ * Persisted to IndexedDB, so a reload paints the last-seen bundle from the
+ * local projection before the network confirms it β€” a 5s poll keeps the live
+ * decision surface current afterwards.
+ */
+export const acceptanceBundleResource = defineReplica<string, AcceptanceBundle>({
+ key: (acceptanceId) => acceptanceId,
+ name: 'acceptanceBundle',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** The subject (topic / task / document) an acceptance is attached to. */
+export interface AcceptanceBySubjectParams {
+ subjectId: string;
+ subjectType: AcceptanceSubjectType;
+}
+
+/** One subject's entry key in `acceptanceBySubjectMap`. */
+export const acceptanceBySubjectKey = ({ subjectId, subjectType }: AcceptanceBySubjectParams) =>
+ `${subjectType}:${subjectId}`;
+
+/**
+ * The standing acceptance aggregate attached to a subject, keyed
+ * `<subjectType>:<subjectId>` (`acceptanceBySubjectMap`). A subject without an
+ * acceptance resolves to nothing β€” the sync hook keeps polling at a fast
+ * interval to discover the aggregate a later verify run creates.
+ */
+export const acceptanceBySubjectResource = defineReplica<
+ AcceptanceBySubjectParams,
+ AcceptanceBySubject,
+ AcceptanceBySubject
+>({
+ key: acceptanceBySubjectKey,
+ name: 'acceptanceBySubject',
+ storage: 'indexedDB',
+ version: 1,
+});