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.

✨ feat(replica): @lobechat/replica local-first package + topic list migration (#20256)

Arvin Xu5b269dbc5580
diff --git a/package.json b/package.json
index 765791b2cc7..69e01ba2666 100644
--- a/package.json
+++ b/package.json
@@ -310,6 +310,7 @@
"@lobechat/openapi": "workspace:*",
"@lobechat/prompts": "workspace:*",
"@lobechat/python-interpreter": "workspace:*",
+ "@lobechat/replica": "workspace:*",
"@lobechat/shared-tool-ui": "workspace:*",
"@lobechat/ssrf-safe-fetch": "workspace:*",
"@lobechat/tool-runtime": "workspace:*",
diff --git a/packages/replica/README.md b/packages/replica/README.md
new file mode 100644
index 00000000000..8f7810abb48
--- /dev/null
+++ b/packages/replica/README.md
@@ -0,0 +1,50 @@
+# @lobechat/replica
+
+Every list and detail the UI shows is a **replica**: a local copy of server state that paints on the first frame, then converges on the server in the background.
+
+- **First frame from the replica.** The last confirmed value is read from persistent storage before the network answers, so a reload or a revisit never flashes a skeleton.
+- **Server confirms quietly.** The head page from the network replaces the replica. Loaded pages, client-only rows and pending writes survive the replace.
+- **Writes land immediately.** Optimistic overlays apply right away. A failed write rolls back to the confirmed base plus any other writes still in flight. Optimistic values never reach storage.
+- **One entity, every copy.** `linkReplicaEntity` sends a patch or delete to every replica that holds the entity: the list row, the management page and the detail cache.
+- **Identity-safe.** Memory and storage are partitioned by scope (user + workspace). On a scope switch the view is cleared before paint, and late results from the previous scope are dropped.
+
+## Layers
+
+| Entry | What it owns |
+| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `@lobechat/replica` | Core engine, framework-agnostic: resource definition, pure reducer, paging (offset / cursor, forward / backward), entity links, serialized persistence. |
+| `@lobechat/replica/zustand` | Zustand adapter: binds a resource to one location in a domain store (`recordLens`). Adds a `useSync` hook that schedules fetches through a `ReplicaSyncDriver` (`createSWRDriver` for SWR). |
+
+The host store stays the only UI source of truth. Components read the store through their usual selectors. `useSync` only reports fetch flags (`isHydrated`, `isValidating`, `error`, `revalidate`) and never returns data.
+
+## Usage
+
+```ts
+import { definePagedReplica } from '@lobechat/replica';
+import { createReplicaSlice, createSWRDriver, recordLens } from '@lobechat/replica/zustand';
+
+const topicList = definePagedReplica<Params, Topic, number, TopicPage>({
+ key: ({ agentId }) => `agent_${agentId}`,
+ name: 'topicList',
+ paging: { direction: 'forward', getId: (t) => t.id, mode: 'offset', persist: { pages: 1 } },
+ query: ({ sortBy }) => ({ sortBy }), // query identity beyond the key
+ scope, // ReplicaScope: { get, use, canPersist }
+ storage: (namespace) => new MyIndexedDBStorage(namespace), // ReplicaStorage
+ version: 1,
+});
+
+const slice = createReplicaSlice(topicList, {
+ driver: createSWRDriver({ mutate, useSWR }),
+ fetcher: fetchTopicPage, // (params, cursor) => { items, total?, nextCursor? }
+ get,
+ set,
+ stateKey: 'topicListReplica', // bookkeeping slot: createReplicaState()
+ view: recordLens('topicDataMap'), // where the rendered value lives
+});
+
+slice.useSync(params); // in a component: hydrate, then sync
+slice.loadMore(key);
+slice.optimistic(key, apply, serverCall);
+```
+
+Inside LobeHub, use `@/libs/replica`. It presets the cache scope, IndexedDB / localStorage storage and the app's SWR driver.
diff --git a/packages/replica/package.json b/packages/replica/package.json
new file mode 100644
index 00000000000..f815cbef01f
--- /dev/null
+++ b/packages/replica/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "@lobechat/replica",
+ "version": "0.0.1",
+ "private": true,
+ "description": "Local-first replicas: paint the last known state on the first frame, reconcile with the server in the background",
+ "exports": {
+ ".": {
+ "types": "./src/index.ts",
+ "default": "./src/index.ts"
+ },
+ "./zustand": {
+ "types": "./src/zustand/index.ts",
+ "default": "./src/zustand/index.ts"
+ }
+ },
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "scripts": {
+ "test": "vitest",
+ "test:coverage": "vitest --coverage --silent='passed-only'"
+ },
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3"
+ },
+ "devDependencies": {
+ "@testing-library/react": "^16.3.2",
+ "swr": "^2.5.0",
+ "zustand": "5.0.4"
+ },
+ "peerDependencies": {
+ "react": ">=18",
+ "zustand": ">=4"
+ },
+ "peerDependenciesMeta": {
+ "zustand": {
+ "optional": true
+ }
+ }
+}
diff --git a/packages/replica/src/core/defineReplica.ts b/packages/replica/src/core/defineReplica.ts
new file mode 100644
index 00000000000..78c93ece8db
--- /dev/null
+++ b/packages/replica/src/core/defineReplica.ts
@@ -0,0 +1,117 @@
+import type { ReplicaPagedData, ReplicaPageResult, ReplicaPagingConfig } from './paging';
+import type { ReplicaResource, ReplicaScope, ReplicaStorage } from './types';
+
+/** Persisted row key: one row per entry key and query. */
+export const replicaStorageKey = (key: string, query?: string) => (query ? `${key}?${query}` : key);
+
+/** Deterministic JSON: sorted keys, `undefined` dropped. */
+export const stableQueryKey = (value: unknown): string =>
+ JSON.stringify(value, (_key, item) =>
+ item && typeof item === 'object' && !Array.isArray(item)
+ ? Object.fromEntries(
+ Object.keys(item)
+ .sort()
+ .filter((key) => item[key] !== undefined)
+ .map((key) => [key, item[key]]),
+ )
+ : item,
+ ) ?? '';
+
+/**
+ * A fixed identity partition. The default for apps without accounts; an app
+ * with sign-in passes a scope derived from the signed-in user / workspace so
+ * one browser profile never mixes two identities' rows.
+ */
+export const staticReplicaScope = (scope = 'default'): ReplicaScope => ({
+ canPersist: () => true,
+ get: () => scope,
+ use: () => scope,
+});
+
+const DEFAULT_SCOPE = staticReplicaScope();
+
+/** Builds the storage of one resource from its namespace (`replica:<name>:v<version>`). */
+export type ReplicaStorageFactory<TData> = (namespace: string) => ReplicaStorage<TData> | undefined;
+
+export interface DefineReplicaOptions<TParams, TData, TFetched = TData> {
+ /** Default network fetcher; a store binding may override it. */
+ fetcher?: (params: TParams, cursor?: any) => Promise<TFetched>;
+ /** Entry identity inside one scope (memory bucket + persisted row). */
+ key: (params: TParams) => string;
+ name: string;
+ paging?: ReplicaPagingConfig<any>;
+ /**
+ * Query identity beyond `key` (filters, sort, page size) β€” anything that
+ * changes the rows without changing the key. Persisted rows are kept per
+ * query, so a projection taken under other filters never hydrates; in memory
+ * a query change resets loaded pages.
+ */
+ query?: (params: TParams) => unknown;
+ /** Identity partition of memory and persisted rows. Defaults to one static scope. */
+ scope?: ReplicaScope;
+ /** Persisted copy of the replica. Omit for a memory-only replica (no first-frame paint). */
+ storage?: ReplicaStorage<TData> | ReplicaStorageFactory<TData>;
+ /** Bump to invalidate every persisted row written by older shapes. */
+ version: number;
+}
+
+export const defineReplica = <TParams, TData, TFetched = TData>(
+ options: DefineReplicaOptions<TParams, TData, TFetched>,
+): ReplicaResource<TParams, TData, TFetched> => {
+ const namespace = `replica:${options.name}:v${options.version}`;
+ const storage =
+ typeof options.storage === 'function' ? options.storage(namespace) : options.storage;
+
+ return {
+ fetcher: options.fetcher,
+ key: options.key,
+ name: options.name,
+ namespace,
+ paging: options.paging,
+ persisted: !!storage,
+ query: (params) => (options.query ? stableQueryKey(options.query(params)) : undefined),
+ storageKey: (params) =>
+ replicaStorageKey(
+ options.key(params),
+ options.query ? stableQueryKey(options.query(params)) : undefined,
+ ),
+ scope: options.scope ?? DEFAULT_SCOPE,
+ storage,
+ version: options.version,
+ };
+};
+
+export interface DefinePagedReplicaOptions<TParams, TItem, TCursor> extends Omit<
+ DefineReplicaOptions<
+ TParams,
+ ReplicaPagedData<TItem, TCursor>,
+ ReplicaPageResult<TItem, TCursor>
+ >,
+ 'fetcher' | 'paging' | 'storage'
+> {
+ /** `cursor` is `undefined` for the head page. */
+ fetchPage?: (
+ params: TParams,
+ cursor: TCursor | undefined,
+ ) => Promise<ReplicaPageResult<TItem, TCursor>>;
+ paging: ReplicaPagingConfig<TItem>;
+ storage?: ReplicaStorage<any> | ReplicaStorageFactory<any>;
+}
+
+/**
+ * A resource whose value is a paged list ({@link ReplicaPagedData}). The
+ * store view type may extend the paged shape with domain fields.
+ */
+export const definePagedReplica = <
+ TParams,
+ TItem,
+ TCursor = number,
+ TData extends ReplicaPagedData<TItem, TCursor> = ReplicaPagedData<TItem, TCursor>,
+>(
+ options: DefinePagedReplicaOptions<TParams, TItem, TCursor>,
+): ReplicaResource<TParams, TData, ReplicaPageResult<TItem, TCursor>> =>
+ defineReplica<TParams, TData, ReplicaPageResult<TItem, TCursor>>({
+ ...options,
+ fetcher: options.fetchPage,
+ storage: options.storage as ReplicaStorage<TData> | ReplicaStorageFactory<TData> | undefined,
+ });
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.ts
new file mode 100644
index 00000000000..1bab6badfe5
--- /dev/null
+++ b/packages/replica/src/core/engine.ts
@@ -0,0 +1,540 @@
+import isEqual from 'fast-deep-equal';
+
+import { replicaStorageKey, stableQueryKey } from './defineReplica';
+import {
+ applyHeadPage,
+ applyNextPage,
+ collapseToHead,
+ getNextPageCursor,
+ hasPagedItem,
+ insertHeadItems,
+ mapPagedItem,
+ type ReplicaPagedData,
+ type ReplicaPageResult,
+ type ReplicaPagingContext,
+ toPersistedPage,
+} from './paging';
+import type { ReplicaAction, ReplicaEffect, ReplicaViewWrite } from './reducer';
+import { replicaReducer } from './reducer';
+import type { ReplicaResource, ReplicaState } from './types';
+import { ReplicaWriteQueue } from './writeQueue';
+
+/** Reserved storage key of the per-scope index of persisted rows. */
+export const REPLICA_INDEX_KEY = '__replica:index';
+
+/**
+ * The engine's view of the host store. The engine never owns the rendered
+ * value β€” the host does (a Zustand slice, a signal, a plain object) β€” it only
+ * reads entries through `read` and hands every transition to `commit`.
+ */
+export interface ReplicaStorePort<TData> {
+ /**
+ * Apply the view writes and the next bookkeeping slot as ONE host update, so
+ * subscribers never observe a view out of step with its bookkeeping.
+ */
+ commit: (writes: ReplicaViewWrite<TData>[], state: ReplicaState<TData>, label: string) => void;
+ /** Current bookkeeping slot. */
+ getState: () => ReplicaState<TData>;
+ /** Enumerate loaded keys (entity propagation). Defaults to the bookkeeping entries. */
+ keys?: () => string[];
+ /** Materialized value of one entry, as the UI sees it. */
+ read: (key: string) => TData | undefined;
+}
+
+/**
+ * How an entity (e.g. one topic) appears inside this resource's value. Paged
+ * resources get it for free from `paging.getId`; a single-entity resource
+ * (a detail cache) passes `getId`.
+ */
+export interface ReplicaEntityAdapter<TData, TItem> {
+ /** Map the entity value into the resource value; defaults to identity. */
+ apply?: (data: TData, item: TItem) => TData;
+ getId: (data: TData) => string;
+}
+
+export interface ReplicaEngineOptions<TParams, TData, TFetched> {
+ /** Label prefix of host updates (devtools action names). Defaults to the resource name. */
+ actionPrefix?: string;
+ /** Single-entity resources only: how to find / patch the entity. */
+ entity?: ReplicaEntityAdapter<TData, any>;
+ /** Overrides `resource.fetcher` when the fetch needs store context. */
+ fetcher?: (params: TParams, cursor?: any) => Promise<TFetched>;
+ /** Paged: rows that only exist client-side (kept across refreshes, never persisted). */
+ 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: fold a server response into the confirmed value. Return
+ * `undefined` to keep the current value. Defaults to "the response is the value".
+ */
+ merge?: (incoming: TFetched, confirmed: TData | undefined, params: TParams) => TData | undefined;
+ /** Where the engine reads and commits the view. */
+ port: ReplicaStorePort<TData>;
+ /** Re-run the network sync of one entry (or all); wired by the fetch adapter. */
+ revalidate?: (key?: string) => Promise<unknown>;
+ /** Strip transient / client-only parts before persisting; `undefined` skips. */
+ toPersisted?: (data: TData) => TData | undefined;
+ /** Paged: domain fields derived from params, written with every head page. */
+ viewFields?: (params: TParams) => Partial<TData>;
+}
+
+export interface OptimisticMutationOptions<TData, TResult> {
+ /** Turn the server result into the confirmed value; defaults to re-applying `apply`. */
+ confirm?: (result: TResult) => (data: TData) => TData;
+ /** Revalidate the entry after the server call settles. */
+ revalidate?: boolean;
+}
+
+/** Handle of an optimistic overlay that is settled later (see `beginOptimistic`). */
+export interface ReplicaOptimisticToken<TData> {
+ commit: (confirm?: (data: TData) => TData) => void;
+ rollback: () => void;
+}
+
+/**
+ * The replica engine: every transition of one resource, independent of any
+ * UI framework or state library.
+ *
+ * It owns hydrate-if-empty, server replace, pagination, optimistic overlays
+ * with commit/rollback, entity propagation, scope isolation and serialized
+ * persistence. The host store keeps the rendered value (see
+ * {@link ReplicaStorePort}); fetch scheduling (when to sync, dedupe, focus
+ * revalidation) belongs to an adapter such as `@lobechat/replica/zustand`.
+ */
+export const createReplicaEngine = <TParams, TData, TFetched = TData>(
+ resource: ReplicaResource<TParams, TData, TFetched>,
+ options: ReplicaEngineOptions<TParams, TData, TFetched>,
+) => {
+ const { port } = options;
+ const paging = resource.paging;
+ const pagingCtx: ReplicaPagingContext<any> = { isClientOnly: options.isClientOnly };
+ const prefix = options.actionPrefix ?? resource.name;
+ const writeQueue = resource.storage ? new ReplicaWriteQueue<TData>(resource.storage) : undefined;
+ const fetcher = options.fetcher ?? resource.fetcher;
+ let mutationSeq = 0;
+ /** Keys with a `loadMore` request in flight (the only valid `isLoadingMore`). */
+ const loadingMore = new Set<string>();
+
+ const getSlot = port.getState;
+ const storageKey = (key: string, query?: string) => ({
+ queryKey: replicaStorageKey(key, query),
+ });
+
+ const toPersisted = (data: TData): TData | undefined => {
+ const paged = paging ? (toPersistedPage(data as any, paging, pagingCtx) as TData) : data;
+ return options.toPersisted ? options.toPersisted(paged) : paged;
+ };
+
+ // ---- persisted-row index ---------------------------------------------
+ // Storage has no key listing, so each scope keeps an index row of the
+ // storage keys this resource persisted. Entity changes use it to patch rows
+ // whose entry is not loaded in memory (e.g. a status update for a list the
+ // user navigated away from), so a later visit never hydrates a stale value.
+ const indexKey = (scope: string) => ({ queryKey: REPLICA_INDEX_KEY, scope });
+ /** Keys known to be in the index row, per scope (skips redundant index writes). */
+ const indexed = new Map<string, Set<string>>();
+
+ const trackStorageKey = (scope: string, queryKey: string, present: boolean) => {
+ if (!writeQueue) return;
+ const known = indexed.get(scope) ?? new Set<string>();
+ indexed.set(scope, known);
+ if (known.has(queryKey) === present) return;
+ if (present) known.add(queryKey);
+ else known.delete(queryKey);
+ writeQueue.update(indexKey(scope), (current) => {
+ const keys = new Set((current?.data as unknown as string[] | undefined) ?? []);
+ if (keys.has(queryKey) === present) return undefined;
+ if (present) keys.add(queryKey);
+ else keys.delete(queryKey);
+ return { data: [...keys] as unknown as TData, updatedAt: Date.now() };
+ });
+ };
+
+ const readIndex = async (scope: string): Promise<string[]> => {
+ const row = await resource.storage?.get(indexKey(scope));
+ return (row?.data as unknown as string[] | undefined) ?? [];
+ };
+
+ const runEffects = (effects: ReplicaEffect<TData>[]) => {
+ if (!writeQueue || effects.length === 0) return;
+ // Until identity resolves the scope is a guess; never write into it.
+ if (!resource.scope.canPersist()) return;
+ for (const effect of effects) {
+ const key = { ...storageKey(effect.key, effect.query), scope: effect.scope };
+ if (effect.type === 'remove') {
+ writeQueue.remove(key);
+ trackStorageKey(effect.scope, key.queryKey, false);
+ continue;
+ }
+ const data = toPersisted(effect.data);
+ if (data === undefined) continue;
+ writeQueue.set(key, { data, updatedAt: Date.now() });
+ trackStorageKey(effect.scope, key.queryKey, true);
+ }
+ };
+
+ /** Read an entry as it will be once `writes` are applied (latest write wins). */
+ const readThrough = (writes: ReplicaViewWrite<TData>[], key: string): TData | undefined => {
+ for (let i = writes.length - 1; i >= 0; i--) {
+ const write = writes[i];
+ if ('type' in write) return undefined;
+ if (write.key === key) return write.data;
+ }
+ return port.read(key);
+ };
+
+ const dispatch = (action: ReplicaAction<TData>): boolean => {
+ const activeScope = resource.scope.get();
+ // An action captured under another identity is stale β€” drop it.
+ if (action.scope !== activeScope) return false;
+
+ const initial = getSlot();
+ let slot = initial;
+ const writes: ReplicaViewWrite<TData>[] = [];
+ const read = (key: string) => readThrough(writes, key);
+ if (slot.scope !== undefined && slot.scope !== activeScope) {
+ const reset = replicaReducer(slot, { scope: activeScope, type: 'resetScope' }, read);
+ writes.push(...reset.writes);
+ slot = reset.state;
+ }
+
+ const transition = replicaReducer(slot, action, read);
+ if (transition.state === slot && transition.writes.length === 0 && slot === initial)
+ return false;
+
+ writes.push(...transition.writes);
+ port.commit(writes, transition.state, `${prefix}/${action.type}`);
+ runEffects(transition.effects);
+ return true;
+ };
+
+ /**
+ * Drop memory owned by another identity as soon as a new scope is active β€”
+ * even when the new scope has nothing persisted and its fetch is slow, the
+ * previous user's / workspace's rows must not stay on screen.
+ */
+ const ensureScope = (scope: string) => {
+ if (scope === resource.scope.get() && getSlot().scope !== scope)
+ dispatch({ scope, type: 'resetScope' });
+ };
+
+ const getConfirmed = (key: string): TData | undefined => {
+ const entry = getSlot().entries[key];
+ return entry?.pending.length ? entry.base : port.read(key);
+ };
+
+ const hydrate = async (params: TParams, scope = resource.scope.get()) => {
+ if (!resource.storage) return false;
+ const key = resource.key(params);
+ const query = resource.query(params);
+ const cached = await resource.storage.get({ ...storageKey(key, query), scope });
+ if (!cached) return false;
+ if (options.isHydratable && !options.isHydratable(cached.data, params)) return false;
+ return dispatch({
+ data: cached.data,
+ key,
+ params,
+ query,
+ scope,
+ type: 'hydrate',
+ updatedAt: cached.updatedAt,
+ });
+ };
+
+ const viewMatchesFields = (current: TData | undefined, params: TParams) => {
+ const fields = options.viewFields?.(params);
+ if (!current || !fields) return true;
+ // Falsy descriptors (undefined / false / null) are equivalent.
+ const norm = (value: unknown) => stableQueryKey(value || null);
+ return Object.entries(fields).every(
+ ([field, value]) => norm(value) === norm((current as Record<string, unknown>)[field]),
+ );
+ };
+
+ const mergeHead = (
+ key: string,
+ incoming: TFetched,
+ confirmed: TData | undefined,
+ params: TParams,
+ reset: boolean,
+ ) => {
+ const page = incoming as unknown as ReplicaPageResult<unknown, unknown>;
+ const pageSize = (params as { pageSize?: number }).pageSize ?? page.items.length;
+ const merged = {
+ ...applyHeadPage(confirmed as any, page, { pageSize, reset }, paging!, pagingCtx),
+ ...options.viewFields?.(params),
+ isLoadingMore: loadingMore.has(key),
+ };
+ // Keep domain-only fields of the current view (e.g. transient flags).
+ const next = { ...(confirmed as object), ...merged } as TData;
+ return confirmed !== undefined && isEqual(next, confirmed) ? undefined : next;
+ };
+
+ const replace = (params: TParams, incoming: TFetched, scope = resource.scope.get()) => {
+ const key = resource.key(params);
+ const query = resource.query(params);
+ const entry = getSlot().entries[key];
+ // A different query (filters, sort) must not merge with loaded pages. A
+ // view seeded without bookkeeping is compared by its `viewFields`.
+ const reset = entry
+ ? entry.query !== query
+ : paging !== undefined && !viewMatchesFields(port.read(key), params);
+ return dispatch({
+ data: (confirmed) =>
+ paging
+ ? mergeHead(key, incoming, confirmed, params, reset)
+ : options.merge
+ ? options.merge(incoming, confirmed, params)
+ : (incoming as unknown as TData),
+ key,
+ params,
+ query,
+ scope,
+ type: 'replace',
+ });
+ };
+
+ /** Confirmed local write: patches the view (and the base under any overlay). */
+ const update = (
+ key: string,
+ apply: (data: TData | undefined) => TData | undefined,
+ { 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' });
+
+ const revalidate = (key?: string): Promise<unknown> =>
+ options.revalidate ? options.revalidate(key) : Promise.resolve();
+
+ /** Start an optimistic overlay now and settle it later (multi-resource flows). */
+ const beginOptimistic = (
+ key: string,
+ apply: (data: TData) => TData,
+ ): ReplicaOptimisticToken<TData> => {
+ const scope = resource.scope.get();
+ const id = ++mutationSeq;
+ dispatch({ apply, id, key, scope, type: 'optimistic' });
+ return {
+ commit: (confirm) => {
+ dispatch({ confirm, id, key, scope, type: 'commit' });
+ },
+ rollback: () => {
+ dispatch({ id, key, scope, type: 'rollback' });
+ },
+ };
+ };
+
+ /**
+ * Apply `apply` to the view right away, run `serverCall`, then commit (the
+ * confirmed value is persisted) or roll back (the view is rebuilt from the
+ * confirmed base plus any other in-flight overlays) and rethrow.
+ */
+ const optimistic = async <TResult>(
+ key: string,
+ apply: (data: TData) => TData,
+ serverCall: () => Promise<TResult>,
+ mutationOptions: OptimisticMutationOptions<TData, TResult> = {},
+ ): Promise<TResult> => {
+ const token = beginOptimistic(key, apply);
+ try {
+ const result = await serverCall();
+ token.commit(mutationOptions.confirm?.(result));
+ return result;
+ } catch (error) {
+ token.rollback();
+ throw error;
+ } finally {
+ if (mutationOptions.revalidate) void revalidate(key);
+ }
+ };
+
+ // ---- pagination --------------------------------------------------------
+
+ /**
+ * Fetch and merge the next page with the params of the loaded head page
+ * (`fallbackParams` covers views seeded outside `useSync`). In `cursor` mode
+ * paging only starts from a server-confirmed head page: a hydrated cursor
+ * may be stale. A result is dropped when the scope, the query or the loaded
+ * depth changed while it was in flight.
+ */
+ const loadMore = async (key: string, fallbackParams?: TParams): Promise<void> => {
+ if (!paging || !fetcher) return;
+ const entry = getSlot().entries[key];
+ const current = port.read(key) as ReplicaPagedData<unknown, unknown> | undefined;
+ if (!current || loadingMore.has(key)) return;
+ if (paging.mode === 'cursor' && entry?.source === 'storage') return;
+ const params = (entry?.params ?? fallbackParams) as TParams | undefined;
+ if (params === undefined) return;
+ const cursor = getNextPageCursor(current, paging);
+ if (cursor === null || cursor === undefined) return;
+
+ const query = entry?.query;
+ const scope = resource.scope.get();
+ const depth = current.currentPage;
+ const setLoading = (patch: object) =>
+ update(key, (data) => data && ({ ...data, ...patch } as TData), { persist: false });
+
+ loadingMore.add(key);
+ setLoading({ isLoadingMore: true, loadMoreError: undefined });
+ const isCurrent = () => {
+ const latest = port.read(key) as ReplicaPagedData<unknown, unknown> | undefined;
+ return (
+ resource.scope.get() === scope &&
+ getSlot().entries[key]?.query === query &&
+ latest?.currentPage === depth
+ );
+ };
+ try {
+ const page = (await fetcher(params, cursor)) as unknown as ReplicaPageResult<
+ unknown,
+ unknown
+ >;
+ if (!isCurrent()) return void setLoading({ isLoadingMore: false });
+ update(
+ key,
+ (data) => data && (applyNextPage(data as any, page, paging, pagingCtx) as TData),
+ { persist: (paging.persist?.pages ?? 1) > 1 },
+ );
+ } catch (error) {
+ setLoading({ isLoadingMore: false, loadMoreError: isCurrent() ? error : undefined });
+ } finally {
+ loadingMore.delete(key);
+ }
+ };
+
+ /** Insert rows at the head (new / streamed items). */
+ const insertHead = <TItem>(key: string, items: TItem[], { persist = false } = {}) =>
+ paging
+ ? update(key, (data) => data && (insertHeadItems(data as any, items, paging) as TData), {
+ persist,
+ })
+ : false;
+
+ /** Drop loaded pages, keeping the head (e.g. after an edit inside older pages). */
+ const collapse = (key: string) =>
+ paging
+ ? update(key, (data) => data && (collapseToHead(data as any, paging) as TData), {
+ persist: false,
+ })
+ : false;
+
+ // ---- entity propagation -----------------------------------------------
+
+ const entityKeys = (id: string): string[] => {
+ const keys = port.keys?.() ?? Object.keys(getSlot().entries);
+ return keys.filter((key) => {
+ const data = port.read(key);
+ if (data === undefined) return false;
+ if (paging) return hasPagedItem(data as any, id, paging);
+ return options.entity ? options.entity.getId(data) === id : false;
+ });
+ };
+
+ /** Map one entity inside a value; `undefined` from `fn` removes it (paged only). */
+ const mapEntity = <TItem>(
+ data: TData,
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ ): TData | undefined => {
+ if (paging) return mapPagedItem(data as any, id, fn as any, paging) as TData;
+ const entity = options.entity;
+ if (!entity || entity.getId(data) !== id) return data;
+ const next = fn(data as unknown as TItem);
+ if (next === undefined) return undefined;
+ return entity.apply ? entity.apply(data, next) : (next as unknown as TData);
+ };
+
+ /**
+ * Apply an entity change to persisted rows that memory does not hold (the
+ * memory path already persists loaded entries). Read-modify-write runs in
+ * the per-key write queue, so it sees every earlier write; a missing row is
+ * never recreated. Resolves once the index has been read and the patches
+ * are queued.
+ */
+ const patchStoredEntity = async <TItem>(
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ ): Promise<void> => {
+ if (!writeQueue || !resource.scope.canPersist()) return;
+ const scope = resource.scope.get();
+ const slot = getSlot();
+ const loaded = new Set(
+ slot.scope === scope
+ ? Object.entries(slot.entries).map(([key, entry]) => storageKey(key, entry.query).queryKey)
+ : [],
+ );
+ const keys = await readIndex(scope);
+ // Identity changed while reading the index: those rows are not ours to touch.
+ if (resource.scope.get() !== scope) return;
+ for (const queryKey of keys) {
+ if (loaded.has(queryKey)) continue;
+ writeQueue.update({ queryKey, scope }, (current) => {
+ if (!current) return undefined;
+ const next = mapEntity(current.data, id, fn);
+ if (next === current.data) return undefined;
+ if (next === undefined) {
+ trackStorageKey(scope, queryKey, false);
+ return null;
+ }
+ return { data: next, updatedAt: Date.now() };
+ });
+ }
+ };
+
+ const updateEntity = <TItem>(
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ { persist = true }: { persist?: boolean } = {},
+ ) => {
+ if (persist) void patchStoredEntity(id, fn);
+ for (const key of entityKeys(id)) {
+ const current = port.read(key);
+ if (current === undefined) continue;
+ const next = mapEntity(current, id, fn);
+ if (next === undefined) remove(key);
+ else
+ update(key, (data) => (data === undefined ? data : (mapEntity(data, id, fn) ?? data)), {
+ persist,
+ });
+ }
+ };
+
+ const beginEntityOptimistic = <TItem>(
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ ): ReplicaOptimisticToken<TData>[] =>
+ entityKeys(id).flatMap((key) => {
+ // Removing a single-entity value is applied on commit, not optimistically.
+ if (!paging) {
+ const current = port.read(key);
+ if (current !== undefined && mapEntity(current, id, fn) === undefined) return [];
+ }
+ return [beginOptimistic(key, (data) => mapEntity(data, id, fn) ?? data)];
+ });
+
+ return {
+ beginEntityOptimistic,
+ beginOptimistic,
+ collapse,
+ dispatch,
+ ensureScope,
+ entityKeys,
+ fetcher,
+ getConfirmed,
+ hydrate,
+ insertHead,
+ loadMore,
+ optimistic,
+ patchStoredEntity,
+ remove,
+ replace,
+ resource,
+ revalidate,
+ update,
+ updateEntity,
+ };
+};
+
+export type ReplicaEngine<TParams, TData, TFetched = TData> = ReturnType<
+ typeof createReplicaEngine<TParams, TData, TFetched>
+>;
diff --git a/packages/replica/src/core/entity.ts b/packages/replica/src/core/entity.ts
new file mode 100644
index 00000000000..56b2addb31f
--- /dev/null
+++ b/packages/replica/src/core/entity.ts
@@ -0,0 +1,74 @@
+import type { ReplicaOptimisticToken } from './engine';
+
+/** The part of a slice entity propagation needs (structural, so any slice fits). */
+export interface ReplicaEntityTarget {
+ beginEntityOptimistic: <TItem>(
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ ) => ReplicaOptimisticToken<any>[];
+ /** Patch persisted rows whose entry is not loaded in memory. */
+ patchStoredEntity: <TItem>(id: string, fn: (item: TItem) => TItem | undefined) => Promise<void>;
+ revalidate: (key?: string) => Promise<unknown>;
+ updateEntity: <TItem>(
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ options?: { persist?: boolean },
+ ) => void;
+}
+
+/**
+ * Link resources that hold copies of the same entity (e.g. a topic in the
+ * sidebar list, the management page and the detail cache).
+ *
+ * Each resource keeps exactly one store location and decides how the entity
+ * maps into its own shape (paged resources by `getId`, single-entity ones by
+ * their entity adapter). The link only fans an entity-level change out to the
+ * resources that currently hold it β€” no global event bus, no shared owner.
+ */
+export const linkReplicaEntity = <TItem>(targets: ReplicaEntityTarget[]) => {
+ /**
+ * Confirmed patch everywhere the entity is loaded, and (when persisted, the
+ * default) in persisted rows of entries that are not loaded.
+ */
+ const update = (
+ id: string,
+ fn: (item: TItem) => TItem,
+ options?: { persist?: boolean },
+ ): void => {
+ for (const target of targets) target.updateEntity<TItem>(id, fn, options);
+ };
+
+ /** Confirmed removal everywhere (list rows dropped, single-entity values removed). */
+ const remove = (id: string, options?: { persist?: boolean }): void => {
+ for (const target of targets) target.updateEntity<TItem>(id, () => undefined, options);
+ };
+
+ /**
+ * One server call, one overlay per resource holding the entity: all commit
+ * together or all roll back together (then rethrow). Pass `'remove'` for an
+ * optimistic delete.
+ */
+ const optimistic = async <TResult>(
+ id: string,
+ fn: ((item: TItem) => TItem) | 'remove',
+ serverCall: () => Promise<TResult>,
+ ): Promise<TResult> => {
+ const apply = fn === 'remove' ? () => undefined : fn;
+ const tokens = targets.flatMap((target) => target.beginEntityOptimistic<TItem>(id, apply));
+ try {
+ const result = await serverCall();
+ for (const token of tokens) token.commit();
+ // `remove` / `update` also patch persisted rows that are not loaded.
+ if (fn === 'remove') remove(id);
+ else for (const target of targets) void target.patchStoredEntity<TItem>(id, fn);
+ return result;
+ } catch (error) {
+ for (const token of tokens) token.rollback();
+ throw error;
+ }
+ };
+
+ const revalidate = () => Promise.all(targets.map((target) => target.revalidate()));
+
+ return { optimistic, remove, revalidate, update };
+};
diff --git a/packages/replica/src/core/keys.ts b/packages/replica/src/core/keys.ts
new file mode 100644
index 00000000000..4fb3b00e068
--- /dev/null
+++ b/packages/replica/src/core/keys.ts
@@ -0,0 +1,27 @@
+/**
+ * Keys of the queries a fetch adapter runs for a replica. Hosts that sweep
+ * their query cache by prefix (e.g. "refetch everything after a restore")
+ * match on {@link REPLICA_KEY_PREFIX}.
+ */
+export const REPLICA_KEY_PREFIX = 'replica:';
+
+export const replicaKeys = {
+ /** One-shot read of the persisted row for `storageKey`. */
+ hydrate: (name: string, version: number, scope: string, storageKey: string) =>
+ ['replica:hydrate', name, version, scope, storageKey] as const,
+ /** Network sync of the head of one entry. */
+ sync: (name: string, version: number, scope: string, key: string, params: unknown) =>
+ ['replica:sync', name, version, scope, key, params] as const,
+};
+
+/** Match a resource's sync keys, optionally narrowed to one scope and/or entry key. */
+export const isReplicaSyncKey = (
+ queryKey: unknown,
+ name: string,
+ filter: { key?: string; scope?: string } = {},
+): boolean =>
+ Array.isArray(queryKey) &&
+ queryKey[0] === 'replica:sync' &&
+ queryKey[1] === name &&
+ (filter.scope === undefined || queryKey[3] === filter.scope) &&
+ (filter.key === undefined || queryKey[4] === filter.key);
diff --git a/packages/replica/src/core/paging.test.ts b/packages/replica/src/core/paging.test.ts
new file mode 100644
index 00000000000..df5f67a0126
--- /dev/null
+++ b/packages/replica/src/core/paging.test.ts
@@ -0,0 +1,288 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ applyHeadPage,
+ applyNextPage,
+ collapseToHead,
+ getNextPageCursor,
+ insertHeadItems,
+ mapPagedItem,
+ type ReplicaPagedData,
+ type ReplicaPagingConfig,
+ toPersistedPage,
+} from './paging';
+
+interface Row {
+ id: string;
+ title?: string;
+}
+
+const rows = (...ids: string[]): Row[] => ids.map((id) => ({ id }));
+const ids = (data: { items: Row[] }) => data.items.map((item) => item.id);
+
+const offset: ReplicaPagingConfig<Row> = {
+ direction: 'forward',
+ getId: (row) => row.id,
+ mode: 'offset',
+};
+
+describe('offset / forward paging (topic-like list)', () => {
+ const twoPages = () => {
+ const head = applyHeadPage(
+ undefined,
+ { items: rows('a', 'b'), total: 5 },
+ { pageSize: 2 },
+ offset,
+ );
+ return applyNextPage(head, { items: rows('c', 'd'), total: 5 }, offset);
+ };
+
+ it('merges the next page and dedupes by id', () => {
+ const head = applyHeadPage(
+ undefined,
+ { items: rows('a', 'b'), total: 5 },
+ { pageSize: 2 },
+ offset,
+ );
+ expect(head).toMatchObject({ currentPage: 0, hasMore: true, nextCursor: 1 });
+
+ // A row shifted from page 0 into page 1 (offset drift) is not duplicated.
+ const next = applyNextPage(head, { items: rows('b', 'c'), total: 5 }, offset);
+ expect(ids(next)).toEqual(['a', 'b', 'c']);
+ expect(next).toMatchObject({ currentPage: 1, isLoadingMore: false, nextCursor: 2 });
+ });
+
+ it('a head refresh keeps the loaded depth and dedupes by id', () => {
+ const refreshed = applyHeadPage(
+ twoPages(),
+ { items: rows('new', 'a'), total: 6 },
+ { pageSize: 2 },
+ offset,
+ );
+ expect(ids(refreshed)).toEqual(['new', 'a', 'b', 'c']);
+ expect(refreshed.currentPage).toBe(1);
+ expect(refreshed.hasMore).toBe(true);
+ });
+
+ it('a query reset or a page-size change collapses to the head page', () => {
+ const reset = applyHeadPage(
+ twoPages(),
+ { items: rows('x'), total: 1 },
+ { pageSize: 2, reset: true },
+ offset,
+ );
+ expect(ids(reset)).toEqual(['x']);
+ expect(reset).toMatchObject({ currentPage: 0, hasMore: false, nextCursor: null });
+
+ const resized = applyHeadPage(
+ twoPages(),
+ { items: rows('a', 'b', 'c'), total: 5 },
+ { pageSize: 3 },
+ offset,
+ );
+ expect(resized.currentPage).toBe(0);
+ });
+
+ it('a head refresh clears the last page error', () => {
+ const failed = { ...twoPages(), loadMoreError: new Error('boom') };
+ const refreshed = applyHeadPage(
+ failed,
+ { items: rows('a', 'b'), total: 5 },
+ { pageSize: 2 },
+ offset,
+ );
+ expect(refreshed.loadMoreError).toBeUndefined();
+ });
+
+ it('keeps client-only rows across head refreshes', () => {
+ const ctx = { isClientOnly: (row: Row) => row.id === 'tmp' };
+ const withTmp = insertHeadItems(twoPages(), rows('tmp'), offset);
+ const refreshed = applyHeadPage(
+ withTmp,
+ { items: rows('a', 'b'), total: 5 },
+ { pageSize: 2 },
+ offset,
+ ctx,
+ );
+ expect(ids(refreshed)).toEqual(['tmp', 'a', 'b', 'c', 'd']);
+
+ // Once the server returns the row it is no longer duplicated.
+ const confirmed = applyHeadPage(
+ refreshed,
+ { items: rows('tmp', 'a'), total: 6 },
+ { pageSize: 2 },
+ offset,
+ ctx,
+ );
+ expect(ids(confirmed).filter((id) => id === 'tmp')).toHaveLength(1);
+ });
+
+ it('inserts new rows at the head without moving the cursor', () => {
+ const data = twoPages();
+ const inserted = insertHeadItems(data, rows('n1', 'a'), offset);
+ expect(ids(inserted)).toEqual(['n1', 'a', 'b', 'c', 'd']);
+ expect(inserted.nextCursor).toBe(data.nextCursor);
+ expect(inserted.total).toBe(6);
+ expect(inserted.pages?.[0].count).toBe(3);
+ });
+
+ it('patches and removes a row by id', () => {
+ const data = twoPages();
+ const renamed = mapPagedItem(data, 'c', (row) => ({ ...row, title: 'C' }), offset);
+ expect(renamed.items[2]).toEqual({ id: 'c', title: 'C' });
+ expect(mapPagedItem(data, 'missing', () => undefined, offset)).toBe(data);
+
+ const removed = mapPagedItem(data, 'c', () => undefined, offset);
+ expect(ids(removed)).toEqual(['a', 'b', 'd']);
+ expect(removed.total).toBe(4);
+ });
+
+ it('derives the offset cursor for views without bookkeeping', () => {
+ const legacy = { currentPage: 1, hasMore: true, items: rows('a'), pageSize: 1 };
+ expect(getNextPageCursor(legacy, offset)).toBe(2);
+ expect(getNextPageCursor({ ...legacy, hasMore: false }, offset)).toBeNull();
+ });
+
+ describe('persistence limits', () => {
+ it('persists the head page only by default, without flags or client-only rows', () => {
+ const data = { ...insertHeadItems(twoPages(), rows('tmp'), offset), isLoadingMore: true };
+ const persisted = toPersistedPage(data, offset, { isClientOnly: (row) => row.id === 'tmp' });
+ expect(ids(persisted)).toEqual(['a', 'b']);
+ expect(persisted).toMatchObject({ currentPage: 0, hasMore: true, nextCursor: 1 });
+ expect(persisted).not.toHaveProperty('isLoadingMore');
+ });
+
+ it('honours persist.pages and persist.maxItems', () => {
+ const threePages = applyNextPage(twoPages(), { items: rows('e'), total: 5 }, offset);
+ const pages = toPersistedPage(threePages, { ...offset, persist: { pages: 2 } });
+ expect(ids(pages)).toEqual(['a', 'b', 'c', 'd']);
+ expect(pages).toMatchObject({ currentPage: 1, nextCursor: 2 });
+
+ // maxItems cuts at a page boundary so the persisted offset stays valid.
+ const capped = toPersistedPage(threePages, { ...offset, persist: { maxItems: 3, pages: 3 } });
+ expect(ids(capped)).toEqual(['a', 'b']);
+ expect(capped.currentPage).toBe(0);
+ });
+ });
+});
+
+/**
+ * Message-like fixture: transcript ascending by createdAt (newest last),
+ * "load older" prepends, the server cursor is `{ createdAt, id }` and `null`
+ * marks the topic start β€” mirrors `getMessagesByCursor` / `olderCursor`.
+ */
+describe('cursor / backward paging (message-like transcript)', () => {
+ interface Message {
+ createdAt: number;
+ id: string;
+ }
+ interface Cursor {
+ createdAt: number;
+ id: string;
+ }
+ const msg = (n: number): Message => ({ createdAt: n, id: `m${n}` });
+ const range = (from: number, to: number) =>
+ Array.from({ length: to - from + 1 }, (_, i) => msg(from + i));
+ const cursorOf = (m: Message): Cursor => ({ createdAt: m.createdAt, id: m.id });
+ const messages: ReplicaPagingConfig<Message> = {
+ direction: 'backward',
+ getId: (m) => m.id,
+ mode: 'cursor',
+ persist: { maxItems: 100 },
+ sort: (a, b) => a.createdAt - b.createdAt,
+ };
+ const mids = (data: ReplicaPagedData<Message, Cursor>) => data.items.map((m) => m.id);
+
+ const loadedTwoWindows = () => {
+ const head = applyHeadPage<Message, Cursor>(
+ undefined,
+ { items: range(7, 10), nextCursor: cursorOf(msg(7)) },
+ { pageSize: 4 },
+ messages,
+ );
+ return applyNextPage(head, { items: range(3, 6), nextCursor: cursorOf(msg(3)) }, messages);
+ };
+
+ it('prepends older history and pins the join anchor', () => {
+ const data = loadedTwoWindows();
+ expect(mids(data)).toEqual(['m3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10']);
+ expect(data.anchorId).toBe('m7');
+ expect(data.nextCursor).toEqual({ createdAt: 3, id: 'm3' });
+ });
+
+ it('marks the topic start on a null cursor or an empty page', () => {
+ const exhausted = applyNextPage(
+ loadedTwoWindows(),
+ { items: range(1, 2), nextCursor: null },
+ messages,
+ );
+ expect(exhausted.hasMore).toBe(false);
+ const empty = applyNextPage(
+ loadedTwoWindows(),
+ { items: [], nextCursor: cursorOf(msg(3)) },
+ messages,
+ );
+ expect(empty.nextCursor).toBeNull();
+ });
+
+ it('streamed messages land at the newest end without breaking the older cursor', () => {
+ const data = insertHeadItems(loadedTwoWindows(), [msg(11)], messages);
+ expect(mids(data).at(-1)).toBe('m11');
+ expect(data.nextCursor).toEqual({ createdAt: 3, id: 'm3' });
+ });
+
+ it('keeps older pages when the refreshed window still contains the anchor', () => {
+ const refreshed = applyHeadPage(
+ loadedTwoWindows(),
+ { items: range(7, 11), nextCursor: cursorOf(msg(7)) },
+ { pageSize: 4 },
+ messages,
+ );
+ expect(mids(refreshed)).toEqual(range(3, 11).map((m) => m.id));
+ expect(refreshed.nextCursor).toEqual({ createdAt: 3, id: 'm3' });
+ });
+
+ it('collapses to the fresh window when it slid past the anchor (gap)', () => {
+ const refreshed = applyHeadPage(
+ loadedTwoWindows(),
+ { items: range(9, 12), nextCursor: cursorOf(msg(9)) },
+ { pageSize: 4 },
+ messages,
+ );
+ expect(mids(refreshed)).toEqual(['m9', 'm10', 'm11', 'm12']);
+ expect(refreshed.currentPage).toBe(0);
+ expect(refreshed.nextCursor).toEqual({ createdAt: 9, id: 'm9' });
+ });
+
+ it('keeps optimistic (tmp) messages at the newest end across refreshes', () => {
+ const ctx = { isClientOnly: (m: Message) => m.id.startsWith('tmp') };
+ const withTmp = insertHeadItems(loadedTwoWindows(), [{ createdAt: 99, id: 'tmp_1' }], messages);
+ const refreshed = applyHeadPage(
+ withTmp,
+ { items: range(7, 10), nextCursor: cursorOf(msg(7)) },
+ { pageSize: 4 },
+ messages,
+ ctx,
+ );
+ expect(mids(refreshed).at(-1)).toBe('tmp_1');
+ expect(toPersistedPage(refreshed, messages, ctx).items.some((m) => m.id === 'tmp_1')).toBe(
+ false,
+ );
+ });
+
+ it('collapse after an edit in older history keeps the newest window and its cursor', () => {
+ const collapsed = collapseToHead(loadedTwoWindows(), messages);
+ expect(mids(collapsed)).toEqual(['m7', 'm8', 'm9', 'm10']);
+ expect(collapsed.nextCursor).toEqual({ createdAt: 7, id: 'm7' });
+ });
+
+ it('persists the newest window, capped by maxItems; a cut forgets the cursor', () => {
+ const persisted = toPersistedPage(loadedTwoWindows(), messages);
+ expect(mids(persisted)).toEqual(['m7', 'm8', 'm9', 'm10']);
+ expect(persisted.nextCursor).toEqual({ createdAt: 7, id: 'm7' });
+
+ const capped = toPersistedPage(loadedTwoWindows(), { ...messages, persist: { maxItems: 2 } });
+ expect(mids(capped)).toEqual(['m9', 'm10']);
+ expect(capped.nextCursor).toBeUndefined();
+ });
+});
diff --git a/packages/replica/src/core/paging.ts b/packages/replica/src/core/paging.ts
new file mode 100644
index 00000000000..ed59eca8e9b
--- /dev/null
+++ b/packages/replica/src/core/paging.ts
@@ -0,0 +1,439 @@
+/**
+ * First-class pagination for replicas.
+ *
+ * Vocabulary (direction-agnostic):
+ * - HEAD page: the newest window, what a refresh re-fetches (`cursor` undefined).
+ * - NEXT pages: further pages in the paging direction (older history).
+ * - `forward`: the view is head-first, next pages append at the END
+ * (sidebar lists: newest topic first, "load more" below).
+ * - `backward`: the view is oldest-first, next pages PREPEND at the start
+ * (chat transcripts: newest message last, "load older" on scroll-up).
+ * - `offset` mode: the cursor is the page index (0 = head).
+ * `cursor` mode: the server hands back an opaque `nextCursor`.
+ *
+ * Every function is pure; the store binding owns staleness and scope.
+ */
+
+export type ReplicaPagingMode = 'cursor' | 'offset';
+export type ReplicaPagingDirection = 'backward' | 'forward';
+
+export interface ReplicaPagingConfig<TItem> {
+ direction: ReplicaPagingDirection;
+ getId: (item: TItem) => string;
+ mode: ReplicaPagingMode;
+ /** Which part survives a reload. Defaults to the head page only. */
+ persist?: {
+ /** Hard cap on persisted items (taken from the head side). */
+ maxItems?: number;
+ /** Number of pages from the head side. Default 1. */
+ pages?: number;
+ };
+ /** Optional total order re-applied after every merge (e.g. messages by createdAt). */
+ sort?: (a: TItem, b: TItem) => number;
+}
+
+export interface ReplicaPageResult<TItem, TCursor> {
+ items: TItem[];
+ /** Cursor mode: next page cursor; `null` = exhausted, `undefined` = unknown. */
+ nextCursor?: TCursor | null;
+ total?: number;
+}
+
+export interface ReplicaPageInfo<TCursor> {
+ /** Items this page contributed after de-duplication. */
+ count: number;
+ /** Cursor of the page after this one; `null` = exhausted, `undefined` = unknown. */
+ next?: TCursor | null;
+}
+
+/**
+ * The paged view a resource keeps in the store. Domain views extend it, so
+ * selectors read `items` / `hasMore` / `isLoadingMore` as before.
+ */
+export interface ReplicaPagedData<TItem, TCursor = number> {
+ /**
+ * Boundary row of the head page once more pages are loaded (forward: its
+ * last row, backward: its first row). A refreshed head page that no longer
+ * contains it has slid past the loaded pages β€” merging would hide a gap.
+ */
+ anchorId?: string;
+ /** Index of the last merged page (0 = head only). */
+ currentPage: number;
+ hasMore: boolean;
+ isLoadingMore?: boolean;
+ items: TItem[];
+ loadMoreError?: unknown;
+ /** Cursor for the next page (offset: page index). `null` = exhausted. */
+ nextCursor?: TCursor | null;
+ /** Per-page bookkeeping, head first. Missing on legacy data = one page. */
+ pages?: ReplicaPageInfo<TCursor>[];
+ pageSize: number;
+ total?: number;
+}
+
+export interface ReplicaPagingContext<TItem> {
+ /**
+ * Client-only rows (optimistic inserts whose server row may not exist yet).
+ * They survive head refreshes and are never persisted.
+ */
+ isClientOnly?: (item: TItem) => boolean;
+}
+
+const dedupe = <TItem>(
+ items: TItem[],
+ getId: (item: TItem) => string,
+ seen = new Set<string>(),
+) => {
+ const out: TItem[] = [];
+ for (const item of items) {
+ const id = getId(item);
+ if (seen.has(id)) continue;
+ seen.add(id);
+ out.push(item);
+ }
+ return out;
+};
+
+const ordered = <TItem>(items: TItem[], config: ReplicaPagingConfig<TItem>) =>
+ config.sort ? [...items].sort(config.sort) : items;
+
+/** Concatenate in view order: forward = head first, backward = head last. */
+const join = <TItem>(head: TItem[], rest: TItem[], direction: ReplicaPagingDirection) =>
+ direction === 'forward' ? [...head, ...rest] : [...rest, ...head];
+
+const deriveHasMore = <TItem, TCursor>(
+ data: Pick<ReplicaPagedData<TItem, TCursor>, 'items' | 'nextCursor' | 'total'>,
+ serverCount: number,
+) => (data.total !== undefined ? data.total > serverCount : data.nextCursor !== null);
+
+const offsetNext = (more: boolean, nextIndex: number) => (more ? nextIndex : null);
+
+/**
+ * Cursor to request the next page with; `null` β†’ exhausted, `undefined` β†’
+ * cannot page yet. Offset views without bookkeeping (seeded by legacy code or
+ * an older persisted shape) derive it from `currentPage` / `hasMore`.
+ */
+export const getNextPageCursor = <TItem, TCursor>(
+ data: ReplicaPagedData<TItem, TCursor> | undefined,
+ config: Pick<ReplicaPagingConfig<TItem>, 'mode'>,
+): TCursor | null | undefined => {
+ if (!data) return undefined;
+ if (data.nextCursor !== undefined || config.mode !== 'offset') return data.nextCursor;
+ return (data.hasMore ? (data.currentPage ?? 0) + 1 : null) as TCursor | null;
+};
+
+const splitClientOnly = <TItem>(items: TItem[], ctx: ReplicaPagingContext<TItem>) => {
+ if (!ctx.isClientOnly) return { clientOnly: [] as TItem[], server: items };
+ const clientOnly: TItem[] = [];
+ const server: TItem[] = [];
+ for (const item of items) (ctx.isClientOnly(item) ? clientOnly : server).push(item);
+ return { clientOnly, server };
+};
+
+/**
+ * Fold a fresh HEAD page into the view.
+ *
+ * - First load, a query change (`reset`) or an unextended view β†’ the head page.
+ * - Extended view, `offset` mode β†’ keep the loaded depth: fresh head first,
+ * then previously loaded rows not in it (shifted offsets self-heal by id).
+ * - Extended view, `cursor` mode β†’ keep older pages only when the fresh head
+ * still contains the join anchor and the next cursor is known; otherwise
+ * collapse to the head page (never show a hidden gap).
+ *
+ * Client-only rows still in the view are kept on the head side.
+ */
+export const applyHeadPage = <TItem, TCursor>(
+ current: ReplicaPagedData<TItem, TCursor> | undefined,
+ page: ReplicaPageResult<TItem, TCursor>,
+ options: { pageSize: number; reset?: boolean },
+ config: ReplicaPagingConfig<TItem>,
+ ctx: ReplicaPagingContext<TItem> = {},
+): ReplicaPagedData<TItem, TCursor> => {
+ const { getId, direction } = config;
+ const fresh = dedupe(page.items, getId);
+ const freshIds = new Set(fresh.map(getId));
+ const { clientOnly, server: currentServer } = splitClientOnly(current?.items ?? [], ctx);
+ const survivors = clientOnly.filter((item) => !freshIds.has(getId(item)));
+ const total = page.total ?? (options.reset ? undefined : current?.total);
+ // Client-only rows are the newest: they sit at the very head of the view.
+ const headItems = direction === 'forward' ? [...survivors, ...fresh] : [...fresh, ...survivors];
+
+ const headOnly = (): ReplicaPagedData<TItem, TCursor> => {
+ const nextCursor =
+ config.mode === 'offset'
+ ? (offsetNext(
+ total !== undefined ? total > fresh.length : fresh.length >= options.pageSize,
+ 1,
+ ) as TCursor | null)
+ : page.nextCursor;
+ const data = {
+ anchorId: undefined,
+ currentPage: 0,
+ items: ordered(headItems, config),
+ nextCursor,
+ pageSize: options.pageSize,
+ pages: [{ count: fresh.length, next: nextCursor }],
+ total,
+ };
+ return {
+ ...data,
+ hasMore: deriveHasMore(data, fresh.length),
+ isLoadingMore: current?.isLoadingMore,
+ // A fresh head page supersedes the last page failure.
+ loadMoreError: undefined,
+ };
+ };
+
+ const extended = !!current && current.currentPage > 0 && !options.reset;
+ if (!extended || current.pageSize !== options.pageSize) return headOnly();
+
+ let rest: TItem[];
+ let anchorId: string | undefined;
+ if (config.mode === 'offset') {
+ const restCandidates = currentServer.filter((item) => !freshIds.has(getId(item)));
+ // Keep the depth the user scrolled to, bounded by what still exists.
+ const visible = Math.min(currentServer.length, total ?? Number.POSITIVE_INFINITY);
+ const keep = Math.max(0, visible - fresh.length);
+ rest =
+ direction === 'forward'
+ ? restCandidates.slice(0, keep)
+ : restCandidates.slice(Math.max(0, restCandidates.length - keep));
+ } else {
+ const anchorIndex = current.anchorId
+ ? currentServer.findIndex((item) => getId(item) === current.anchorId)
+ : -1;
+ if (anchorIndex === -1 || !freshIds.has(current.anchorId!) || current.nextCursor === undefined)
+ return headOnly();
+ const farSide =
+ direction === 'forward'
+ ? currentServer.slice(anchorIndex + 1)
+ : currentServer.slice(0, anchorIndex);
+ rest = farSide.filter((item) => !freshIds.has(getId(item)));
+ const boundary = direction === 'forward' ? fresh.at(-1) : fresh[0];
+ anchorId = boundary ? getId(boundary) : current.anchorId;
+ }
+
+ const pages = current.pages?.length
+ ? [{ ...current.pages[0], count: fresh.length }, ...current.pages.slice(1)]
+ : [{ count: fresh.length, next: current.nextCursor }];
+ const data = {
+ anchorId: anchorId ?? current.anchorId,
+ currentPage: current.currentPage,
+ items: ordered(join(headItems, rest, direction), config),
+ nextCursor: current.nextCursor,
+ pageSize: options.pageSize,
+ pages,
+ total,
+ };
+ return {
+ ...data,
+ hasMore: deriveHasMore(data, fresh.length + rest.length),
+ isLoadingMore: current.isLoadingMore,
+ loadMoreError: undefined,
+ };
+};
+
+/** Merge the NEXT page (fetched with `getNextPageCursor`) into the view. */
+export const applyNextPage = <TItem, TCursor>(
+ current: ReplicaPagedData<TItem, TCursor>,
+ page: ReplicaPageResult<TItem, TCursor>,
+ config: ReplicaPagingConfig<TItem>,
+ ctx: ReplicaPagingContext<TItem> = {},
+): ReplicaPagedData<TItem, TCursor> => {
+ const { getId, direction } = config;
+ const seen = new Set(current.items.map(getId));
+ const added = dedupe(page.items, getId, seen);
+ const total = page.total ?? current.total;
+ const serverCount = splitClientOnly(current.items, ctx).server.length + added.length;
+
+ let next: TCursor | null | undefined;
+ if (config.mode === 'offset') {
+ const more = total !== undefined ? total > serverCount : page.items.length >= current.pageSize;
+ next = offsetNext(more, current.currentPage + 2) as TCursor | null;
+ } else {
+ // Only an empty page marks the end when the server reports no cursor.
+ next = page.items.length === 0 ? null : page.nextCursor;
+ }
+
+ // The first extension pins the join anchor at the head page's boundary.
+ let anchorId = current.anchorId;
+ if (current.currentPage === 0) {
+ const server = splitClientOnly(current.items, ctx).server;
+ const boundary = direction === 'forward' ? server.at(-1) : server[0];
+ anchorId = boundary ? getId(boundary) : undefined;
+ }
+
+ const items = ordered(
+ direction === 'forward' ? [...current.items, ...added] : [...added, ...current.items],
+ config,
+ );
+ const data = {
+ ...current,
+ anchorId,
+ currentPage: current.currentPage + 1,
+ isLoadingMore: false,
+ items,
+ loadMoreError: undefined,
+ nextCursor: next,
+ pages: [
+ ...(current.pages?.length ? current.pages : [{ count: current.items.length }]),
+ { count: added.length, next },
+ ],
+ total,
+ };
+ return { ...data, hasMore: deriveHasMore(data, serverCount) };
+};
+
+/**
+ * Insert new rows on the HEAD side (a streamed message, a created topic).
+ * Cursors point at the far end, so they stay valid; offsets shift and are
+ * healed by id de-duplication on the next page merge.
+ */
+export const insertHeadItems = <TItem, TCursor>(
+ current: ReplicaPagedData<TItem, TCursor>,
+ items: TItem[],
+ config: ReplicaPagingConfig<TItem>,
+): ReplicaPagedData<TItem, TCursor> => {
+ const seen = new Set(current.items.map(config.getId));
+ const added = dedupe(items, config.getId, seen);
+ if (added.length === 0) return current;
+ const pages = current.pages?.length ? current.pages : [{ count: current.items.length }];
+ return {
+ ...current,
+ items: ordered(join(added, current.items, config.direction), config),
+ pages: [{ ...pages[0], count: pages[0].count + added.length }, ...pages.slice(1)],
+ total: current.total === undefined ? undefined : current.total + added.length,
+ };
+};
+
+/**
+ * Patch (or remove, when `fn` returns `undefined`) one row by id. Returns the
+ * same reference when the row is absent or unchanged.
+ */
+export const mapPagedItem = <TItem, TCursor, TData extends ReplicaPagedData<TItem, TCursor>>(
+ current: TData,
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ config: Pick<ReplicaPagingConfig<TItem>, 'getId'>,
+): TData => {
+ const index = current.items.findIndex((item) => config.getId(item) === id);
+ if (index === -1) return current;
+ const next = fn(current.items[index]);
+ if (next === current.items[index]) return current;
+ if (next !== undefined) {
+ const items = [...current.items];
+ items[index] = next;
+ return { ...current, items };
+ }
+ const items = current.items.filter((_, i) => i !== index);
+ const total = current.total === undefined ? undefined : Math.max(items.length, current.total - 1);
+ return {
+ ...current,
+ hasMore: total !== undefined ? total > items.length : current.hasMore,
+ items,
+ total,
+ };
+};
+
+/** Whether a paged view holds a row. */
+export const hasPagedItem = <TItem>(
+ data: ReplicaPagedData<TItem, unknown> | undefined,
+ id: string,
+ config: Pick<ReplicaPagingConfig<TItem>, 'getId'>,
+) => !!data?.items.some((item) => config.getId(item) === id);
+
+/** Drop every loaded page but the head (e.g. after an edit inside older history). */
+export const collapseToHead = <TItem, TCursor>(
+ current: ReplicaPagedData<TItem, TCursor>,
+ config: ReplicaPagingConfig<TItem>,
+): ReplicaPagedData<TItem, TCursor> => {
+ if (current.currentPage === 0) return current;
+ const head = current.pages?.[0];
+ const count = head?.count ?? current.pageSize;
+ const items =
+ config.direction === 'forward' ? current.items.slice(0, count) : current.items.slice(-count);
+ const nextCursor = config.mode === 'offset' ? (1 as TCursor) : (head?.next ?? undefined);
+ return {
+ ...current,
+ anchorId: undefined,
+ currentPage: 0,
+ hasMore: true,
+ items,
+ nextCursor,
+ pages: [{ count: items.length, next: nextCursor }],
+ };
+};
+
+/**
+ * What survives a reload: whole pages from the head side, bounded by
+ * `persist.pages` and `persist.maxItems`, client-only rows and transient
+ * flags stripped. Offset views are cut at page-size boundaries so the
+ * persisted `currentPage` stays a valid offset; a cut inside a cursor page
+ * forgets the cursor (pagination resumes after the next server head page).
+ */
+export const toPersistedPage = <TItem, TCursor, TData extends ReplicaPagedData<TItem, TCursor>>(
+ data: TData,
+ config: ReplicaPagingConfig<TItem>,
+ ctx: ReplicaPagingContext<TItem> = {},
+): TData => {
+ const { server } = splitClientOnly(data.items, ctx);
+ const pageLimit = Math.max(1, config.persist?.pages ?? 1);
+ const maxItems = config.persist?.maxItems ?? Number.POSITIVE_INFINITY;
+ const pages = data.pages?.length ? data.pages : [{ count: server.length, next: data.nextCursor }];
+
+ let count = 0;
+ let keptPages = 0;
+ let aligned = true;
+ if (config.mode === 'offset') {
+ const loadedPages = Math.min(pageLimit, data.currentPage + 1);
+ const byItems = Math.floor(maxItems / Math.max(1, data.pageSize));
+ keptPages = Math.max(1, Math.min(loadedPages, byItems || 1));
+ count = Math.min(server.length, keptPages * data.pageSize, maxItems);
+ } else {
+ for (const page of pages.slice(0, pageLimit)) {
+ if (count + page.count > maxItems) {
+ aligned = false;
+ count = keptPages === 0 ? Math.min(page.count, maxItems) : count;
+ if (keptPages === 0) keptPages = 1;
+ break;
+ }
+ count += page.count;
+ keptPages += 1;
+ }
+ count = Math.min(count, server.length);
+ }
+
+ const items =
+ config.direction === 'forward' ? server.slice(0, count) : server.slice(server.length - count);
+ const lastKept = pages[keptPages - 1];
+ const nextCursor =
+ config.mode === 'offset'
+ ? ((count < (data.total ?? server.length) ? keptPages : null) as TCursor | null)
+ : aligned
+ ? lastKept?.next
+ : undefined;
+
+ const {
+ isLoadingMore: _loading,
+ loadMoreError: _error,
+ ...rest
+ } = data as ReplicaPagedData<TItem, TCursor>;
+ return {
+ ...rest,
+ anchorId: keptPages > 1 ? data.anchorId : undefined,
+ currentPage: keptPages - 1,
+ hasMore: data.total !== undefined ? data.total > items.length : nextCursor !== null,
+ items,
+ nextCursor,
+ pages: [
+ ...pages.slice(0, keptPages - 1),
+ {
+ count: Math.max(
+ 0,
+ items.length - pages.slice(0, keptPages - 1).reduce((sum, page) => sum + page.count, 0),
+ ),
+ next: nextCursor,
+ },
+ ],
+ } as unknown as TData;
+};
diff --git a/packages/replica/src/core/reducer.test.ts b/packages/replica/src/core/reducer.test.ts
new file mode 100644
index 00000000000..3006baa719c
--- /dev/null
+++ b/packages/replica/src/core/reducer.test.ts
@@ -0,0 +1,232 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ReplicaAction, ReplicaViewWrite } from './reducer';
+import { createReplicaState, replicaReducer } from './reducer';
+import type { ReplicaState } from './types';
+
+type List = string[];
+
+/** Tiny harness: applies view writes to a plain record, like a store lens would. */
+const createHarness = (initialView: Record<string, List> = {}) => {
+ let state: ReplicaState<List> = createReplicaState();
+ let view: Record<string, List> = { ...initialView };
+ const effects: unknown[] = [];
+
+ const run = (action: ReplicaAction<List>) => {
+ const transition = replicaReducer(state, action, (key) => view[key], 1);
+ state = transition.state;
+ for (const write of transition.writes as ReplicaViewWrite<List>[]) {
+ if ('type' in write) view = {};
+ else if (write.data === undefined) delete view[write.key];
+ else view[write.key] = write.data;
+ }
+ effects.push(...transition.effects);
+ return transition;
+ };
+
+ return {
+ effects,
+ run,
+ get state() {
+ return state;
+ },
+ get view() {
+ return view;
+ },
+ };
+};
+
+const S = 'user-1:personal';
+const append = (item: string) => (list: List) => [...list, item];
+
+describe('replicaReducer', () => {
+ describe('hydrate vs replace ordering', () => {
+ it('hydrates an empty slot without persisting', () => {
+ const h = createHarness();
+ h.run({ data: ['cached'], key: 'k', scope: S, type: 'hydrate' });
+
+ expect(h.view.k).toEqual(['cached']);
+ expect(h.state.entries.k.source).toBe('storage');
+ expect(h.effects).toEqual([]);
+ });
+
+ it('never lets a late hydrate overwrite a server projection', () => {
+ const h = createHarness();
+ h.run({ data: () => ['server'], key: 'k', scope: S, type: 'replace' });
+ h.run({ data: ['stale-cache'], key: 'k', scope: S, type: 'hydrate' });
+
+ expect(h.view.k).toEqual(['server']);
+ expect(h.state.entries.k.source).toBe('server');
+ });
+
+ it('does not hydrate over data already in memory (written outside the binding)', () => {
+ const h = createHarness({ k: ['memory'] });
+ h.run({ data: ['cached'], key: 'k', scope: S, type: 'hydrate' });
+
+ expect(h.view.k).toEqual(['memory']);
+ });
+
+ it('replace overwrites hydrated data and persists it', () => {
+ const h = createHarness();
+ h.run({ data: ['cached'], key: 'k', scope: S, type: 'hydrate' });
+ h.run({ data: () => ['server'], key: 'k', scope: S, type: 'replace' });
+
+ expect(h.view.k).toEqual(['server']);
+ expect(h.effects).toEqual([{ data: ['server'], key: 'k', scope: S, type: 'persist' }]);
+ });
+
+ it('replace merges against the confirmed value and treats undefined as no-op', () => {
+ const h = createHarness({ k: ['a'] });
+ const before = h.view.k;
+ h.run({ data: (confirmed) => confirmed, key: 'k', scope: S, type: 'replace' });
+ expect(h.view.k).toBe(before);
+
+ h.run({ data: () => undefined, key: 'k', scope: S, type: 'replace' });
+ expect(h.view.k).toBe(before);
+ expect(h.state.entries.k.source).toBe('server');
+ });
+ });
+
+ describe('scope isolation', () => {
+ it('ignores actions captured under another scope', () => {
+ const h = createHarness();
+ h.run({ data: () => ['mine'], key: 'k', scope: S, type: 'replace' });
+ h.run({ data: () => ['other-user'], key: 'k', scope: 'user-2:personal', type: 'replace' });
+ h.run({ data: ['other'], key: 'j', scope: 'user-2:personal', type: 'hydrate' });
+
+ expect(h.view).toEqual({ k: ['mine'] });
+ });
+
+ it('resetScope clears memory of the previous scope', () => {
+ const h = createHarness();
+ h.run({ data: () => ['mine'], key: 'k', scope: S, type: 'replace' });
+ h.run({ scope: 'user-2:personal', type: 'resetScope' });
+
+ expect(h.view).toEqual({});
+ expect(h.state).toEqual({ entries: {}, scope: 'user-2:personal' });
+
+ h.run({ data: ['theirs'], key: 'k', scope: 'user-2:personal', type: 'hydrate' });
+ expect(h.view.k).toEqual(['theirs']);
+ });
+
+ it('adopting the first scope does not clear data already in memory', () => {
+ const h = createHarness({ k: ['memory'] });
+ h.run({ scope: S, type: 'resetScope' });
+ expect(h.view.k).toEqual(['memory']);
+ });
+ });
+
+ describe('optimistic overlay', () => {
+ it('commit keeps the view and persists the confirmed value', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+ expect(h.view.k).toEqual(['a', 'b']);
+ expect(h.effects).toEqual([]);
+
+ h.run({ id: 1, key: 'k', scope: S, type: 'commit' });
+ expect(h.view.k).toEqual(['a', 'b']);
+ expect(h.state.entries.k.pending).toEqual([]);
+ expect(h.state.entries.k.base).toBeUndefined();
+ expect(h.effects).toEqual([{ data: ['a', 'b'], key: 'k', scope: S, type: 'persist' }]);
+ });
+
+ it('rollback restores the confirmed value without persisting', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+ h.run({ id: 1, key: 'k', scope: S, type: 'rollback' });
+
+ expect(h.view.k).toEqual(['a']);
+ expect(h.effects).toEqual([]);
+ });
+
+ it('rolling back one mutation keeps the other in-flight overlays', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+ h.run({ apply: append('c'), id: 2, key: 'k', scope: S, type: 'optimistic' });
+ h.run({ id: 1, key: 'k', scope: S, type: 'rollback' });
+
+ expect(h.view.k).toEqual(['a', 'c']);
+ h.run({ id: 2, key: 'k', scope: S, type: 'commit' });
+ expect(h.view.k).toEqual(['a', 'c']);
+ expect(h.effects.at(-1)).toEqual({ data: ['a', 'c'], key: 'k', scope: S, type: 'persist' });
+ });
+
+ it('a background replace rebases pending overlays instead of hiding them', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+ h.run({ data: () => ['a', 'z'], key: 'k', scope: S, type: 'replace' });
+
+ expect(h.view.k).toEqual(['a', 'z', 'b']);
+ // Only the server value is persisted, never the optimistic overlay.
+ expect(h.effects.at(-1)).toEqual({ data: ['a', 'z'], key: 'k', scope: S, type: 'persist' });
+
+ h.run({ id: 1, key: 'k', scope: S, type: 'rollback' });
+ expect(h.view.k).toEqual(['a', 'z']);
+ });
+
+ it('commit can confirm with the server result', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ apply: append('tmp'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+ h.run({ confirm: append('real'), id: 1, key: 'k', scope: S, type: 'commit' });
+
+ expect(h.view.k).toEqual(['a', 'real']);
+ });
+
+ it('an optimistic write on an unloaded key is a no-op', () => {
+ const h = createHarness();
+ h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+ h.run({ id: 1, key: 'k', scope: S, type: 'commit' });
+
+ expect(h.view).toEqual({});
+ expect(h.effects).toEqual([]);
+ });
+
+ it('drops a commit that lands after a scope switch', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ apply: append('b'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+ h.run({ scope: 'user-2:personal', type: 'resetScope' });
+ h.run({ id: 1, key: 'k', scope: S, type: 'commit' });
+
+ expect(h.view).toEqual({});
+ expect(h.effects).toEqual([]);
+ });
+ });
+
+ describe('confirmed local updates', () => {
+ it('patches view and base under an overlay, persisting the confirmed value', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ apply: append('opt'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+ h.run({
+ apply: (list) => list && [...list, 'confirmed'],
+ key: 'k',
+ persist: true,
+ scope: S,
+ type: 'update',
+ });
+
+ expect(h.view.k).toEqual(['a', 'opt', 'confirmed']);
+ expect(h.effects).toEqual([
+ { data: ['a', 'confirmed'], key: 'k', scope: S, type: 'persist' },
+ ]);
+
+ h.run({ id: 1, key: 'k', scope: S, type: 'rollback' });
+ expect(h.view.k).toEqual(['a', 'confirmed']);
+ });
+
+ it('persist: false only touches memory', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ apply: () => ['b'], key: 'k', persist: false, scope: S, type: 'update' });
+
+ expect(h.view.k).toEqual(['b']);
+ expect(h.effects).toEqual([]);
+ });
+
+ it('remove drops the entry and its persisted row', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ key: 'k', scope: S, type: 'remove' });
+
+ expect(h.view).toEqual({});
+ expect(h.effects).toEqual([{ key: 'k', scope: S, type: 'remove' }]);
+ });
+ });
+});
diff --git a/packages/replica/src/core/reducer.ts b/packages/replica/src/core/reducer.ts
new file mode 100644
index 00000000000..3ab49229903
--- /dev/null
+++ b/packages/replica/src/core/reducer.ts
@@ -0,0 +1,218 @@
+import type { ReplicaEntryMeta, ReplicaPendingMutation, ReplicaState } from './types';
+
+/**
+ * Pure transition core of a replica. It never touches the store
+ * or storage: it returns the next bookkeeping slot, the view writes the store
+ * binding must apply, and the persistence effects it must run.
+ *
+ * The VIEW (what selectors read) lives in the domain store, wherever the
+ * binding's lens puts it. The reducer only reads it through `readView`, so a
+ * domain can keep its existing state shape (e.g. `topicDataMap`).
+ */
+export type ReplicaAction<T> =
+ | {
+ data: T;
+ key: string;
+ params?: unknown;
+ query?: string;
+ scope: string;
+ type: 'hydrate';
+ updatedAt?: number;
+ }
+ | {
+ /** Receives the confirmed value (base or view); `undefined` keeps it. */
+ data: (confirmed: T | undefined) => T | undefined;
+ key: string;
+ params?: unknown;
+ query?: string;
+ scope: string;
+ type: 'replace';
+ }
+ | {
+ apply: (data: T | undefined) => T | undefined;
+ key: string;
+ persist: boolean;
+ scope: string;
+ type: 'update';
+ }
+ | { apply: (data: T) => T; id: number; key: string; scope: string; type: 'optimistic' }
+ | { confirm?: (data: T) => T; id: number; key: string; scope: string; type: 'commit' }
+ | { id: number; key: string; scope: string; type: 'rollback' }
+ | { key: string; scope: string; type: 'remove' }
+ | { scope: string; type: 'resetScope' };
+
+export type ReplicaEffect<T> =
+ | { data: T; key: string; query?: string; scope: string; type: 'persist' }
+ | { key: string; query?: string; scope: string; type: 'remove' };
+
+export type ReplicaViewWrite<T> = { data: T | undefined; key: string } | { type: 'clear' };
+
+export interface ReplicaTransition<T> {
+ effects: ReplicaEffect<T>[];
+ state: ReplicaState<T>;
+ writes: ReplicaViewWrite<T>[];
+}
+
+export const createReplicaState = <T>(): ReplicaState<T> => ({ entries: {} });
+
+const materialize = <T>(
+ base: T | undefined,
+ pending: ReplicaPendingMutation<T>[],
+): T | undefined =>
+ base === undefined
+ ? undefined
+ : pending.reduce<T>((data, mutation) => mutation.apply(data), base);
+
+const noop = <T>(state: ReplicaState<T>): ReplicaTransition<T> => ({
+ effects: [],
+ state,
+ writes: [],
+});
+
+export const replicaReducer = <T>(
+ state: ReplicaState<T>,
+ action: ReplicaAction<T>,
+ readView: (key: string) => T | undefined,
+ now: number = Date.now(),
+): ReplicaTransition<T> => {
+ if (action.type === 'resetScope') {
+ if (state.scope === action.scope) return noop(state);
+ // A different identity owns memory now: drop every entry (and its view) of
+ // the previous scope instead of letting it bleed into the new one.
+ return {
+ effects: [],
+ state: { entries: {}, scope: action.scope },
+ writes: state.scope === undefined ? [] : [{ type: 'clear' }],
+ };
+ }
+
+ // Late results from another scope (workspace switch, logout) are ignored.
+ if (state.scope !== undefined && state.scope !== action.scope) return noop(state);
+
+ const scope = action.scope;
+ const entry = state.entries[action.key];
+ const view = readView(action.key);
+ const confirmed = entry?.pending.length ? entry.base : view;
+ const withEntry = (next: ReplicaEntryMeta<T> | undefined): ReplicaState<T> => {
+ const entries = { ...state.entries };
+ if (next) entries[action.key] = next;
+ else delete entries[action.key];
+ return { entries, scope };
+ };
+
+ switch (action.type) {
+ case 'hydrate': {
+ // Hydrate only fills an empty slot: a server-confirmed value, an
+ // optimistic write or any local write always wins over storage.
+ if (entry || view !== undefined) return noop(state);
+ return {
+ effects: [],
+ state: withEntry({
+ params: action.params,
+ pending: [],
+ query: action.query,
+ source: 'storage',
+ updatedAt: action.updatedAt ?? now,
+ }),
+ writes: [{ data: action.data, key: action.key }],
+ };
+ }
+
+ case 'replace': {
+ const pending = entry?.pending ?? [];
+ const next = action.data(confirmed) ?? confirmed;
+ const query = 'query' in action ? action.query : entry?.query;
+ const nextState = withEntry({
+ base: pending.length ? next : undefined,
+ params: action.params ?? entry?.params,
+ pending,
+ query,
+ source: 'server',
+ updatedAt: now,
+ });
+ if (next === undefined) return { effects: [], state: nextState, writes: [] };
+ // In-flight optimistic mutations are rebased onto the fresh server value
+ // so a background revalidation never flickers them away.
+ const nextView = materialize(next, pending);
+ return {
+ effects: [{ data: next, key: action.key, query, scope, type: 'persist' }],
+ state: nextState,
+ writes: nextView === view ? [] : [{ data: nextView, key: action.key }],
+ };
+ }
+
+ case 'update': {
+ const nextView = action.apply(view);
+ const pending = entry?.pending ?? [];
+ const nextBase = pending.length ? action.apply(entry!.base) : nextView;
+ if (nextView === view && nextBase === confirmed) return noop(state);
+ return {
+ effects:
+ action.persist && nextBase !== undefined
+ ? [{ data: nextBase, key: action.key, query: entry?.query, scope, type: 'persist' }]
+ : [],
+ state: withEntry({
+ ...entry,
+ base: pending.length ? nextBase : undefined,
+ pending,
+ source: entry?.source ?? 'local',
+ updatedAt: now,
+ }),
+ writes: nextView === view ? [] : [{ data: nextView, key: action.key }],
+ };
+ }
+
+ case 'optimistic': {
+ if (view === undefined) return noop(state);
+ const pending = [...(entry?.pending ?? []), { apply: action.apply, id: action.id }];
+ return {
+ effects: [],
+ state: withEntry({
+ ...entry,
+ base: confirmed,
+ pending,
+ source: entry?.source ?? 'local',
+ updatedAt: entry?.updatedAt ?? now,
+ }),
+ writes: [{ data: action.apply(view), key: action.key }],
+ };
+ }
+
+ case 'commit':
+ case 'rollback': {
+ const mutation = entry?.pending.find((item) => item.id === action.id);
+ if (!entry || !mutation) return noop(state);
+ const pending = entry.pending.filter((item) => item.id !== action.id);
+ const base =
+ action.type === 'commit' && entry.base !== undefined
+ ? (action.confirm ?? mutation.apply)(entry.base)
+ : entry.base;
+ // A plain commit confirms what the view already shows; only a rollback or
+ // a server-provided `confirm` needs the view rebuilt from the base.
+ const nextView =
+ action.type === 'commit' && !action.confirm ? view : materialize(base, pending);
+ return {
+ effects:
+ action.type === 'commit' && base !== undefined
+ ? [{ data: base, key: action.key, query: entry.query, scope, type: 'persist' }]
+ : [],
+ state: withEntry({
+ ...entry,
+ base: pending.length ? base : undefined,
+ pending,
+ source: entry.source,
+ updatedAt: action.type === 'commit' ? now : entry.updatedAt,
+ }),
+ writes: nextView === view ? [] : [{ data: nextView, key: action.key }],
+ };
+ }
+
+ case 'remove': {
+ return {
+ effects: [{ key: action.key, query: entry?.query, scope, type: 'remove' }],
+ state: withEntry(undefined),
+ writes: view === undefined ? [] : [{ data: undefined, key: action.key }],
+ };
+ }
+ }
+};
diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.ts
new file mode 100644
index 00000000000..f135da9adea
--- /dev/null
+++ b/packages/replica/src/core/types.ts
@@ -0,0 +1,95 @@
+import type { ReplicaPagingConfig } from './paging';
+
+// ---- persistence contract ----------------------------------------------
+
+/** Address of one persisted row: the resource's row key inside an identity scope. */
+export interface ReplicaRowKey {
+ queryKey: string;
+ scope: string;
+}
+
+export interface ReplicaRow<T> {
+ data: T;
+ updatedAt: number;
+}
+
+/**
+ * Where a replica keeps its rows between sessions (IndexedDB, localStorage …).
+ * Best-effort by contract: the server stays the durable source of truth, so
+ * an implementation should swallow its own I/O failures.
+ */
+export interface ReplicaStorage<T> {
+ get: (key: ReplicaRowKey) => Promise<ReplicaRow<T> | undefined>;
+ remove: (key: ReplicaRowKey) => Promise<void>;
+ set: (key: ReplicaRowKey, row: ReplicaRow<T>) => Promise<void>;
+}
+
+/**
+ * Where the confirmed value of an entry came from.
+ * - `storage`: hydrated from the persisted projection (may be stale)
+ * - `server`: confirmed by a network response
+ * - `local`: written locally before any hydrate/replace landed
+ */
+export type ReplicaSource = 'local' | 'server' | 'storage';
+
+/**
+ * Identity partition of the persisted projection (user + workspace by default).
+ * `use` feeds the sync hook, `get` imperative actions, `canPersist` gates writes
+ * while the scope is still an optimistic guess (identity not resolved yet).
+ */
+export interface ReplicaScope {
+ canPersist: () => boolean;
+ get: () => string;
+ use: () => string;
+}
+
+export interface ReplicaPendingMutation<T> {
+ apply: (data: T) => T;
+ id: number;
+}
+
+export interface ReplicaEntryMeta<T> {
+ /**
+ * Confirmed snapshot. Only kept while optimistic mutations are in flight β€”
+ * otherwise the view itself is the confirmed value.
+ */
+ base?: T;
+ /** Params of the last hydrate/replace β€” what `loadMore` pages with. */
+ params?: unknown;
+ pending: ReplicaPendingMutation<T>[];
+ /** Stable query identity beyond the key (filters, page size). */
+ query?: string;
+ source: ReplicaSource;
+ updatedAt: number;
+}
+
+/** Bookkeeping slot a replica keeps inside its domain store. */
+export interface ReplicaState<T> {
+ entries: Record<string, ReplicaEntryMeta<T>>;
+ /** The scope every entry in memory belongs to. */
+ scope?: string;
+}
+
+export interface ReplicaResource<TParams, TData, TFetched = TData> {
+ /** Paged resources receive the page cursor (`undefined` = head page). */
+ fetcher?: (params: TParams, cursor?: any) => Promise<TFetched>;
+ key: (params: TParams) => string;
+ name: string;
+ /** Storage namespace β€” `name` + `version`, so a version bump orphans old rows. */
+ namespace: string;
+ /** Present on paged resources (`definePagedReplica`). */
+ paging?: ReplicaPagingConfig<any>;
+ /** Whether the resource survives a reload (it has a storage). */
+ persisted: boolean;
+ /**
+ * Query identity beyond `key` (filters, page size). Persisted rows are
+ * stored per query, so a different query never hydrates; in memory a query
+ * change resets loaded pages.
+ */
+ query: (params: TParams) => string | undefined;
+ scope: ReplicaScope;
+ storage?: ReplicaStorage<TData>;
+ /** Row key in `storage` for these params (`key`, plus `?query` when set). */
+ storageKey: (params: TParams) => string;
+ version: number;
+}
diff --git a/packages/replica/src/core/writeQueue.test.ts b/packages/replica/src/core/writeQueue.test.ts
new file mode 100644
index 00000000000..776e2fda2ef
--- /dev/null
+++ b/packages/replica/src/core/writeQueue.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ReplicaStorage } from './types';
+import { ReplicaWriteQueue } from './writeQueue';
+
+describe('ReplicaWriteQueue', () => {
+ it('serializes writes for the same projection key', async () => {
+ let releaseFirst!: () => void;
+ const first = new Promise<void>((resolve) => (releaseFirst = resolve));
+ const calls: number[] = [];
+ const storage: ReplicaStorage<number> = {
+ get: vi.fn(),
+ remove: vi.fn(),
+ set: vi.fn(async (_key, projection) => {
+ calls.push(projection.data);
+ if (projection.data === 1) await first;
+ }),
+ };
+ const queue = new ReplicaWriteQueue(storage);
+ const key = { queryKey: 'list', scope: 'scope' };
+
+ queue.set(key, { data: 1, updatedAt: 1 });
+ queue.set(key, { data: 2, updatedAt: 2 });
+ await vi.waitFor(() => expect(calls).toEqual([1]));
+
+ releaseFirst();
+ await vi.waitFor(() => expect(calls).toEqual([1, 2]));
+ });
+
+ it('update reads after earlier queued writes and never recreates a removed row', async () => {
+ const rows = new Map<string, { data: number; updatedAt: number }>();
+ const storage: ReplicaStorage<number> = {
+ get: async ({ queryKey }) => rows.get(queryKey),
+ remove: async ({ queryKey }) => {
+ rows.delete(queryKey);
+ },
+ set: async ({ queryKey }, projection) => {
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ rows.set(queryKey, projection);
+ },
+ };
+ const queue = new ReplicaWriteQueue(storage);
+ const key = { queryKey: 'list', scope: 'scope' };
+ const increment = (current?: { data: number }) =>
+ current ? { data: current.data + 1, updatedAt: 2 } : undefined;
+
+ queue.set(key, { data: 1, updatedAt: 1 });
+ queue.update(key, increment);
+ await vi.waitFor(() => expect(rows.get('list')?.data).toBe(2));
+
+ queue.remove(key);
+ queue.update(key, increment);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(rows.has('list')).toBe(false);
+ });
+});
diff --git a/packages/replica/src/core/writeQueue.ts b/packages/replica/src/core/writeQueue.ts
new file mode 100644
index 00000000000..86141cbef39
--- /dev/null
+++ b/packages/replica/src/core/writeQueue.ts
@@ -0,0 +1,52 @@
+import type { ReplicaRow, ReplicaRowKey, ReplicaStorage } from './types';
+
+/**
+ * Serializes writes for one projection key. A later snapshot can never be overwritten by an
+ * earlier, slower IndexedDB write.
+ */
+export class ReplicaWriteQueue<T> {
+ readonly #pending = new Map<string, Promise<void>>();
+ readonly #storage: ReplicaStorage<T>;
+
+ constructor(storage: ReplicaStorage<T>) {
+ this.#storage = storage;
+ }
+
+ #id = ({ queryKey, scope }: ReplicaRowKey) => `${scope}:${queryKey}`;
+
+ remove = (key: ReplicaRowKey): void => {
+ this.#enqueue(key, () => this.#storage.remove(key));
+ };
+
+ set = (key: ReplicaRowKey, value: ReplicaRow<T>): void => {
+ this.#enqueue(key, () => this.#storage.set(key, value));
+ };
+
+ /**
+ * Serialized read-modify-write: `fn` sees the row as of every earlier queued
+ * write for this key. Return a projection to write it, `null` to remove the
+ * row, or `undefined` to leave it untouched (a missing row stays missing).
+ */
+ update = (
+ key: ReplicaRowKey,
+ fn: (current: ReplicaRow<T> | undefined) => ReplicaRow<T> | null | undefined,
+ ): void => {
+ 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 => {
+ 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);
+ });
+ };
+}
diff --git a/packages/replica/src/index.ts b/packages/replica/src/index.ts
new file mode 100644
index 00000000000..d22053f7917
--- /dev/null
+++ b/packages/replica/src/index.ts
@@ -0,0 +1,8 @@
+export * from './core/defineReplica';
+export * from './core/engine';
+export * from './core/entity';
+export * from './core/keys';
+export * from './core/paging';
+export * from './core/reducer';
+export type * from './core/types';
+export * from './core/writeQueue';
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.ts
new file mode 100644
index 00000000000..451acbcc95b
--- /dev/null
+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts
@@ -0,0 +1,320 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement } from 'react';
+import { SWRConfig } from 'swr';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStore } from 'zustand/vanilla';
+
+import { testDriver as driver } from '../../tests/testDriver';
+import { defineReplica } from '../core/defineReplica';
+import { REPLICA_INDEX_KEY } from '../core/engine';
+import { createReplicaState } from '../core/reducer';
+import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';
+import { createReplicaSlice, recordLens } from './createReplicaSlice';
+
+interface TestState {
+ lists: Record<string, string[]>;
+ listsReplica: ReplicaState<string[]>;
+}
+
+const scopeState = { current: 'user-1:personal', trusted: true };
+const scope: ReplicaScope = {
+ canPersist: () => scopeState.trusted,
+ get: () => scopeState.current,
+ // The real `use` is `useCacheScope`; a plain getter is enough for these tests.
+ use: () => scopeState.current,
+};
+
+/** In-memory storage that records every write, keyed like the real ones. */
+const createMemoryStorage = (delays: Record<string, number> = {}) => {
+ const rows = new Map<string, ReplicaRow<string[]>>();
+ const writes: string[] = [];
+ const indexRows = new Map<string, ReplicaRow<string[]>>();
+ const storage: ReplicaStorage<string[]> = {
+ get: async ({ queryKey, scope }) =>
+ queryKey === REPLICA_INDEX_KEY
+ ? (indexRows.get(scope) as ReplicaRow<string[]> | undefined)
+ : rows.get(`${scope}|${queryKey}`),
+ remove: async ({ queryKey, scope }) => {
+ rows.delete(`${scope}|${queryKey}`);
+ },
+ set: async ({ queryKey, scope }, projection) => {
+ // The per-scope index of persisted rows is bookkeeping, not a data write.
+ if (queryKey === REPLICA_INDEX_KEY) return void indexRows.set(scope, projection);
+ const delay = delays[projection.data.join(',')] ?? 0;
+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
+ writes.push(projection.data.join(','));
+ rows.set(`${scope}|${queryKey}`, projection);
+ },
+ };
+ return { rows, storage, writes };
+};
+
+const setup = ({
+ fetcher = vi.fn(async (_params: { id: string }) => ['server']),
+ storage = createMemoryStorage(),
+ version = 1,
+}: {
+ fetcher?: (params: { id: string }) => Promise<string[]>;
+ storage?: ReturnType<typeof createMemoryStorage>;
+ version?: number;
+} = {}) => {
+ const resource = defineReplica<{ id: string }, string[]>({
+ fetcher,
+ key: ({ id }) => id,
+ name: 'testList',
+ scope,
+ storage: storage.storage,
+ version,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ driver,
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+ return { fetcher, resource, slice, storage, store };
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+beforeEach(() => {
+ scopeState.current = 'user-1:personal';
+ scopeState.trusted = true;
+});
+
+describe('createReplicaSlice', () => {
+ describe('useSync', () => {
+ it('paints the persisted projection while the network request is in flight', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });
+ let resolveFetch!: (value: string[]) => void;
+ const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));
+ const { slice, store } = setup({ fetcher, storage });
+
+ const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });
+
+ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached']));
+ // Background loading never hides the hydrated data.
+ expect(result.current.isHydrated).toBe(true);
+ expect(result.current.isValidating).toBe(true);
+
+ await act(async () => resolveFetch(['server']));
+
+ await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));
+ expect(store.getState().listsReplica.entries.a.source).toBe('server');
+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['server']));
+ });
+
+ it('does not let a slow hydration overwrite a faster server response', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });
+ const originalGet = storage.storage.get;
+ storage.storage.get = async (key) => {
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ return originalGet(key);
+ };
+ const { slice, store } = setup({ storage });
+
+ const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });
+
+ await waitFor(() => expect(result.current.isHydrated).toBe(true));
+ expect(store.getState().lists.a).toEqual(['server']);
+ });
+
+ 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.
+ const backing = new Map<string, ReplicaRow<string[]>>();
+ const namespaced = (namespace: string): ReplicaStorage<string[]> => ({
+ get: async ({ queryKey, scope }) => backing.get(`${namespace}|${scope}|${queryKey}`),
+ remove: async ({ queryKey, scope }) => {
+ backing.delete(`${namespace}|${scope}|${queryKey}`);
+ },
+ set: async ({ queryKey, scope }, row) => {
+ backing.set(`${namespace}|${scope}|${queryKey}`, row);
+ },
+ });
+ const bind = (version: number) => {
+ const resource = defineReplica<{ id: string }, string[]>({
+ key: ({ id }) => id,
+ name: 'versionedList',
+ scope,
+ storage: namespaced,
+ version,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ driver,
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+ return { slice, store };
+ };
+
+ const v1 = bind(1);
+ act(() => {
+ v1.slice.replace({ id: 'a' }, ['v1-shape']);
+ });
+ const dataKeys = () => [...backing.keys()].filter((key) => !key.includes(REPLICA_INDEX_KEY));
+ await waitFor(() => expect(dataKeys()).toHaveLength(1));
+
+ const v1Reload = bind(1);
+ await act(async () => {
+ await v1Reload.slice.hydrate({ id: 'a' });
+ });
+ expect(v1Reload.store.getState().lists.a).toEqual(['v1-shape']);
+
+ const v2 = bind(2);
+ await act(async () => {
+ await v2.slice.hydrate({ id: 'a' });
+ });
+ expect(v2.store.getState().lists.a).toBeUndefined();
+ });
+ });
+
+ describe('scope isolation', () => {
+ it('clears the previous identity and drops its late results', async () => {
+ const { slice, store, storage } = setup();
+ act(() => {
+ slice.replace({ id: 'a' }, ['user-1-data']);
+ });
+ expect(store.getState().lists.a).toEqual(['user-1-data']);
+
+ scopeState.current = 'user-2:personal';
+ // A response that was in flight for user 1 lands after the switch.
+ act(() => {
+ slice.replace({ id: 'a' }, ['late-user-1'], 'user-1:personal');
+ });
+ expect(store.getState().lists.a).toEqual(['user-1-data']);
+
+ // The first action under the new identity resets memory.
+ act(() => {
+ slice.replace({ id: 'b' }, ['user-2-data']);
+ });
+ expect(store.getState().lists).toEqual({ b: ['user-2-data'] });
+ expect(store.getState().listsReplica.scope).toBe('user-2:personal');
+
+ await waitFor(() => expect(storage.rows.size).toBe(2));
+ expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['user-1-data']);
+ expect(storage.rows.get('user-2:personal|b')?.data).toEqual(['user-2-data']);
+ });
+
+ it('useSync clears the previous identity even when the new scope has nothing to hydrate', async () => {
+ const fetcher = vi.fn(() => new Promise<string[]>(() => {}));
+ const { slice, store } = setup({ fetcher });
+ act(() => {
+ slice.replace({ id: 'a' }, ['user-1-data']);
+ });
+
+ scopeState.current = 'user-2:personal';
+ const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });
+
+ await waitFor(() => expect(result.current.isHydrated).toBe(true));
+ expect(store.getState().lists).toEqual({});
+ expect(store.getState().listsReplica.scope).toBe('user-2:personal');
+ });
+
+ it('hydrates only the active scope partition', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-2:personal|a', { data: ['someone-else'], updatedAt: 1 });
+ const { slice, store } = setup({ storage });
+
+ await act(async () => {
+ await slice.hydrate({ id: 'a' });
+ });
+
+ expect(store.getState().lists.a).toBeUndefined();
+ });
+
+ it('never persists while the scope is untrusted', async () => {
+ scopeState.trusted = false;
+ const { slice, storage } = setup();
+ act(() => {
+ slice.replace({ id: 'a' }, ['server']);
+ });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(storage.writes).toEqual([]);
+ });
+ });
+
+ describe('optimistic', () => {
+ it('commits and persists the confirmed value on success', async () => {
+ const { slice, store, storage } = setup();
+ act(() => {
+ slice.replace({ id: 'a' }, ['x']);
+ });
+
+ let resolveCall!: () => void;
+ let promise!: Promise<unknown>;
+ act(() => {
+ promise = slice.optimistic(
+ 'a',
+ (list) => [...list, 'y'],
+ () => new Promise<void>((resolve) => (resolveCall = resolve)),
+ );
+ });
+ expect(store.getState().lists.a).toEqual(['x', 'y']);
+
+ await act(async () => {
+ resolveCall();
+ await promise;
+ });
+ expect(store.getState().lists.a).toEqual(['x', 'y']);
+ await waitFor(() => expect(storage.writes.at(-1)).toBe('x,y'));
+ });
+
+ it('rolls back and rethrows on failure', async () => {
+ const { slice, store, storage } = setup();
+ act(() => {
+ slice.replace({ id: 'a' }, ['x']);
+ });
+ await waitFor(() => expect(storage.writes).toEqual(['x']));
+
+ await act(async () => {
+ await expect(
+ slice.optimistic(
+ 'a',
+ (list) => [...list, 'y'],
+ async () => {
+ throw new Error('boom');
+ },
+ ),
+ ).rejects.toThrow('boom');
+ });
+
+ expect(store.getState().lists.a).toEqual(['x']);
+ expect(storage.writes).toEqual(['x']);
+ });
+ });
+
+ describe('write ordering', () => {
+ it('serializes persistence per key so the latest snapshot wins', async () => {
+ // The first write is slow; without serialization it would land last.
+ const storage = createMemoryStorage({ first: 30 });
+ const { slice } = setup({ storage });
+
+ act(() => {
+ slice.replace({ id: 'a' }, ['first']);
+ slice.replace({ id: 'a' }, ['second']);
+ });
+
+ await waitFor(() => expect(storage.writes).toEqual(['first', 'second']));
+ expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['second']);
+ });
+ });
+});
diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.ts
new file mode 100644
index 00000000000..366db7a29a4
--- /dev/null
+++ b/packages/replica/src/zustand/createReplicaSlice.ts
@@ -0,0 +1,166 @@
+import { useLayoutEffect } from 'react';
+
+import { createReplicaEngine, type ReplicaEngineOptions } from '../core/engine';
+import { isReplicaSyncKey, replicaKeys } from '../core/keys';
+import type { ReplicaViewWrite } from '../core/reducer';
+import type { ReplicaResource, ReplicaState } from '../core/types';
+import type { ReplicaSyncDriver } from './driver';
+
+/** Zustand `setState`, with the devtools action label. */
+type Setter<TStore> = (partial: Partial<TStore>, replace?: false, action?: any) => void;
+
+/**
+ * Where the materialized value lives in the domain store. Selectors keep
+ * reading this location; the slice is the only writer.
+ */
+export interface ReplicaLens<TStore, TData> {
+ clear: (state: TStore) => Partial<TStore>;
+ get: (state: TStore, key: string) => TData | undefined;
+ /** Enumerate loaded keys (needed for entity propagation). */
+ keys?: (state: TStore) => string[];
+ set: (state: TStore, key: string, data: TData | undefined) => Partial<TStore>;
+}
+
+export interface CreateReplicaSliceOptions<TStore, TParams, TData, TFetched> extends Omit<
+ ReplicaEngineOptions<TParams, TData, TFetched>,
+ 'port' | 'revalidate'
+> {
+ /** Query cache that schedules fetches (see `createSWRDriver`). */
+ driver: ReplicaSyncDriver;
+ get: () => TStore;
+ set: Setter<TStore>;
+ /** Store field holding the {@link ReplicaState} bookkeeping slot. */
+ stateKey: keyof TStore & string;
+ /** Where the view lives in the store; `recordLens(field)` covers `Record<key, TData>`. */
+ view: ReplicaLens<TStore, TData>;
+}
+
+export interface ReplicaSyncOptions {
+ enabled?: boolean;
+}
+
+export interface ReplicaSyncResult {
+ error: unknown;
+ /** The persisted row has been read (or there is nothing to read). */
+ isHydrated: boolean;
+ /** A network request is in flight. Never a reason to hide store data. */
+ isValidating: boolean;
+ /** Re-run the network sync for this entry. */
+ revalidate: () => Promise<unknown>;
+}
+
+/**
+ * Bind a replica to a domain Zustand store.
+ *
+ * The domain store stays the only UI source of truth: components read the
+ * `view` location through their usual selectors. The engine owns every
+ * transition of that location; this slice adds the Zustand port and a
+ * `useSync` hook that only orchestrates fetching β€” data never flows through
+ * its return value.
+ */
+export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
+ resource: ReplicaResource<TParams, TData, TFetched>,
+ {
+ driver,
+ get,
+ set,
+ stateKey,
+ view,
+ ...options
+ }: CreateReplicaSliceOptions<TStore, TParams, TData, TFetched>,
+) => {
+ const applyWrites = (state: TStore, writes: ReplicaViewWrite<TData>[]) => {
+ let patch: Partial<TStore> = {};
+ let current = state;
+ for (const write of writes) {
+ const next = 'type' in write ? view.clear(current) : view.set(current, write.key, write.data);
+ patch = { ...patch, ...next };
+ current = { ...current, ...next };
+ }
+ return patch;
+ };
+
+ const revalidate = (key?: string) =>
+ driver.revalidate((queryKey) =>
+ isReplicaSyncKey(queryKey, resource.name, { key, scope: resource.scope.get() }),
+ );
+
+ const engine = createReplicaEngine(resource, {
+ ...options,
+ port: {
+ commit: (writes, state, label) =>
+ set({ ...applyWrites(get(), writes), [stateKey]: state } as Partial<TStore>, false, label),
+ getState: () => get()[stateKey] as unknown as ReplicaState<TData>,
+ keys: view.keys && (() => view.keys!(get())),
+ read: (key) => view.get(get(), key),
+ },
+ revalidate,
+ });
+ const { ensureScope, fetcher, hydrate, replace } = engine;
+
+ /**
+ * Hydrates the persisted row once per scope/key/query, then lets the driver
+ * fetch and revalidate the head. Read the data from the store.
+ */
+ const useSync = (
+ params: TParams | null | undefined,
+ { enabled = true }: ReplicaSyncOptions = {},
+ ): ReplicaSyncResult => {
+ const scope = resource.scope.use();
+ const key = params ? resource.key(params) : undefined;
+ const active = enabled && !!params && key !== undefined;
+
+ // Layout effect: runs before paint, so a scope switch never shows a frame
+ // of the previous identity's data.
+ useLayoutEffect(() => {
+ if (active) ensureScope(scope);
+ }, [active, scope]);
+
+ const hydration = driver.useQuery<boolean>(
+ active && resource.persisted
+ ? replicaKeys.hydrate(resource.name, resource.version, scope, resource.storageKey(params!))
+ : null,
+ async () => {
+ await hydrate(params!, scope);
+ return true;
+ },
+ { once: true },
+ );
+
+ const sync = driver.useQuery<TFetched>(
+ active && fetcher
+ ? replicaKeys.sync(resource.name, resource.version, scope, key!, params)
+ : null,
+ () => fetcher!(params!, undefined),
+ { onSuccess: (data) => replace(params!, data, scope) },
+ );
+
+ return {
+ error: sync.error,
+ isHydrated: !resource.persisted || hydration.data === true,
+ isValidating: sync.isValidating,
+ revalidate: () => sync.mutate(),
+ };
+ };
+
+ return { ...engine, useSync };
+};
+
+export type ReplicaSlice<TStore, TParams, TData, TFetched = TData> = ReturnType<
+ typeof createReplicaSlice<TStore, TParams, TData, TFetched>
+>;
+
+/** Lens for the common case: a `Record<key, TData>` field on the store. */
+export const recordLens = <TStore, TData>(
+ field: keyof TStore & string,
+): ReplicaLens<TStore, TData> => ({
+ clear: () => ({ [field]: {} }) as Partial<TStore>,
+ get: (state, key) => (state[field] as Record<string, TData> | undefined)?.[key],
+ keys: (state) => Object.keys((state[field] as Record<string, TData> | undefined) ?? {}),
+ set: (state, key, data) => {
+ const next = { ...(state[field] as Record<string, TData> | undefined) };
+ if (data === undefined) delete next[key];
+ else next[key] = data;
+ return { [field]: next } as Partial<TStore>;
+ },
+});
diff --git a/packages/replica/src/zustand/driver.ts b/packages/replica/src/zustand/driver.ts
new file mode 100644
index 00000000000..e74e32de8bf
--- /dev/null
+++ b/packages/replica/src/zustand/driver.ts
@@ -0,0 +1,57 @@
+export interface ReplicaQueryOptions<T> {
+ /** Run once per key: no refetch on focus, reconnect or remount (hydration reads). */
+ once?: boolean;
+ onSuccess?: (data: T) => void;
+}
+
+export interface ReplicaQueryResult<T> {
+ data?: T;
+ error?: unknown;
+ isValidating: boolean;
+ /** Re-run this query. */
+ mutate: () => Promise<unknown>;
+}
+
+/**
+ * The query cache that schedules a replica's fetches: dedupe, focus /
+ * reconnect revalidation, retries. The replica decides what a response means;
+ * the driver only decides when to ask. `createSWRDriver` adapts SWR.
+ */
+export interface ReplicaSyncDriver {
+ /** Re-run every mounted query whose key matches. */
+ revalidate: (match: (key: unknown) => boolean) => Promise<unknown>;
+ useQuery: <T>(
+ key: readonly unknown[] | null,
+ fetcher: () => Promise<T>,
+ options: ReplicaQueryOptions<T>,
+ ) => ReplicaQueryResult<T>;
+}
+
+type SWRLikeHook = (
+ key: any,
+ fetcher: any,
+ config?: any,
+) => { data?: any; error?: unknown; isValidating: boolean; mutate: () => Promise<any> };
+
+/**
+ * Driver over SWR. Pass the app's own hook and scoped `mutate` when it wraps
+ * SWR (custom cache provider, key augmentation, retry policy).
+ */
+export const createSWRDriver = ({
+ mutate,
+ useSWR,
+}: {
+ mutate: (match: (key: any) => boolean) => Promise<unknown>;
+ useSWR: SWRLikeHook;
+}): ReplicaSyncDriver => ({
+ revalidate: (match) => mutate(match),
+ useQuery: (key, fetcher, { once, onSuccess }) =>
+ useSWR(key, fetcher, {
+ ...(once && {
+ revalidateIfStale: false,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ }),
+ ...(onSuccess && { onSuccess: (data: unknown) => onSuccess(data as never) }),
+ }),
+});
diff --git a/packages/replica/src/zustand/index.ts b/packages/replica/src/zustand/index.ts
new file mode 100644
index 00000000000..4862ffd3922
--- /dev/null
+++ b/packages/replica/src/zustand/index.ts
@@ -0,0 +1,2 @@
+export * from './createReplicaSlice';
+export * from './driver';
diff --git a/packages/replica/src/zustand/pagedSlice.test.ts b/packages/replica/src/zustand/pagedSlice.test.ts
new file mode 100644
index 00000000000..87eae9656b5
--- /dev/null
+++ b/packages/replica/src/zustand/pagedSlice.test.ts
@@ -0,0 +1,366 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStore } from 'zustand/vanilla';
+
+import { testDriver as driver } from '../../tests/testDriver';
+import { definePagedReplica, defineReplica } from '../core/defineReplica';
+import { linkReplicaEntity } from '../core/entity';
+import type { ReplicaPagedData, ReplicaPageResult } from '../core/paging';
+import { createReplicaState } from '../core/reducer';
+import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';
+import { createReplicaSlice, recordLens } from './createReplicaSlice';
+
+interface Row {
+ id: string;
+ title: string;
+}
+interface Params {
+ filter?: string;
+ owner: string;
+ pageSize: number;
+}
+type Paged = ReplicaPagedData<Row, number> & { filter?: string };
+
+interface TestState {
+ details: Record<string, Row>;
+ detailsReplica: ReplicaState<Row>;
+ lists: Record<string, Paged>;
+ listsReplica: ReplicaState<Paged>;
+}
+
+const scopeState = { current: 'user-1' };
+const scope: ReplicaScope = {
+ canPersist: () => true,
+ get: () => scopeState.current,
+ use: () => scopeState.current,
+};
+
+const createMemoryStorage = <T>() => {
+ const rows = new Map<string, ReplicaRow<T>>();
+ const storage: ReplicaStorage<T> = {
+ get: async ({ queryKey, scope }) => rows.get(`${scope}|${queryKey}`),
+ remove: async ({ queryKey, scope }) => {
+ rows.delete(`${scope}|${queryKey}`);
+ },
+ set: async ({ queryKey, scope }, projection) => {
+ rows.set(`${scope}|${queryKey}`, projection);
+ },
+ };
+ return { rows, storage };
+};
+
+const row = (id: string, title = id): Row => ({ id, title });
+const ids = (data?: { items: Row[] }) => data?.items.map((item) => item.id);
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, reject, resolve };
+};
+
+/** Server with 2-row pages over `a..e` (or a filtered set). */
+const pageOf = (params: Params, cursor = 0): ReplicaPageResult<Row, number> => {
+ const all = (params.filter === 'odd' ? ['a', 'c', 'e'] : ['a', 'b', 'c', 'd', 'e']).map((id) =>
+ row(id),
+ );
+ return {
+ items: all.slice(cursor * params.pageSize, (cursor + 1) * params.pageSize),
+ total: all.length,
+ };
+};
+
+const setup = (
+ fetchPage = vi.fn(async (params: Params, cursor?: number) => pageOf(params, cursor)),
+ {
+ detailStorage = createMemoryStorage<Row>(),
+ listStorage = createMemoryStorage<Paged>(),
+ }: {
+ detailStorage?: ReturnType<typeof createMemoryStorage<Row>>;
+ listStorage?: ReturnType<typeof createMemoryStorage<Paged>>;
+ } = {},
+) => {
+ const listResource = definePagedReplica<Params, Row, number, Paged>({
+ fetchPage,
+ key: ({ owner }) => owner,
+ name: 'pagedTest',
+ paging: { direction: 'forward', getId: (item) => item.id, mode: 'offset' },
+ query: ({ filter }) => ({ filter }),
+ scope,
+ storage: listStorage.storage,
+ version: 1,
+ });
+ const detailResource = defineReplica<string, Row>({
+ key: (id) => id,
+ name: 'detailTest',
+ scope,
+ storage: detailStorage.storage,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ details: {},
+ detailsReplica: createReplicaState(),
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const list = createReplicaSlice(listResource, {
+ driver,
+ get: store.getState,
+ isClientOnly: (item: Row) => item.id.startsWith('tmp'),
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens<TestState, Paged>('lists'),
+ viewFields: ({ filter }) => ({ filter }),
+ });
+ const detail = createReplicaSlice(detailResource, {
+ driver,
+ entity: { getId: (item) => item.id },
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'detailsReplica',
+ view: recordLens<TestState, Row>('details'),
+ });
+ return { detail, detailStorage, fetchPage, list, listResource, listStorage, store };
+};
+
+const params: Params = { owner: 'o1', pageSize: 2 };
+
+beforeEach(() => {
+ scopeState.current = 'user-1';
+});
+
+describe('paged replica slice', () => {
+ it('loadMore pages with the stored head params and dedupes by id', async () => {
+ const { fetchPage, list, store } = setup();
+ list.replace(params, pageOf(params));
+ await list.loadMore('o1');
+ expect(fetchPage).toHaveBeenLastCalledWith(params, 1);
+ expect(ids(store.getState().lists.o1)).toEqual(['a', 'b', 'c', 'd']);
+ expect(store.getState().lists.o1).toMatchObject({ currentPage: 1, hasMore: true });
+ });
+
+ it('drops a page that lands after the query changed', async () => {
+ const pending = deferred<ReplicaPageResult<Row, number>>();
+ const { list, store } = setup(
+ vi.fn(async (p: Params, cursor?: number) => (cursor ? pending.promise : pageOf(p, cursor))),
+ );
+ list.replace(params, pageOf(params));
+ const loading = list.loadMore('o1');
+ expect(store.getState().lists.o1.isLoadingMore).toBe(true);
+
+ const odd = { ...params, filter: 'odd' };
+ list.replace(odd, pageOf(odd));
+ // Head refresh while the page is in flight keeps the flag.
+ expect(store.getState().lists.o1).toMatchObject({ filter: 'odd', isLoadingMore: true });
+
+ pending.resolve(pageOf(params, 1));
+ await loading;
+ expect(ids(store.getState().lists.o1)).toEqual(['a', 'c']);
+ expect(store.getState().lists.o1.isLoadingMore).toBe(false);
+ });
+
+ it('a head refresh with no page in flight clears a stale loading flag', () => {
+ const { list, store } = setup();
+ list.replace(params, pageOf(params));
+ list.update('o1', (data) => data && { ...data, isLoadingMore: true }, { persist: false });
+ list.replace(params, { items: [row('z'), row('a')], total: 6 });
+ expect(store.getState().lists.o1.isLoadingMore).toBe(false);
+ });
+
+ it('a scope switch clears loaded pages and drops the late page', async () => {
+ const pending = deferred<ReplicaPageResult<Row, number>>();
+ const { list, store } = setup(
+ vi.fn(async (p: Params, cursor?: number) => (cursor ? pending.promise : pageOf(p, cursor))),
+ );
+ list.replace(params, pageOf(params));
+ const loading = list.loadMore('o1');
+
+ scopeState.current = 'user-2';
+ list.ensureScope('user-2');
+ expect(store.getState().lists).toEqual({});
+
+ pending.resolve(pageOf(params, 1));
+ await loading;
+ expect(store.getState().lists).toEqual({});
+ });
+
+ it('rolls back an optimistic patch without losing a page loaded meanwhile', async () => {
+ const { list, store } = setup();
+ list.replace(params, pageOf(params));
+ const server = deferred<void>();
+
+ const write = list
+ .optimistic(
+ 'o1',
+ (data) => ({ ...data, items: data.items.map((r) => (r.id === 'a' ? row('a', 'A!') : r)) }),
+ () => server.promise,
+ )
+ .catch(() => undefined);
+ expect(store.getState().lists.o1.items[0].title).toBe('A!');
+
+ await list.loadMore('o1');
+ expect(ids(store.getState().lists.o1)).toEqual(['a', 'b', 'c', 'd']);
+
+ server.reject(new Error('nope'));
+ await write;
+ expect(store.getState().lists.o1.items[0].title).toBe('a');
+ expect(ids(store.getState().lists.o1)).toEqual(['a', 'b', 'c', 'd']);
+ });
+
+ it('persists the head page per query; another query never hydrates it', async () => {
+ const { list, listResource, listStorage, store } = setup();
+ list.replace(params, pageOf(params));
+ await list.loadMore('o1');
+ await vi.waitFor(() =>
+ expect(listStorage.rows.get(`user-1|${listResource.storageKey(params)}`)).toBeDefined(),
+ );
+ const persisted = listStorage.rows.get(`user-1|${listResource.storageKey(params)}`)!;
+ expect(ids(persisted.data)).toEqual(['a', 'b']);
+
+ // Fresh store: the filtered query misses, the original query hydrates.
+ const reloaded = setup();
+ reloaded.listStorage.rows.set(`user-1|${listResource.storageKey(params)}`, persisted);
+ expect(await reloaded.list.hydrate({ ...params, filter: 'odd' })).toBe(false);
+ expect(await reloaded.list.hydrate(params)).toBe(true);
+ expect(ids(reloaded.store.getState().lists.o1)).toEqual(['a', 'b']);
+ expect(store).toBeDefined();
+ });
+
+ it('insertHead keeps client-only rows across refreshes but out of storage', async () => {
+ const { list, listResource, listStorage, store } = setup();
+ list.replace(params, pageOf(params));
+ list.insertHead('o1', [row('tmp-1')]);
+ list.replace(params, pageOf(params));
+ expect(ids(store.getState().lists.o1)).toEqual(['tmp-1', 'a', 'b']);
+ await vi.waitFor(() => {
+ const persisted = listStorage.rows.get(`user-1|${listResource.storageKey(params)}`);
+ expect(ids(persisted?.data)).toEqual(['a', 'b']);
+ });
+ });
+});
+
+describe('linkReplicaEntity', () => {
+ const seeded = () => {
+ const ctx = setup();
+ ctx.list.replace(params, pageOf(params));
+ ctx.list.replace({ owner: 'o2', pageSize: 2 }, { items: [row('a'), row('x')], total: 2 });
+ ctx.detail.replace('a', row('a'));
+ const topic = linkReplicaEntity<Row>([ctx.list, ctx.detail]);
+ return { ...ctx, topic };
+ };
+
+ it('propagates a patch to every resource and key holding the entity', () => {
+ const { store, topic } = seeded();
+ topic.update('a', (r) => ({ ...r, title: 'renamed' }));
+ const state = store.getState();
+ expect(state.lists.o1.items[0].title).toBe('renamed');
+ expect(state.lists.o2.items[0].title).toBe('renamed');
+ expect(state.details.a.title).toBe('renamed');
+ expect(state.lists.o1.items[1].title).toBe('b');
+ });
+
+ it('removes the entity everywhere and fixes list totals', () => {
+ const { store, topic } = seeded();
+ topic.remove('a');
+ const state = store.getState();
+ expect(ids(state.lists.o1)).toEqual(['b']);
+ expect(state.lists.o1.total).toBe(4);
+ expect(state.details.a).toBeUndefined();
+ });
+
+ it('an optimistic write commits or rolls back across all resources together', async () => {
+ const { store, topic } = seeded();
+ const rename = (r: Row) => ({ ...r, title: 'opt' });
+
+ await expect(
+ topic.optimistic('a', rename, async () => {
+ expect(store.getState().details.a.title).toBe('opt');
+ expect(store.getState().lists.o2.items[0].title).toBe('opt');
+ throw new Error('server down');
+ }),
+ ).rejects.toThrow('server down');
+ expect(store.getState().details.a.title).toBe('a');
+ expect(store.getState().lists.o1.items[0].title).toBe('a');
+
+ await topic.optimistic('a', rename, async () => 'ok');
+ expect(store.getState().details.a.title).toBe('opt');
+ expect(store.getState().listsReplica.entries.o1.pending).toHaveLength(0);
+ });
+
+ it('an optimistic delete hides list rows at once and drops the detail on commit', async () => {
+ const { store, topic } = seeded();
+ const server = deferred<void>();
+ const removal = topic.optimistic('a', 'remove', () => server.promise);
+ expect(ids(store.getState().lists.o1)).toEqual(['b']);
+ expect(store.getState().details.a).toBeDefined();
+ server.resolve();
+ await removal;
+ expect(store.getState().details.a).toBeUndefined();
+ expect(ids(store.getState().lists.o2)).toEqual(['x']);
+ });
+});
+
+describe('entity changes for entries that are not loaded', () => {
+ /** Session 1 persists `o1` (list) and `a` (detail); session 2 starts with empty memory. */
+ const persistedThenReloaded = async () => {
+ const first = setup();
+ first.list.replace(params, pageOf(params));
+ first.detail.replace('a', row('a'));
+ const listKey = `user-1|${first.listResource.storageKey(params)}`;
+ await vi.waitFor(() => {
+ expect(first.listStorage.rows.get(listKey)).toBeDefined();
+ expect(first.detailStorage.rows.get('user-1|a')).toBeDefined();
+ });
+ const second = setup(undefined, {
+ detailStorage: first.detailStorage,
+ listStorage: first.listStorage,
+ });
+ const topic = linkReplicaEntity<Row>([second.list, second.detail]);
+ return { ...second, listKey, topic };
+ };
+
+ it('patches persisted rows of unloaded entries', async () => {
+ const { detailStorage, listKey, listStorage, store, topic } = await persistedThenReloaded();
+ topic.update('a', (r) => ({ ...r, title: 'done' }));
+ expect(store.getState().lists).toEqual({});
+ await vi.waitFor(() => {
+ expect(listStorage.rows.get(listKey)?.data.items[0].title).toBe('done');
+ expect(detailStorage.rows.get('user-1|a')?.data.title).toBe('done');
+ });
+ expect(listStorage.rows.get(listKey)?.data.items[1].title).toBe('b');
+ });
+
+ it('removes the entity from unloaded persisted rows and never resurrects them', async () => {
+ const { detailStorage, listKey, listStorage, topic } = await persistedThenReloaded();
+ topic.remove('a');
+ await vi.waitFor(() => {
+ expect(ids(listStorage.rows.get(listKey)?.data)).toEqual(['b']);
+ expect(detailStorage.rows.has('user-1|a')).toBe(false);
+ });
+ expect(listStorage.rows.get(listKey)?.data.total).toBe(4);
+
+ // A later patch of the removed entity must not recreate its detail row.
+ topic.update('a', (r) => ({ ...r, title: 'ghost' }));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(detailStorage.rows.has('user-1|a')).toBe(false);
+ });
+
+ it('a committed optimistic write also reaches unloaded rows', async () => {
+ const { listKey, listStorage, topic } = await persistedThenReloaded();
+ await topic.optimistic(
+ 'a',
+ (r) => ({ ...r, title: 'opt' }),
+ async () => 'ok',
+ );
+ await vi.waitFor(() => expect(listStorage.rows.get(listKey)?.data.items[0].title).toBe('opt'));
+ });
+
+ it('never touches rows of another scope', async () => {
+ const { listKey, listStorage, topic } = await persistedThenReloaded();
+ scopeState.current = 'user-2';
+ topic.update('a', (r) => ({ ...r, title: 'other-user' }));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(listStorage.rows.get(listKey)?.data.items[0].title).toBe('a');
+ });
+});
diff --git a/packages/replica/tests/testDriver.ts b/packages/replica/tests/testDriver.ts
new file mode 100644
index 00000000000..08a093fd9c6
--- /dev/null
+++ b/packages/replica/tests/testDriver.ts
@@ -0,0 +1,6 @@
+import useSWR, { mutate } from 'swr';
+
+import { createSWRDriver } from '../src/zustand/driver';
+
+/** SWR driver for tests: plain `useSWR`, matcher revalidation on the default cache. */
+export const testDriver = createSWRDriver({ mutate: (match) => mutate(match), useSWR });
diff --git a/packages/replica/vitest.config.mts b/packages/replica/vitest.config.mts
new file mode 100644
index 00000000000..940870a78e9
--- /dev/null
+++ b/packages/replica/vitest.config.mts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ reporter: ['text', 'json', 'lcov', 'text-summary'],
+ },
+ environment: 'happy-dom',
+ },
+});
diff --git a/src/features/AgentSidebar/Topic/List/TopicListSkeleton.tsx b/src/features/AgentSidebar/Topic/List/TopicListSkeleton.tsx
index 72b76627c48..41af5848dac 100644
--- a/src/features/AgentSidebar/Topic/List/TopicListSkeleton.tsx
+++ b/src/features/AgentSidebar/Topic/List/TopicListSkeleton.tsx
@@ -6,8 +6,10 @@ import { cssVar } from 'antd-style';
import { memo } from 'react';
// Mirrors the grouped topic list frame (12px group caption + icon-led 36px
-// rows) so the deferred-mount frame reads as the layout it resolves into,
-// unlike the avatar-style generic SkeletonList.
+// rows) so a session without a persisted page reads as the layout it resolves
+// into, unlike the avatar-style generic SkeletonList. The test id is the hook a
+// product-level frame capture uses to prove no such frame is painted once the
+// agent route loader has seeded the page.
const GROUPS = [
{ header: 44, rows: ['82%', '58%', '70%'] },
{ header: 60, rows: ['64%', '76%', '48%', '68%'] },
@@ -43,7 +45,7 @@ const RowSkeleton = memo<{ width: string }>(({ width }) => (
RowSkeleton.displayName = 'TopicRowSkeleton';
const TopicListSkeleton = memo(() => (
- <Flexbox gap={2}>
+ <Flexbox data-testid={'topic-list-skeleton'} gap={2}>
{GROUPS.map((group, i) => (
<Flexbox gap={1} key={i} paddingBlock={4} paddingInline={'8px 4px'}>
<Flexbox horizontal align={'center'} height={24}>
diff --git a/src/features/AgentSidebar/Topic/List/index.test.tsx b/src/features/AgentSidebar/Topic/List/index.test.tsx
index 784ca653525..6f7891b5eda 100644
--- a/src/features/AgentSidebar/Topic/List/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/index.test.tsx
@@ -23,6 +23,14 @@ const chatStoreStateMock = vi.hoisted(() => ({
topicLength: 0,
topics: [],
}));
+const skeletonRenderCount = vi.hoisted(() => ({ value: 0 }));
+
+vi.mock('./TopicListSkeleton', () => ({
+ default: () => {
+ skeletonRenderCount.value += 1;
+ return <div data-testid="topic-list-skeleton" />;
+ },
+}));
vi.mock('@/features/NavPanel/components/EmptyNavItem', () => ({
default: ({
@@ -142,8 +150,28 @@ describe('Agent topic list', () => {
permissionMock.create_content = true;
chatStoreStateMock.hasMore = true;
chatStoreStateMock.isExpandingPageSize = false;
+ chatStoreStateMock.isUndefinedTopics = false;
chatStoreStateMock.topicLength = 0;
chatStoreStateMock.topics = [];
+ skeletonRenderCount.value = 0;
+ });
+
+ // The route loader seeds the persisted page before this mounts
+ // (`agentChatTopicListLoader`), so a mount frame that shows the loading
+ // placeholder is exactly the flash this must not reintroduce.
+ it('renders the list on the mount commit when the session bucket already exists', () => {
+ render(<TopicList />);
+
+ expect(skeletonRenderCount.value).toBe(0);
+ expect(screen.getByTestId('all-topics-drawer')).toBeInTheDocument();
+ });
+
+ it('keeps the skeleton for a session whose bucket has not landed yet', () => {
+ chatStoreStateMock.isUndefinedTopics = true;
+
+ render(<TopicList />);
+
+ expect(screen.getByTestId('topic-list-skeleton')).toBeInTheDocument();
});
it('opens the agent chat route from the empty start topic entry', () => {
diff --git a/src/features/AgentSidebar/Topic/List/index.tsx b/src/features/AgentSidebar/Topic/List/index.tsx
index 99e3b068477..e7a6a2ec30b 100644
--- a/src/features/AgentSidebar/Topic/List/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/index.tsx
@@ -5,7 +5,6 @@ import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
-import { useDeferredMount } from '@/hooks/useDeferredMount';
import { useFetchActiveTopicDetail } from '@/hooks/useFetchActiveTopicDetail';
import { useFetchChatTopics } from '@/hooks/useFetchChatTopics';
import { usePermission } from '@/hooks/usePermission';
@@ -39,13 +38,11 @@ const TopicList = memo(() => {
useFetchChatTopics();
useFetchActiveTopicDetail();
- // Route transitions must paint instantly: the mount commit shows a skeleton
- // frame and the real list renders in a deferred (interruptible) follow-up
- // pass, off the navigation's critical path.
- const listReady = useDeferredMount();
-
- // Show skeleton when current session's topic data is not yet loaded
- if (isUndefinedTopics || !listReady) return <TopicListSkeleton />;
+ // The agent route loader seeds this session's persisted page before the layout
+ // commits (`agentChatTopicListLoader`), so a frame painted here already has
+ // rows. The skeleton is left for the cases that genuinely have nothing
+ // persisted yet, or a storage read that never lands β€” never as a mount tax.
+ if (isUndefinedTopics) return <TopicListSkeleton />;
return (
<>
diff --git a/src/features/AgentTopicManager/index.tsx b/src/features/AgentTopicManager/index.tsx
index 7ba1add250f..78312354a18 100644
--- a/src/features/AgentTopicManager/index.tsx
+++ b/src/features/AgentTopicManager/index.tsx
@@ -83,7 +83,7 @@ const AgentTopicManager = memo(() => {
reset();
}, [activeAgentId, reset]);
- const { error, isLoading, mutate } = useFetchAgentTopicsView(true, {
+ const { error, isHydrated, isValidating, revalidate } = useFetchAgentTopicsView(true, {
agentId: activeAgentId,
pageSize: PAGE_SIZE,
// Opt into the heavier card-detail columns (firstUserMessage,
@@ -92,6 +92,9 @@ const AgentTopicManager = memo(() => {
withDetails: true,
});
+ // Rows come from the store; the hook only reports fetch progress.
+ const isLoading = !isHydrated || isValidating;
+
const trimmedSearch = search.trim();
const { data: searchResults } = useSearchTopics(
trimmedSearch.length > 0 ? trimmedSearch : undefined,
@@ -244,7 +247,7 @@ const AgentTopicManager = memo(() => {
error={error}
variant={'block'}
onRetry={() => {
- void mutate();
+ void revalidate();
}}
/>
) : isLoading && baseTopics.length === 0 ? (
diff --git a/src/hooks/chatTopicListQuery.test.ts b/src/hooks/chatTopicListQuery.test.ts
new file mode 100644
index 00000000000..6c48ba04b87
--- /dev/null
+++ b/src/hooks/chatTopicListQuery.test.ts
@@ -0,0 +1,139 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
+
+import { deriveSidebarTopicListQuery, getSidebarTopicListParams } from './chatTopicListQuery';
+
+const agentStateMock = vi.hoisted(() => ({
+ activeAgentId: 'agent-1' as string | undefined,
+ agentMap: {} as Record<string, any>,
+ builtinAgentIdMap: { inbox: 'agt_inbox' } as Record<string, string>,
+}));
+const globalStateMock = vi.hoisted(() => ({ topicPageSize: 20 }));
+const userStateMock = vi.hoisted(() => ({
+ topicGroupMode: 'byTime' as string,
+ topicIncludeCompleted: false,
+}));
+
+vi.mock('@/store/agent', () => ({ useAgentStore: { getState: () => agentStateMock } }));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: {
+ currentAgentConfig: (s: typeof agentStateMock) => s.agentMap[s.activeAgentId!],
+ getAgentConfigById: (id: string) => (s: typeof agentStateMock) => s.agentMap[id],
+ },
+ builtinAgentSelectors: {
+ inboxAgentId: (s: typeof agentStateMock) => s.builtinAgentIdMap.inbox,
+ },
+}));
+
+vi.mock('@/store/global', () => ({ useGlobalStore: { getState: () => globalStateMock } }));
+
+vi.mock('@/store/global/selectors', () => ({
+ systemStatusSelectors: { topicPageSize: (s: typeof globalStateMock) => s.topicPageSize },
+}));
+
+vi.mock('@/store/user', () => ({ useUserStore: { getState: () => userStateMock } }));
+
+vi.mock('@/store/user/selectors', () => ({
+ preferenceSelectors: {
+ topicGroupMode: (s: typeof userStateMock) => s.topicGroupMode,
+ topicIncludeCompleted: (s: typeof userStateMock) => s.topicIncludeCompleted,
+ },
+}));
+
+describe('deriveSidebarTopicListQuery', () => {
+ it('hides completed topics and keeps the sidebar trigger filter by default', () => {
+ expect(
+ deriveSidebarTopicListQuery({
+ includeCompleted: false,
+ isGroupSession: false,
+ topicGroupMode: 'byTime',
+ }),
+ ).toEqual({
+ excludeStatuses: ['completed'],
+ excludeTriggers: MAIN_SIDEBAR_EXCLUDE_TRIGGERS,
+ sortBy: undefined,
+ });
+ });
+
+ it('drops the completed filter when the preference includes them', () => {
+ expect(
+ deriveSidebarTopicListQuery({
+ includeCompleted: true,
+ isGroupSession: false,
+ topicGroupMode: 'byTime',
+ }).excludeStatuses,
+ ).toBeUndefined();
+ });
+
+ it('sorts by status only for an agent session grouped by status', () => {
+ expect(
+ deriveSidebarTopicListQuery({
+ includeCompleted: false,
+ isGroupSession: false,
+ topicGroupMode: 'byStatus',
+ }).sortBy,
+ ).toBe('status');
+
+ expect(
+ deriveSidebarTopicListQuery({
+ includeCompleted: false,
+ isGroupSession: true,
+ topicGroupMode: 'byStatus',
+ }).sortBy,
+ ).toBeUndefined();
+ });
+});
+
+describe('getSidebarTopicListParams', () => {
+ beforeEach(() => {
+ agentStateMock.activeAgentId = 'agent-1';
+ agentStateMock.agentMap = {};
+ globalStateMock.topicPageSize = 20;
+ userStateMock.topicGroupMode = 'byTime';
+ userStateMock.topicIncludeCompleted = false;
+ });
+
+ it('returns nothing without a session', () => {
+ expect(getSidebarTopicListParams({})).toBeNull();
+ });
+
+ it('builds the exact request the sidebar will make for a route agent', () => {
+ expect(getSidebarTopicListParams({ agentId: 'agent-7' })).toEqual({
+ agentId: 'agent-7',
+ excludeStatuses: ['completed'],
+ excludeTriggers: MAIN_SIDEBAR_EXCLUDE_TRIGGERS,
+ isInbox: false,
+ pageSize: 20,
+ });
+ });
+
+ it('flags the inbox agent and honours the page size preference', () => {
+ globalStateMock.topicPageSize = 30;
+
+ expect(getSidebarTopicListParams({ agentId: 'agt_inbox' })).toMatchObject({
+ isInbox: true,
+ pageSize: 30,
+ });
+ });
+
+ it('resolves the group mode from the route agent config, not the active one', () => {
+ agentStateMock.activeAgentId = 'some-other-agent';
+ agentStateMock.agentMap['agent-7'] = { chatConfig: { topicGroupMode: 'byStatus' } };
+
+ expect(getSidebarTopicListParams({ agentId: 'agent-7' })?.sortBy).toBe('status');
+ });
+
+ it('never flags a group session as inbox and keeps its default ordering', () => {
+ userStateMock.topicGroupMode = 'byStatus';
+
+ expect(getSidebarTopicListParams({ groupId: 'grp_1' })).toEqual({
+ groupId: 'grp_1',
+ excludeStatuses: ['completed'],
+ excludeTriggers: MAIN_SIDEBAR_EXCLUDE_TRIGGERS,
+ isInbox: false,
+ pageSize: 20,
+ });
+ });
+});
diff --git a/src/hooks/chatTopicListQuery.ts b/src/hooks/chatTopicListQuery.ts
new file mode 100644
index 00000000000..a4ac5f4cc55
--- /dev/null
+++ b/src/hooks/chatTopicListQuery.ts
@@ -0,0 +1,99 @@
+import type { TopicQuerySortBy } from '@lobechat/types';
+
+import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
+import { resolveAgentTopicGroupMode } from '@/features/AgentSidebar/Topic/utils/topicGroupMode';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import {
+ normalizeTopicListParams,
+ type TopicListParams,
+} from '@/store/chat/slices/topic/projection';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+import type { TopicGroupMode } from '@/types/topic';
+
+const EXCLUDE_STATUSES_COMPLETED = ['completed'];
+
+/**
+ * Filter / sort identity of a sidebar list request β€” the local-first resource's
+ * `query`, which decides which persisted row may hydrate the bucket.
+ */
+export interface SidebarTopicListQuery {
+ excludeStatuses?: string[];
+ excludeTriggers?: string[];
+ sortBy?: TopicQuerySortBy;
+}
+
+/**
+ * Pure derivation of that identity from its inputs.
+ *
+ * Both readers below feed it β€” the reactive hook that renders the sidebar and
+ * the imperative one the route loader uses before the first paint β€” so the two
+ * paths can never ask for different rows.
+ *
+ * "Group by status" ordering is resolved server-side so the highest-priority
+ * topics stay on the first page even when the list is paginated; only the agent
+ * sidebar supports it, group sessions keep the default updatedAt ordering.
+ */
+export const deriveSidebarTopicListQuery = ({
+ includeCompleted,
+ isGroupSession,
+ topicGroupMode,
+}: {
+ includeCompleted: boolean;
+ isGroupSession: boolean;
+ topicGroupMode: TopicGroupMode;
+}): SidebarTopicListQuery => ({
+ excludeStatuses: includeCompleted ? undefined : EXCLUDE_STATUSES_COMPLETED,
+ excludeTriggers: MAIN_SIDEBAR_EXCLUDE_TRIGGERS,
+ sortBy: !isGroupSession && topicGroupMode === 'byStatus' ? 'status' : undefined,
+});
+
+/**
+ * Topic-group mode of one agent, resolved the same way the sidebar resolves it
+ * for the active agent (agent config β†’ CLI-agent default β†’ user preference).
+ */
+export const getTopicGroupModeForAgent = (agentId?: string): TopicGroupMode => {
+ const agentState = useAgentStore.getState();
+ const config = agentId
+ ? agentSelectors.getAgentConfigById(agentId)(agentState)
+ : agentSelectors.currentAgentConfig(agentState);
+
+ return resolveAgentTopicGroupMode({
+ agentTopicGroupMode: config?.chatConfig?.topicGroupMode,
+ agentType: config?.agencyConfig?.heterogeneousProvider?.type,
+ globalMode: preferenceSelectors.topicGroupMode(useUserStore.getState()),
+ });
+};
+
+/**
+ * The exact params the agent sidebar will ask for, computed without React so a
+ * route loader can hydrate the persisted page before the first paint.
+ *
+ * `session.agentId` names the *route's* agent: until the agent layout commits,
+ * the stores still hold the previously active agent.
+ */
+export const getSidebarTopicListParams = (session: {
+ agentId?: string;
+ groupId?: string;
+}): TopicListParams | null => {
+ const { agentId, groupId } = session;
+ if (!agentId && !groupId) return null;
+
+ const agentState = useAgentStore.getState();
+ const inboxAgentId = builtinAgentSelectors.inboxAgentId(agentState);
+
+ return normalizeTopicListParams({
+ ...deriveSidebarTopicListQuery({
+ includeCompleted: preferenceSelectors.topicIncludeCompleted(useUserStore.getState()),
+ isGroupSession: !!groupId,
+ topicGroupMode: getTopicGroupModeForAgent(agentId),
+ }),
+ agentId,
+ groupId,
+ isInbox: !groupId && !!inboxAgentId && inboxAgentId === agentId,
+ pageSize: systemStatusSelectors.topicPageSize(useGlobalStore.getState()),
+ });
+};
diff --git a/src/hooks/useFetchChatTopics.test.ts b/src/hooks/useFetchChatTopics.test.ts
index 97e6d4bd366..268eda961f5 100644
--- a/src/hooks/useFetchChatTopics.test.ts
+++ b/src/hooks/useFetchChatTopics.test.ts
@@ -39,6 +39,7 @@ vi.mock('@/store/chat', () => ({
activeAgentId: mocks.activeAgentId,
activeGroupId: mocks.activeGroupId,
useFetchTopics: mocks.storeFetchTopics,
+ topicDataMap: {},
}),
}));
diff --git a/src/hooks/useFetchChatTopics.ts b/src/hooks/useFetchChatTopics.ts
index 45985eb2756..3b8ed740297 100644
--- a/src/hooks/useFetchChatTopics.ts
+++ b/src/hooks/useFetchChatTopics.ts
@@ -1,7 +1,8 @@
-import type { TopicQuerySortBy } from '@lobechat/types';
-
-import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
import { useAgentTopicGroupMode } from '@/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode';
+import {
+ deriveSidebarTopicListQuery,
+ type SidebarTopicListQuery,
+} from '@/hooks/chatTopicListQuery';
import { useFetchTopics } from '@/hooks/useFetchTopics';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
@@ -11,8 +12,6 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
-const EXCLUDE_STATUSES_COMPLETED = ['completed'];
-
/**
* The one query shape a `topicDataMap` bucket is allowed to hold. The bucket is
* keyed by container (`agent_<id>`) only β€” not by filters β€” so every fetch that
@@ -20,27 +19,20 @@ const EXCLUDE_STATUSES_COMPLETED = ['completed'];
* mounted fetches with different filters therefore fight, and the looser one
* wins whenever it lands last.
*
- * Keep all filter derivation here so no call site can drift: same args means
- * the same SWR key, which means SWR dedupes them into a single request.
+ * The derivation itself lives in {@link deriveSidebarTopicListQuery}, which the
+ * pre-paint hydrate reads imperatively: same inputs means the same SWR key and
+ * the same persisted row, so SWR dedupes and the hydrate actually applies.
*/
-const useChatTopicListQuery = () => {
+const useChatTopicListQuery = (): SidebarTopicListQuery => {
const includeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);
const activeGroupId = useChatStore((s) => s.activeGroupId);
const { topicGroupMode } = useAgentTopicGroupMode();
- // "Group by status" ordering is resolved server-side so the highest-priority
- // topics (awaiting human β†’ running β†’ active) stay on the first page even when
- // the list is paginated β€” client-side grouping over a partial page is exactly
- // what made the previous approach flaky. Only the agent sidebar supports it;
- // group sessions keep the default updatedAt ordering.
- const sortBy: TopicQuerySortBy | undefined =
- !activeGroupId && topicGroupMode === 'byStatus' ? 'status' : undefined;
-
- return {
- excludeStatuses: includeCompleted ? undefined : EXCLUDE_STATUSES_COMPLETED,
- excludeTriggers: MAIN_SIDEBAR_EXCLUDE_TRIGGERS,
- sortBy,
- };
+ return deriveSidebarTopicListQuery({
+ includeCompleted,
+ isGroupSession: !!activeGroupId,
+ topicGroupMode,
+ });
};
/**
diff --git a/src/hooks/useFetchTopics.test.ts b/src/hooks/useFetchTopics.test.ts
index bce091a0fc5..2da57cd3da1 100644
--- a/src/hooks/useFetchTopics.test.ts
+++ b/src/hooks/useFetchTopics.test.ts
@@ -52,6 +52,7 @@ describe('useFetchTopics', () => {
activeAgentId,
activeGroupId: undefined,
useFetchTopics: mockUseFetchTopicsFn,
+ topicDataMap: {},
}),
);
@@ -74,6 +75,7 @@ describe('useFetchTopics', () => {
activeAgentId,
activeGroupId,
useFetchTopics: mockUseFetchTopicsFn,
+ topicDataMap: {},
}),
);
@@ -98,6 +100,7 @@ describe('useFetchTopics', () => {
activeAgentId: INBOX_SESSION_ID,
activeGroupId,
useFetchTopics: mockUseFetchTopicsFn,
+ topicDataMap: {},
}),
);
@@ -120,6 +123,7 @@ describe('useFetchTopics', () => {
activeAgentId: INBOX_SESSION_ID,
activeGroupId: undefined,
useFetchTopics: mockUseFetchTopicsFn,
+ topicDataMap: {},
}),
);
@@ -141,6 +145,7 @@ describe('useFetchTopics', () => {
activeAgentId: 'agent-1',
activeGroupId: undefined,
useFetchTopics: mockUseFetchTopicsFn,
+ topicDataMap: {},
}),
);
mockUseGlobalStore.mockImplementation((selector) =>
diff --git a/src/hooks/useFetchTopics.ts b/src/hooks/useFetchTopics.ts
index 537d0b004b4..5d6a8772d6e 100644
--- a/src/hooks/useFetchTopics.ts
+++ b/src/hooks/useFetchTopics.ts
@@ -3,6 +3,7 @@ import type { TopicQuerySortBy } from '@lobechat/types';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
+import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -24,7 +25,10 @@ export const useFetchTopics = (options?: {
const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
// If in group session, use groupId; otherwise use agentId
- const { isValidating, data } = useFetchTopicsHook(true, {
+ const hasTopicData = useChatStore(
+ (s) => !!s.topicDataMap[topicMapKey({ agentId: activeAgentId, groupId: activeGroupId })],
+ );
+ const { isValidating } = useFetchTopicsHook(true, {
agentId: activeAgentId,
...(options?.excludeStatuses && options.excludeStatuses.length > 0
? { excludeStatuses: options.excludeStatuses }
@@ -39,7 +43,7 @@ export const useFetchTopics = (options?: {
});
return {
- // isRevalidating: has cached data, updating in background
- isRevalidating: isValidating && !!data,
+ // isRevalidating: the store already shows topics, updating in background
+ isRevalidating: isValidating && hasTopicData,
};
};
diff --git a/src/libs/replica/index.test.ts b/src/libs/replica/index.test.ts
new file mode 100644
index 00000000000..83f0734bfaa
--- /dev/null
+++ b/src/libs/replica/index.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { replicaSWRDriver } 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', () => {
+ it('imports under a partial `@/libs/swr` mock', () => {
+ expect(replicaSWRDriver).toBeDefined();
+ });
+});
diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.ts
new file mode 100644
index 00000000000..5645dbb4d67
--- /dev/null
+++ b/src/libs/replica/index.ts
@@ -0,0 +1,94 @@
+import {
+ definePagedReplica as defineCorePagedReplica,
+ type DefinePagedReplicaOptions,
+ defineReplica as defineCoreReplica,
+ type DefineReplicaOptions,
+ type ReplicaPagedData,
+ type ReplicaResource,
+ type ReplicaScope,
+ type ReplicaStorage,
+} from '@lobechat/replica';
+import {
+ createReplicaSlice as createCoreReplicaSlice,
+ type CreateReplicaSliceOptions,
+ createSWRDriver,
+} from '@lobechat/replica/zustand';
+
+import {
+ IndexedDBQueryProjectionStorage,
+ LocalStorageQueryProjectionStorage,
+} from '@/libs/queryProjectionStorage';
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { getCacheScope, isScopeTrusted, useCacheScope } from '@/libs/swr/useCacheScope';
+
+/**
+ * LobeHub wiring of `@lobechat/replica`: replicas are partitioned like the SWR
+ * cache (`${userId}:${workspaceId}`), persist to IndexedDB by default and
+ * fetch through the app's SWR hook (workspace-augmented keys, retry policy).
+ */
+
+export const cacheScope: ReplicaScope = {
+ canPersist: isScopeTrusted,
+ get: getCacheScope,
+ use: useCacheScope,
+};
+
+export type ReplicaStorageKind = 'indexedDB' | 'localStorage' | 'memory';
+
+type AppStorageOption<TData> = ReplicaStorageKind | ReplicaStorage<TData>;
+
+const resolveStorage =
+ <TData>(storage: AppStorageOption<TData> = 'indexedDB') =>
+ (namespace: string): ReplicaStorage<TData> | undefined => {
+ if (typeof storage === 'object') return storage;
+ if (storage === 'indexedDB') return new IndexedDBQueryProjectionStorage<TData>({ namespace });
+ if (storage === 'localStorage')
+ return new LocalStorageQueryProjectionStorage<TData>({ namespace });
+ return undefined;
+ };
+
+export const defineReplica = <TParams, TData, TFetched = TData>({
+ storage,
+ ...options
+}: Omit<DefineReplicaOptions<TParams, TData, TFetched>, 'storage'> & {
+ storage?: AppStorageOption<TData>;
+}) =>
+ defineCoreReplica<TParams, TData, TFetched>({
+ scope: cacheScope,
+ ...options,
+ storage: resolveStorage(storage),
+ });
+
+export const definePagedReplica = <
+ TParams,
+ TItem,
+ TCursor = number,
+ TData extends ReplicaPagedData<TItem, TCursor> = ReplicaPagedData<TItem, TCursor>,
+>({
+ storage,
+ ...options
+}: Omit<DefinePagedReplicaOptions<TParams, TItem, TCursor>, 'storage'> & {
+ storage?: AppStorageOption<TData>;
+}) =>
+ defineCorePagedReplica<TParams, TItem, TCursor, TData>({
+ scope: cacheScope,
+ ...options,
+ storage: resolveStorage(storage),
+ });
+
+// Resolve the SWR bindings per call, not at import: the topic store pulls this
+// module in eagerly, and test suites that mock `@/libs/swr` partially must
+// still be able to import it.
+export const replicaSWRDriver = createSWRDriver({
+ mutate: (match) => mutate(match),
+ useSWR: (key, fetcher, config) => useClientDataSWR(key, fetcher, config),
+});
+
+/** `createReplicaSlice` bound to the app's SWR driver. */
+export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
+ resource: ReplicaResource<TParams, TData, TFetched>,
+ options: Omit<CreateReplicaSliceOptions<TStore, TParams, TData, TFetched>, 'driver'>,
+) => createCoreReplicaSlice(resource, { driver: replicaSWRDriver, ...options });
+
+export * from '@lobechat/replica';
+export { recordLens, type ReplicaSyncResult } from '@lobechat/replica/zustand';
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 311d63ad850..c30e8d58603 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -123,12 +123,6 @@ export const isMessageListKey = (
// ---- topic --------------------------------------------------------------
export const topicKeys = {
- agentView: def('topic:agentView', (containerKey: string, opts: Record<string, unknown>) => [
- 'topic:agentView',
- containerKey,
- opts,
- ]),
- detail: def('topic:detail', (topicId: string) => ['topic:detail', topicId]),
list: def('topic:list', (containerKey: string, opts: Record<string, unknown>) => [
'topic:list',
containerKey,
diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts
new file mode 100644
index 00000000000..f47e4d8b8cb
--- /dev/null
+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts
@@ -0,0 +1,94 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ agentChatTopicListLoader,
+ PRE_PAINT_HYDRATE_TIMEOUT,
+ preHydrateTopicListForRoute,
+} from './topicListLoader';
+
+const preHydrateTopicListMock = vi.hoisted(() => vi.fn(async () => true));
+const getSidebarTopicListParamsMock = vi.hoisted(() => vi.fn());
+const builtinAgentIdMap = vi.hoisted(() => ({ inbox: 'agt_inbox' }) as Record<string, string>);
+
+vi.mock('@lobechat/builtin-agents', () => ({
+ BUILTIN_AGENT_SLUGS: { inbox: 'inbox' },
+}));
+
+vi.mock('@/hooks/chatTopicListQuery', () => ({
+ getSidebarTopicListParams: getSidebarTopicListParamsMock,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: { getState: () => ({ builtinAgentIdMap }) },
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ builtinAgentSelectors: {
+ getBuiltinAgentId: (slug: string) => (state: { builtinAgentIdMap: Record<string, string> }) =>
+ state.builtinAgentIdMap[slug],
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: { getState: () => ({ preHydrateTopicList: preHydrateTopicListMock }) },
+}));
+
+const loaderArgs = (aid?: string) => ({ params: aid ? { aid } : {} }) as never;
+
+describe('agent chat topic list loader', () => {
+ beforeEach(() => {
+ preHydrateTopicListMock.mockClear();
+ preHydrateTopicListMock.mockResolvedValue(true);
+ getSidebarTopicListParamsMock.mockReset();
+ getSidebarTopicListParamsMock.mockReturnValue({ agentId: 'agt_1', pageSize: 20 });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('seeds the persisted page for the route agent before the route commits', async () => {
+ getSidebarTopicListParamsMock.mockReturnValue({ agentId: 'agt_1', pageSize: 20 });
+
+ await expect(agentChatTopicListLoader(loaderArgs('agt_1'))).resolves.toBeNull();
+
+ expect(getSidebarTopicListParamsMock).toHaveBeenCalledWith({ agentId: 'agt_1' });
+ expect(preHydrateTopicListMock).toHaveBeenCalledWith({ agentId: 'agt_1', pageSize: 20 });
+ });
+
+ it('resolves a builtin slug to its agent id', async () => {
+ await preHydrateTopicListForRoute('inbox');
+
+ expect(getSidebarTopicListParamsMock).toHaveBeenCalledWith({ agentId: 'agt_inbox' });
+ });
+
+ it('skips entirely when the route names no agent', async () => {
+ await expect(agentChatTopicListLoader(loaderArgs())).resolves.toBeNull();
+
+ expect(getSidebarTopicListParamsMock).not.toHaveBeenCalled();
+ expect(preHydrateTopicListMock).not.toHaveBeenCalled();
+ });
+
+ it('does not block the route when the hydrate never resolves', async () => {
+ vi.useFakeTimers();
+ preHydrateTopicListMock.mockImplementation(() => new Promise(() => {}));
+
+ const pending = agentChatTopicListLoader(loaderArgs('agt_1'));
+ let settled = false;
+ void pending.then(() => {
+ settled = true;
+ });
+
+ await vi.advanceTimersByTimeAsync(PRE_PAINT_HYDRATE_TIMEOUT - 1);
+ expect(settled).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(pending).resolves.toBeNull();
+ });
+
+ it('never rejects the route when the hydrate fails', async () => {
+ preHydrateTopicListMock.mockRejectedValue(new Error('storage exploded'));
+
+ await expect(agentChatTopicListLoader(loaderArgs('agt_1'))).resolves.toBeNull();
+ });
+});
diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.ts
new file mode 100644
index 00000000000..81848733b20
--- /dev/null
+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts
@@ -0,0 +1,71 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import type { LoaderFunctionArgs } from 'react-router';
+
+import { getSidebarTopicListParams } from '@/hooks/chatTopicListQuery';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+
+const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));
+
+/**
+ * Upper bound for the pre-paint hydrate.
+ *
+ * The read itself is not the risk: measured on the real storage path, a warm
+ * IndexedDB read of the sidebar page (20 rows β‰ˆ 9 KB) is ~0.2–0.5 ms p50, the
+ * first read of a cold page with an existing database ~1–10 ms, and creating
+ * the database ~7–30 ms. The deadline only ever fires on a pathological storage
+ * stall, so a route transition never waits longer than this for it.
+ */
+export const PRE_PAINT_HYDRATE_TIMEOUT = 50;
+
+/** Resolve once `promise` settles or `ms` elapses β€” never rejects, never hangs. */
+const settleWithin = (promise: Promise<unknown>, ms: number): Promise<void> =>
+ new Promise((resolve) => {
+ const finish = () => {
+ clearTimeout(timer);
+ resolve();
+ };
+ const timer = setTimeout(finish, ms);
+ void Promise.resolve(promise).then(finish, finish);
+ });
+
+/**
+ * Builtin slugs (`inbox`, …) resolve from the store; an id passes through. A
+ * user-chosen slug needs a server lookup, so it resolves only after the route
+ * redirects to the real id and the loader runs again β€” hydrating under the slug
+ * key is a harmless miss.
+ */
+const resolveRouteAgentId = (routeAgentId?: string): string | undefined => {
+ if (!routeAgentId) return undefined;
+ if (!builtinAgentSlugs.has(routeAgentId)) return routeAgentId;
+
+ return builtinAgentSelectors.getBuiltinAgentId(routeAgentId)(useAgentStore.getState());
+};
+
+/**
+ * Seed the sidebar's persisted topic page for a route's agent.
+ *
+ * Route loaders run before React commits the new route, so this is the one place
+ * a local (async) read can still land pre-paint. Without it the sidebar mounts
+ * first and paints its loading skeleton until the in-tree hydrate resolves.
+ */
+export const preHydrateTopicListForRoute = async (routeAgentId?: string): Promise<void> => {
+ const agentId = resolveRouteAgentId(routeAgentId);
+ if (!agentId) return;
+
+ const params = getSidebarTopicListParams({ agentId });
+ if (!params) return;
+
+ await settleWithin(
+ useChatStore.getState().preHydrateTopicList(params),
+ PRE_PAINT_HYDRATE_TIMEOUT,
+ );
+};
+
+/** Loader for the agent chat routes (`/agent/:aid`, `/agent/:aid/:topicId`). */
+export const agentChatTopicListLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {
+ await preHydrateTopicListForRoute(params.aid);
+
+ return null;
+};
diff --git a/src/spa/router/agentChatTopicListLoader.ts b/src/spa/router/agentChatTopicListLoader.ts
new file mode 100644
index 00000000000..d44e6c8d1d4
--- /dev/null
+++ b/src/spa/router/agentChatTopicListLoader.ts
@@ -0,0 +1,14 @@
+import type { LoaderFunctionArgs } from 'react-router';
+
+/**
+ * Route-table entry for the agent chat pre-paint hydrate.
+ *
+ * The real loader imports the chat and agent stores. The route tables sit in the
+ * entry chunk's static graph, so importing it directly would pull both stores
+ * into the first screen; resolving it on first use keeps them in the agent
+ * route's lazy chunks, which load in parallel with this one.
+ */
+export const agentChatTopicListLoader = (args: LoaderFunctionArgs) =>
+ import('@/routes/(main)/agent/(chat)/topicListLoader').then((module) =>
+ module.agentChatTopicListLoader(args),
+ );
diff --git a/src/spa/router/agentChatTopicListLoader.wiring.test.ts b/src/spa/router/agentChatTopicListLoader.wiring.test.ts
new file mode 100644
index 00000000000..2115463a1a1
--- /dev/null
+++ b/src/spa/router/agentChatTopicListLoader.wiring.test.ts
@@ -0,0 +1,63 @@
+// @vitest-environment happy-dom
+import type { RouteObject } from 'react-router';
+import { describe, expect, it, vi } from 'vitest';
+
+import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
+
+import { agentChatTopicListLoader } from './agentChatTopicListLoader';
+import { desktopRoutes } from './desktopRouter.config';
+import { mobileRoutes } from './mobileRouter.config';
+
+const loaderModule = vi.hoisted(() => ({ evaluated: false }));
+
+// The real loader imports the chat and agent stores. Recording its evaluation
+// proves the route tables only reach it on first use: a static import from the
+// router would pull both stores into the entry chunk's first-screen graph.
+vi.mock('@/routes/(main)/agent/(chat)/topicListLoader', () => {
+ loaderModule.evaluated = true;
+ return { agentChatTopicListLoader: vi.fn(async () => null) };
+});
+
+const flatten = (routes: RouteObject[]): RouteObject[] =>
+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);
+
+/**
+ * The chat routes are the ones carrying the agent chat meta (index + `:topicId`);
+ * every other agent sub-route (docs, goals, profile, …) has its own meta.
+ */
+const chatRoutes = (routes: RouteObject[]) =>
+ flatten(routes).filter(
+ (route) => (route.handle as { meta?: unknown } | undefined)?.meta === agentRouteMeta,
+ );
+
+// The hydration itself is covered elsewhere; this guards the wiring, which is the
+// part a route-config refactor can silently drop β€” and dropping it looks exactly
+// like the flash it was added to remove.
+describe('agent chat topic list loader wiring', () => {
+ it('does not load the store-backed loader while the route tables load', () => {
+ expect(loaderModule.evaluated).toBe(false);
+ });
+
+ it('pre-hydrates the topic list on every desktop agent chat route', () => {
+ const routes = chatRoutes(desktopRoutes);
+
+ expect(routes.length).toBeGreaterThan(0);
+ expect(routes.map((route) => route.loader)).toEqual(routes.map(() => agentChatTopicListLoader));
+ });
+
+ it('pre-hydrates the topic list on the mobile agent chat routes too', () => {
+ const routes = chatRoutes(mobileRoutes);
+
+ expect(routes.length).toBeGreaterThan(0);
+ expect(routes.map((route) => route.loader)).toEqual(routes.map(() => agentChatTopicListLoader));
+ });
+
+ it('delegates to the real loader on first use', async () => {
+ const { agentChatTopicListLoader: realLoader } =
+ await import('@/routes/(main)/agent/(chat)/topicListLoader');
+ const args = { params: { aid: 'agt_1' } } as any;
+
+ await expect(agentChatTopicListLoader(args)).resolves.toBeNull();
+ expect(realLoader).toHaveBeenCalledWith(args);
+ });
+});
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 57f9b9f0f6e..923f8e51275 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -71,6 +71,7 @@ import {
} from '@/routes/(main)/group/features/routeMeta';
import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShellSkeleton';
import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
+import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';
import { NoRouteSkeleton, routeMeta, type RouteSkeletonProps } from '@/spa/router/routeMeta';
import { SettingsTabs } from '@/store/global/initialState';
import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
@@ -146,10 +147,12 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: agentChatElement,
handle: { meta: agentRouteMeta },
index: true,
+ loader: agentChatTopicListLoader,
},
{
element: agentChatElement,
handle: { meta: agentRouteMeta },
+ loader: agentChatTopicListLoader,
path: ':topicId',
},
],
diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsx
index 75a354213c5..7d28bf6157b 100644
--- a/src/spa/router/mobileRouter.config.tsx
+++ b/src/spa/router/mobileRouter.config.tsx
@@ -15,6 +15,7 @@ import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMe
import WorkspaceProviderRedirect from '@/features/WorkspaceSetting/ProviderRedirect';
import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
+import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';
import { routeMeta } from '@/spa/router/routeMeta';
import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
@@ -43,10 +44,12 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: mobileChatElement,
handle: { meta: agentRouteMeta },
index: true,
+ loader: agentChatTopicListLoader,
},
{
element: mobileChatElement,
handle: { meta: agentRouteMeta },
+ loader: agentChatTopicListLoader,
path: ':topicId',
},
{
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index a6dae3a920a..07d2a6ac82e 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -8,6 +8,7 @@ import { type Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LOADING_FLAT } from '@/const/message';
+import { cacheScope, REPLICA_INDEX_KEY, replicaKeys } from '@/libs/replica';
import { mutate } from '@/libs/swr';
import { aiChatService } from '@/services/aiChat';
import { chatService } from '@/services/chat';
@@ -24,6 +25,13 @@ import { useUserStore } from '@/store/user';
import { type ChatTopic } from '@/types/topic';
import { useChatStore } from '../../store';
+import { topicListResource } from './projection';
+
+// Revalidation is narrowed to the active identity scope.
+const topicListSyncKey = (containerKey: string, scope = cacheScope.get()) =>
+ replicaKeys.sync(topicListResource.name, topicListResource.version, scope, containerKey, {
+ pageSize: 20,
+ });
vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
const actual = await importOriginal<{ toast: Record<string, unknown> }>();
@@ -273,17 +281,18 @@ describe('topic action', () => {
// Check if mutate has been called with a matcher function
expect(mutate).toHaveBeenCalledWith(expect.any(Function));
- // Verify the matcher function works correctly
- // Key format: [SWR_USE_FETCH_TOPIC, containerKey, { isInbox, pageSize }]
+ // Verify the matcher function works correctly (local-first sync keys)
const matcherFn = (mutate as Mock).mock.calls[0][0];
const containerKey = `agent_${activeAgentId}`;
// Should match key with correct containerKey
- expect(matcherFn(['topic:list', containerKey, { isInbox: false, pageSize: 20 }])).toBe(true);
+ expect(matcherFn(topicListSyncKey(containerKey))).toBe(true);
// Should not match key with different containerKey
- expect(matcherFn(['topic:list', 'agent_other-id', { isInbox: false, pageSize: 20 }])).toBe(
- false,
- );
+ expect(matcherFn(topicListSyncKey('agent_other-id'))).toBe(false);
+ // Should not match another identity's sync key
+ expect(matcherFn(topicListSyncKey(containerKey, 'other-user:personal'))).toBe(false);
+ // The legacy SWR-persisted key is gone
+ expect(matcherFn(['topic:list', containerKey, { isInbox: false, pageSize: 20 }])).toBe(false);
// Should not match non-array keys
expect(matcherFn('some-string')).toBe(false);
// Should not match keys with wrong prefix
@@ -376,8 +385,8 @@ describe('topic action', () => {
});
const matcherFn = (mutate as Mock).mock.calls[0][0];
- expect(matcherFn(['topic:list', BUILDER_KEY, { pageSize: 20 }])).toBe(true);
- expect(matcherFn(['topic:list', topicMapKey({ agentId: 'edited-agent' }), {}])).toBe(false);
+ expect(matcherFn(topicListSyncKey(BUILDER_KEY))).toBe(true);
+ expect(matcherFn(topicListSyncKey(topicMapKey({ agentId: 'edited-agent' })))).toBe(false);
});
it('writes model and the re-pinned reasoning config in one request', async () => {
@@ -1029,12 +1038,11 @@ describe('topic action', () => {
const archived = { id: 'archived-topic', status: 'completed', title: 'Archived Topic' };
(topicService.getTopicDetail as Mock).mockResolvedValue(archived);
- const { result } = renderHook(() => useChatStore().useFetchTopicDetail('archived-topic'));
+ renderHook(() => useChatStore().useFetchTopicDetail('archived-topic'));
await waitFor(() => {
- expect(result.current.data).toEqual(archived);
+ expect(useChatStore.getState().topicDetailMap['archived-topic']).toEqual(archived);
});
- expect(useChatStore.getState().topicDetailMap['archived-topic']).toEqual(archived);
});
it('does not fetch when no topic id is given', () => {
@@ -1056,14 +1064,13 @@ describe('topic action', () => {
useChatStore().useFetchTopics(true, { agentId: sessionId }),
);
- // Wait for the hook to resolve and update the state
+ // Data is read from the store, never from the fetch hook.
await waitFor(() => {
- expect(result.current.data).toEqual({ items: topics, total: topics.length });
+ expect(
+ useChatStore.getState().topicDataMap[topicMapKey({ agentId: sessionId })]?.items,
+ ).toEqual(topics);
});
- // Verify topics are stored in topicDataMap with correct key
- expect(
- useChatStore.getState().topicDataMap[topicMapKey({ agentId: sessionId })]?.items,
- ).toEqual(topics);
+ expect(result.current).not.toHaveProperty('data');
});
describe('unread message prefetch', () => {
@@ -1238,17 +1245,10 @@ describe('topic action', () => {
const useFetchTopics = useChatStore.getState().useFetchTopics;
- const swrResponse = renderHook(() =>
+ renderHook(() =>
useFetchTopics(true, { agentId, excludeTriggers: ['cron', 'eval'], pageSize }),
);
- await waitFor(() => {
- expect(swrResponse.result.current.data).toEqual({
- items: refreshedFirstPage,
- total: 59,
- });
- });
-
await waitFor(() => {
const topicData = useChatStore.getState().topicDataMap[topicMapKey({ agentId })];
@@ -1305,17 +1305,10 @@ describe('topic action', () => {
});
const useFetchTopics = useChatStore.getState().useFetchTopics;
- const swrResponse = renderHook(() =>
+ renderHook(() =>
useFetchTopics(true, { agentId, excludeTriggers: ['cron', 'eval'], pageSize }),
);
- await waitFor(() => {
- expect(swrResponse.result.current.data).toEqual({
- items: refreshedFirstPage,
- total: 60,
- });
- });
-
await waitFor(() => {
const topicData = useChatStore.getState().topicDataMap[topicMapKey({ agentId })];
@@ -1365,13 +1358,7 @@ describe('topic action', () => {
});
const useFetchTopics = useChatStore.getState().useFetchTopics;
- const swrResponse = renderHook(() =>
- useFetchTopics(true, { agentId, excludeTriggers: ['cron'], pageSize }),
- );
-
- await waitFor(() => {
- expect(swrResponse.result.current.data).toEqual({ items: refreshedTopics, total: 20 });
- });
+ renderHook(() => useFetchTopics(true, { agentId, excludeTriggers: ['cron'], pageSize }));
await waitFor(() => {
const topicData = useChatStore.getState().topicDataMap[topicMapKey({ agentId })];
@@ -1421,13 +1408,7 @@ describe('topic action', () => {
});
const useFetchTopics = useChatStore.getState().useFetchTopics;
- const swrResponse = renderHook(() =>
- useFetchTopics(true, { agentId, excludeStatuses: ['completed'], pageSize }),
- );
-
- await waitFor(() => {
- expect(swrResponse.result.current.data).toEqual({ items: refreshedTopics, total: 20 });
- });
+ renderHook(() => useFetchTopics(true, { agentId, excludeStatuses: ['completed'], pageSize }));
await waitFor(() => {
const topicData = useChatStore.getState().topicDataMap[topicMapKey({ agentId })];
@@ -2245,7 +2226,7 @@ describe('topic action', () => {
expect(topicData.hasMore).toBe(false);
});
});
- describe('persisted topic-list cache write-through', () => {
+ describe('persisted topic-list projection', () => {
const setupBucket = (agentId: string) => {
const containerKey = topicMapKey({ agentId });
const { result } = renderHook(() => useChatStore());
@@ -2265,13 +2246,16 @@ describe('topic action', () => {
},
});
});
- vi.mocked(mutate).mockClear();
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ const set = vi.spyOn(topicListResource.storage!, 'set').mockResolvedValue();
+ // Data rows only: the per-scope index of persisted rows is bookkeeping.
+ const persisted = () => set.mock.calls.filter(([key]) => key.queryKey !== REPLICA_INDEX_KEY);
- return { containerKey, result };
+ return { containerKey, persisted, result };
};
- it('mirrors a run-end status patch into the cached topic list', () => {
- const { containerKey, result } = setupBucket('agent-write-through');
+ it('persists a run-end status patch so a reload does not repaint the spinner', async () => {
+ const { containerKey, persisted, result } = setupBucket('agent-write-through');
act(() => {
result.current.internal_dispatchTopic({
@@ -2281,50 +2265,144 @@ describe('topic action', () => {
});
});
- expect(mutate).toHaveBeenCalledTimes(1);
- const [matcher, updater, options] = vi.mocked(mutate).mock.calls[0] as [
- (key: unknown) => boolean,
- (cached?: { items: ChatTopic[]; total: number }) => unknown,
- unknown,
- ];
+ await waitFor(() => expect(persisted()).toHaveLength(1));
+ const [key, projection] = persisted()[0];
+ expect(key.queryKey).toBe(containerKey);
+ expect(projection.data.items).toMatchObject([{ id: 'topic-1', status: 'unread' }]);
+ // Transient paging flags never reach storage.
+ expect(projection.data).not.toHaveProperty('isLoadingMore');
+ });
- expect(options).toEqual({ revalidate: false });
- // Only this container's list keys β€” the agent-view key and other
- // containers keep their own cached pages.
- expect(matcher(['topic:list', containerKey, { pageSize: 20 }])).toBe(true);
- expect(matcher(['topic:list', topicMapKey({ agentId: 'other-agent' }), {}])).toBe(false);
- expect(matcher(['topic:agentView', containerKey, {}])).toBe(false);
+ it('does not persist client-only optimistic rows', async () => {
+ const { persisted, result } = setupBucket('agent-write-through-add');
- const cached = {
- items: [{ id: 'topic-1', status: 'running', title: 'Topic 1' }] as ChatTopic[],
- total: 1,
- };
- expect(updater(cached)).toMatchObject({
- items: [{ id: 'topic-1', status: 'unread' }],
- total: 1,
+ act(() => {
+ result.current.internal_dispatchTopic({
+ optimistic: true,
+ type: 'addTopic',
+ value: { id: 'topic-optimistic', title: 'New' },
+ });
});
+ expect(persisted()).toHaveLength(0);
- // A cached page without the patched row (or no entry at all) stays as-is,
- // so the mutate cannot create a bogus entry.
- const otherPage = { items: [{ id: 'topic-2', status: 'active' }] as ChatTopic[], total: 1 };
- expect(updater(otherPage)).toBe(otherPage);
- expect(updater(undefined)).toBeUndefined();
+ // A later confirmed patch persists the bucket without the placeholder.
+ act(() => {
+ result.current.internal_dispatchTopic({
+ id: 'topic-1',
+ type: 'updateTopic',
+ value: { status: 'unread' },
+ });
+ });
+ await waitFor(() => expect(persisted()).toHaveLength(1));
+ expect(persisted()[0][1].data.items.map((item: ChatTopic) => item.id)).toEqual(['topic-1']);
});
- it('does not mirror client-only optimistic rows', () => {
- const { result } = setupBucket('agent-write-through-add');
+ it('does not create a bucket when patching an unloaded container', () => {
+ const { result } = setupBucket('agent-loaded');
act(() => {
result.current.internal_dispatchTopic({
- optimistic: true,
- type: 'addTopic',
- value: { id: 'topic-optimistic', title: 'New' },
+ agentId: 'agent-not-loaded',
+ id: 'topic-x',
+ type: 'updateTopic',
+ value: { status: 'unread' },
});
});
- expect(mutate).not.toHaveBeenCalled();
+ expect(
+ useChatStore.getState().topicDataMap[topicMapKey({ agentId: 'agent-not-loaded' })],
+ ).toBeUndefined();
});
});
+
+ describe('optimistic topic updates', () => {
+ const seed = (agentId: string) => {
+ const containerKey = topicMapKey({ agentId });
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ topicDataMap: {
+ [containerKey]: {
+ currentPage: 0,
+ hasMore: false,
+ items: [{ favorite: false, id: 'topic-1', title: 'Old' }] as ChatTopic[],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ });
+ });
+ return containerKey;
+ };
+
+ it('shows a rename immediately and keeps it after the server confirms', async () => {
+ const containerKey = seed('agent-rename');
+ let resolveUpdate!: () => void;
+ vi.mocked(topicService.updateTopic).mockImplementation(
+ () => new Promise((resolve) => (resolveUpdate = () => resolve(undefined as any))),
+ );
+
+ let pending!: Promise<void>;
+ act(() => {
+ pending = useChatStore.getState().updateTopicTitle('topic-1', 'New');
+ });
+ expect(useChatStore.getState().topicDataMap[containerKey].items[0].title).toBe('New');
+
+ await act(async () => {
+ resolveUpdate();
+ await pending;
+ });
+ expect(useChatStore.getState().topicDataMap[containerKey].items[0].title).toBe('New');
+ expect(useChatStore.getState().topicListReplica.entries[containerKey].pending).toEqual([]);
+ });
+
+ it('rolls a failed favorite back instead of leaving the optimistic value', async () => {
+ const containerKey = seed('agent-favorite-fail');
+ vi.mocked(topicService.updateTopic).mockRejectedValue(new Error('offline'));
+
+ await act(async () => {
+ await expect(useChatStore.getState().favoriteTopic('topic-1', true)).rejects.toThrow(
+ 'offline',
+ );
+ });
+
+ expect(useChatStore.getState().topicDataMap[containerKey].items[0].favorite).toBe(false);
+ });
+
+ it('keeps an in-flight rename when a background revalidation lands', async () => {
+ const agentId = 'agent-rename-revalidate';
+ const containerKey = seed(agentId);
+ let resolveUpdate!: () => void;
+ vi.mocked(topicService.updateTopic).mockImplementation(
+ () => new Promise((resolve) => (resolveUpdate = () => resolve(undefined as any))),
+ );
+ (topicService.getTopics as Mock).mockResolvedValue({
+ items: [{ favorite: false, id: 'topic-1', title: 'Old' }],
+ total: 1,
+ });
+
+ let pending!: Promise<void>;
+ act(() => {
+ pending = useChatStore.getState().updateTopicTitle('topic-1', 'New');
+ });
+
+ renderHook(() => useChatStore().useFetchTopics(true, { agentId, pageSize: 20 }));
+ await waitFor(() => expect(topicService.getTopics).toHaveBeenCalled());
+ await waitFor(() =>
+ expect(useChatStore.getState().topicListReplica.entries[containerKey].source).toBe(
+ 'server',
+ ),
+ );
+ // The stale server row is rebased under the pending rename.
+ expect(useChatStore.getState().topicDataMap[containerKey].items[0].title).toBe('New');
+
+ await act(async () => {
+ resolveUpdate();
+ await pending;
+ });
+ });
+ });
+
describe('loadMoreAgentTopicsView', () => {
it('records a pagination error without clearing existing topics or hasMore', async () => {
const { result } = renderHook(() => useChatStore());
@@ -2516,6 +2594,56 @@ describe('topic action', () => {
).rejects.toThrow('rename failed');
});
});
+
+ it('propagates a topic change to the sidebar, management page and detail resources', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = 'agent-entity';
+ const key = topicMapKey({ agentId });
+ const topic = { favorite: false, id: 'topic-entity', title: 'Topic' } as ChatTopic;
+ const bucket = { currentPage: 0, hasMore: false, items: [topic], pageSize: 20, total: 1 };
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ agentTopicsViewMap: { [key]: { ...bucket, withDetails: true } },
+ topicDataMap: { [key]: bucket },
+ topicDetailMap: { [topic.id]: topic },
+ });
+ });
+ vi.spyOn(result.current, 'refreshTopic').mockResolvedValue(undefined);
+ const server = vi.spyOn(topicService, 'updateTopic');
+
+ // A failed write rolls back in every resource.
+ server.mockRejectedValueOnce(new Error('rename failed'));
+ await act(async () => {
+ await expect(
+ result.current.internal_updateTopic(topic.id, { title: 'Renamed' }),
+ ).rejects.toThrow('rename failed');
+ });
+ let state = useChatStore.getState();
+ expect(state.topicDataMap[key].items[0].title).toBe('Topic');
+ expect(state.agentTopicsViewMap[key].items[0].title).toBe('Topic');
+ expect(state.topicDetailMap[topic.id].title).toBe('Topic');
+
+ // A confirmed write lands in all three.
+ server.mockResolvedValueOnce(undefined as any);
+ await act(async () => {
+ await result.current.internal_updateTopic(topic.id, { favorite: true });
+ });
+ state = useChatStore.getState();
+ expect(state.topicDataMap[key].items[0].favorite).toBe(true);
+ expect(state.agentTopicsViewMap[key].items[0].favorite).toBe(true);
+ expect(state.topicDetailMap[topic.id].favorite).toBe(true);
+
+ // A delete reaches all three, with list totals adjusted.
+ act(() => {
+ result.current.internal_dispatchTopic({ id: topic.id, type: 'deleteTopic' });
+ });
+ state = useChatStore.getState();
+ expect(state.topicDataMap[key]).toMatchObject({ items: [], total: 0 });
+ expect(state.agentTopicsViewMap[key]).toMatchObject({ items: [], total: 0 });
+ expect(state.topicDetailMap[topic.id]).toBeUndefined();
+ });
});
describe('cleanupStaleRunningTopics', () => {
it('should mark stale running topics active when no alive operation exists', async () => {
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index f35731b4b16..a76e2026189 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -22,8 +22,16 @@ import { type SWRResponse } from 'swr';
import useSWR from 'swr';
import { LOADING_FLAT } from '@/const/message';
+import {
+ createReplicaSlice,
+ linkReplicaEntity,
+ recordLens,
+ type ReplicaPageResult,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
import { cronKeys, deviceKeys, topicKeys } from '@/libs/swr/keys';
+import { getCacheScope } from '@/libs/swr/useCacheScope';
import { aiChatService } from '@/services/aiChat';
import { type GitLinkedPRSummary, gitService } from '@/services/git';
import { messageService } from '@/services/message';
@@ -56,18 +64,21 @@ import {
userGeneralSettingsSelectors,
userProfileSelectors,
} from '@/store/user/selectors';
-import {
- type ChatTopic,
- type ChatTopicStatus,
- type CreateTopicParams,
- type TopicQuerySortBy,
-} from '@/types/topic';
+import { type ChatTopic, type ChatTopicStatus, type CreateTopicParams } from '@/types/topic';
import { setNamespace } from '@/utils/storeDebug';
import { displayMessageSelectors } from '../message/selectors';
import { type TopicData } from './initialState';
+import {
+ applyTopicDispatchToBucket,
+ normalizeTopicListParams,
+ type TopicAgentViewParams,
+ topicAgentViewResource,
+ topicDetailResource,
+ type TopicListParams,
+ topicListResource,
+} from './projection';
import { type ChatTopicDispatch } from './reducer';
-import { topicReducer } from './reducer';
import { topicSelectors } from './selectors';
const n = setNamespace('t');
@@ -82,6 +93,18 @@ const STALE_RUNNING_TOPIC_QUERY_PAGE_SIZE = 500;
*/
const UNREAD_TOPIC_PREFETCH_LIMIT = 5;
+/**
+ * Entity patch shared by every topic resource: merge, and bump `updatedAt`
+ * only on a real change (same reference otherwise, so nothing re-renders).
+ */
+const patchTopic =
+ (value: Partial<ChatTopic>) =>
+ (topic: ChatTopic): ChatTopic => {
+ const merged = { ...topic, ...value };
+ // TODO: updatedAt type needs to be changed to Date later
+ return isEqual(topic, merged) ? topic : ({ ...merged, updatedAt: new Date() } as any);
+ };
+
type CronTopicsGroupWithJobInfo = {
cronJob: unknown;
cronJobId: string;
@@ -191,10 +214,74 @@ export class ChatTopicActionImpl {
#summarizingTopicTitleIds = new Set<string>();
+ /**
+ * Three local-first resources over the same entity, each owning ONE store
+ * location (selectors keep reading those maps):
+ * - `#topicList`: sidebar pages β†’ `topicDataMap[containerKey]`
+ * - `#topicAgentView`: management page (`withDetails`, larger pages) β†’
+ * `agentTopicsViewMap[containerKey]`
+ * - `#topicDetail`: by-id fallback β†’ `topicDetailMap[topicId]`
+ * `#topicEntity` fans a topic-level change (patch / delete / optimistic
+ * write) out to whichever of them currently hold that topic.
+ */
+ readonly #topicList;
+ readonly #topicAgentView;
+ readonly #topicDetail;
+ readonly #topicEntity;
+
constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
void _api;
this.#set = set;
this.#get = get;
+ // In-flight first-send rows: kept across refetches, never persisted.
+ const isClientOnly = (topic: ChatTopic) => get().creatingTopicIds.includes(topic.id);
+ // The page-size expansion flag is transient UI state.
+ const toPersisted = ({ isExpandingPageSize: _expanding, ...data }: TopicData) => data;
+
+ this.#topicList = createReplicaSlice(topicListResource, {
+ actionPrefix: n('topicList'),
+ fetcher: this.#fetchTopicListPage,
+ get,
+ isClientOnly,
+ set,
+ stateKey: 'topicListReplica',
+ toPersisted,
+ view: recordLens<ChatStore, TopicData>('topicDataMap'),
+ viewFields: ({ excludeStatuses, excludeTriggers, isInbox, sortBy, withDetails }) => ({
+ excludeStatuses,
+ excludeTriggers,
+ isInbox: Boolean(isInbox),
+ sortBy,
+ withDetails,
+ }),
+ });
+ this.#topicAgentView = createReplicaSlice(topicAgentViewResource, {
+ actionPrefix: n('topicAgentView'),
+ fetcher: this.#fetchAgentViewPage,
+ get,
+ isClientOnly,
+ set,
+ stateKey: 'agentTopicsViewReplica',
+ toPersisted,
+ view: recordLens<ChatStore, TopicData>('agentTopicsViewMap'),
+ viewFields: ({ withDetails }) => ({ withDetails }),
+ });
+ this.#topicDetail = createReplicaSlice(topicDetailResource, {
+ actionPrefix: n('topicDetail'),
+ entity: { getId: (topic) => topic.id },
+ fetcher: (topicId) => topicService.getTopicDetail(topicId),
+ get,
+ // A missing topic keeps whatever is cached (the list may still hold it).
+ merge: (topic, confirmed) => (!topic || isEqual(topic, confirmed) ? undefined : topic),
+ set,
+ stateKey: 'topicDetailReplica',
+ view: recordLens<ChatStore, ChatTopic>('topicDetailMap'),
+ });
+ this.#topicEntity = linkReplicaEntity<ChatTopic>([
+ this.#topicList,
+ this.#topicAgentView,
+ this.#topicDetail,
+ ]);
}
#resolveTopicLinkedPullRequestRefreshParams = (
@@ -543,7 +630,10 @@ export class ChatTopicActionImpl {
provider: string;
},
): Promise<void> => {
- const containerKey = topicSelectors.getTopicContainerKeyById(id)(this.#get());
+ const { activeAgentId, activeGroupId } = this.#get();
+ const containerKey =
+ topicSelectors.getTopicContainerKeyById(id)(this.#get()) ??
+ topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
const previous = topicSelectors.getTopicById(id)(this.#get());
const { reasoningConfig: _stale, ...rest } = previous?.metadata ?? {};
this.#get().internal_dispatchTopic({
@@ -695,7 +785,10 @@ export class ChatTopicActionImpl {
id: string,
metadata: Pick<ChatTopicMetadata, 'heteroEffort' | 'reasoningConfig'>,
): Promise<void> => {
- const containerKey = topicSelectors.getTopicContainerKeyById(id)(this.#get());
+ const { activeAgentId, activeGroupId } = this.#get();
+ const containerKey =
+ topicSelectors.getTopicContainerKeyById(id)(this.#get()) ??
+ topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
const previous = topicSelectors.getTopicById(id)(this.#get());
if (!previous) return;
this.#get().internal_dispatchTopic({
@@ -1192,159 +1285,93 @@ export class ChatTopicActionImpl {
await summaryTopicTitle(id, messages);
};
- useFetchTopics = (
- enable: boolean,
- {
- agentId,
- excludeStatuses,
- excludeTriggers,
- groupId,
- pageSize: customPageSize,
- isInbox,
- sortBy,
- withDetails,
- }: {
- agentId?: string;
- excludeStatuses?: string[];
- excludeTriggers?: string[];
- groupId?: string;
- isInbox?: boolean;
- pageSize?: number;
- sortBy?: TopicQuerySortBy;
- withDetails?: boolean;
- } = {},
- ): SWRResponse<{ items: ChatTopic[]; total: number }> => {
- const pageSize = customPageSize || 20;
- const effectiveExcludeTriggers =
- excludeTriggers && excludeTriggers.length > 0 ? excludeTriggers : undefined;
- const effectiveExcludeStatuses =
- excludeStatuses && excludeStatuses.length > 0 ? excludeStatuses : undefined;
- // Use topicMapKey to generate the container key for topic data map
+ /**
+ * One sidebar page (`cursor` = page index, `undefined` = head). The head
+ * page also drives the page-size-expansion flag and the unread prefetch.
+ */
+ #fetchTopicListPage = async (
+ { agentId, groupId, pageSize, ...query }: TopicListParams,
+ cursor?: number,
+ ): Promise<ReplicaPageResult<ChatTopic, number>> => {
const containerKey = topicMapKey({ agentId, groupId });
- const hasValidContainer = !!(groupId || agentId);
-
- return useClientDataSWRWithSync<{ items: ChatTopic[]; total: number }>(
- enable && hasValidContainer
- ? topicKeys.list(containerKey, {
- isInbox,
- pageSize,
- ...(effectiveExcludeTriggers ? { excludeTriggers: effectiveExcludeTriggers } : {}),
- ...(effectiveExcludeStatuses ? { excludeStatuses: effectiveExcludeStatuses } : {}),
- ...(sortBy ? { sortBy } : {}),
- ...(withDetails ? { withDetails: true } : {}),
- })
- : null,
- async () => {
- // agentId, groupId, isInbox, pageSize come from the outer scope closure
- if (!agentId && !groupId) return { items: [], total: 0 };
-
- const currentData = this.#get().topicDataMap[containerKey];
- const lastPageSize = currentData?.pageSize;
- const hasExistingItems = (currentData?.items?.length || 0) > 0;
-
- // Only treat as "expanding page size" when user actually increases pageSize,
- // not when SWR revalidates or when total items < pageSize.
- const isExpanding =
- hasExistingItems && typeof lastPageSize === 'number' && pageSize > lastPageSize;
- if (isExpanding) {
- this.#get().internal_updateTopicData(containerKey, { isExpandingPageSize: true });
- }
+ const isHead = cursor === undefined;
+ const currentData = this.#get().topicDataMap[containerKey];
+ const lastPageSize = currentData?.pageSize;
+
+ // Only treat as "expanding page size" when user actually increases pageSize,
+ // not when SWR revalidates or when total items < pageSize.
+ const isExpanding =
+ isHead &&
+ (currentData?.items?.length || 0) > 0 &&
+ typeof lastPageSize === 'number' &&
+ pageSize > lastPageSize;
+ if (isExpanding)
+ this.#get().internal_updateTopicData(containerKey, { isExpandingPageSize: true });
- const result = await topicService.getTopics({
+ try {
+ const result = await topicService.getTopics({
+ agentId,
+ current: cursor ?? 0,
+ groupId,
+ pageSize,
+ ...query,
+ });
+ const items = this.#applyPendingStatusWrites(result.items, 'server');
+ if (isHead)
+ this.#prefetchUnreadTopicMessages(items, this.#get().topicDataMap[containerKey]?.items, {
agentId,
- current: 0,
- excludeStatuses: effectiveExcludeStatuses,
- excludeTriggers: effectiveExcludeTriggers,
groupId,
- isInbox,
- pageSize,
- sortBy,
- withDetails,
});
+ return { items, total: result.total };
+ } finally {
+ if (isExpanding)
+ this.#get().internal_updateTopicData(containerKey, { isExpandingPageSize: false });
+ }
+ };
- // Reset expanding state after fetch completes
- if (isExpanding) {
- this.#get().internal_updateTopicData(containerKey, { isExpandingPageSize: false });
- }
+ #fetchAgentViewPage = async (
+ { agentId, pageSize, withDetails }: TopicAgentViewParams,
+ cursor?: number,
+ ): Promise<ReplicaPageResult<ChatTopic, number>> => {
+ const result = await topicService.getTopics({
+ agentId,
+ current: cursor ?? 0,
+ pageSize,
+ withDetails,
+ });
+ return {
+ items: this.#applyPendingStatusWrites(result.items, 'server'),
+ total: result.total,
+ };
+ };
- return { ...result, items: this.#applyPendingStatusWrites(result.items, 'server') };
- },
- {
- // onData: responsible for state updates (fires for both cached and fresh data)
- onData: (result) => {
- if (!hasValidContainer) return;
-
- const { total: totalCount } = result;
-
- const currentData = this.#get().topicDataMap[containerKey];
- // `result` can be a cached response or a list already normalized by
- // the fetcher. Neither proves the server observed the pending write.
- const topics = this.#reconcileFetchedTopics(result.items, currentData?.items, 'cache');
-
- // Fire BEFORE the no-change early return below: on a cold boot the
- // cached list arrives with no `currentData`, and that first delivery
- // is exactly the sweep that must warm app-closed-while-running runs.
- this.#prefetchUnreadTopicMessages(topics, currentData?.items, { agentId, groupId });
-
- const isRefreshingExpandedList =
- !!currentData &&
- currentData.currentPage > 0 &&
- currentData.pageSize === pageSize &&
- Boolean(currentData.isInbox) === Boolean(isInbox) &&
- isEqual(currentData.excludeStatuses, effectiveExcludeStatuses) &&
- isEqual(currentData.excludeTriggers, effectiveExcludeTriggers);
-
- const nextItems = isRefreshingExpandedList
- ? (() => {
- const visibleCount = Math.min(currentData.items.length, totalCount);
- const topicIds = new Set(topics.map((item) => item.id));
-
- return [
- ...topics,
- ...currentData.items.filter((topic) => !topicIds.has(topic.id)),
- ].slice(0, visibleCount);
- })()
- : topics;
-
- const hasMore = totalCount > nextItems.length;
-
- // no need to update map if the current key's data exists and is the same
- if (
- currentData &&
- isEqual(nextItems, currentData.items) &&
- currentData.total === totalCount &&
- isEqual(currentData.excludeStatuses, effectiveExcludeStatuses) &&
- isEqual(currentData.excludeTriggers, effectiveExcludeTriggers)
- ) {
- return;
- }
+ /**
+ * Fetch orchestration for a container's topic list. Hydrates the persisted
+ * projection, then revalidates; results land in `topicDataMap` β€” read them
+ * through `topicSelectors`, never from this hook.
+ */
+ useFetchTopics = (enable: boolean, params: Partial<TopicListParams> = {}): ReplicaSyncResult => {
+ return this.#topicList.useSync(normalizeTopicListParams(params), { enabled: enable });
+ };
- this.#set(
- {
- topicDataMap: {
- ...this.#get().topicDataMap,
- [containerKey]: {
- currentPage: isRefreshingExpandedList ? currentData.currentPage : 0,
- excludeStatuses: effectiveExcludeStatuses,
- excludeTriggers: effectiveExcludeTriggers,
- hasMore,
- isInbox: Boolean(isInbox),
- isExpandingPageSize: false,
- isLoadingMore: false,
- loadMoreError: undefined,
- items: nextItems,
- pageSize,
- total: totalCount,
- withDetails,
- },
- },
- },
- false,
- n('useFetchTopics(onData)', { containerKey }),
- );
- },
- },
- );
+ /**
+ * Seed the sidebar's persisted page for a session before its first paint.
+ *
+ * Called from the agent route loader, where the route's agent is known but the
+ * stores still hold the previously active one. Best-effort by contract: a miss
+ * (nothing persisted for this key + query) is not an error, and the caller
+ * bounds the wait β€” everything else still flows through `useSync`.
+ */
+ preHydrateTopicList = async (params: Partial<TopicListParams>): Promise<boolean> => {
+ const normalized = normalizeTopicListParams(params);
+ if (!normalized) return false;
+
+ const scope = getCacheScope();
+ // The slot may still hold the previous identity's rows (a session that ended
+ // before the identity round-trip landed); drop them before seeding this one.
+ this.#topicList.ensureScope(scope);
+
+ return this.#topicList.hydrate(normalized, scope);
};
/**
@@ -1355,289 +1382,71 @@ export class ChatTopicActionImpl {
* in `topicDetailMap`, which `currentActiveTopic` / `getTopicById` read as
* a fallback. Pass `undefined` to disable the fetch.
*/
- useFetchTopicDetail = (topicId?: string | null): SWRResponse<ChatTopic | null> =>
- useClientDataSWRWithSync<ChatTopic | null>(
- topicId ? topicKeys.detail(topicId) : null,
- () => topicService.getTopicDetail(topicId!),
- {
- onData: (topic) => {
- if (!topic) return;
-
- const currentMap = this.#get().topicDetailMap;
- if (isEqual(currentMap[topic.id], topic)) return;
-
- this.#set(
- { topicDetailMap: { ...currentMap, [topic.id]: topic } },
- false,
- n('useFetchTopicDetail(onData)', { topicId: topic.id }),
- );
- },
- },
- );
+ useFetchTopicDetail = (topicId?: string | null): ReplicaSyncResult =>
+ this.#topicDetail.useSync(topicId || null);
/**
- * Topic fetch dedicated to the Agent Topics management page.
- * Lives in its own SWR key + state bucket so the heavier `withDetails`
- * payload doesn't collide with the sidebar's cheap fetch β€” sharing one
- * bucket meant whichever response landed last clobbered the other.
+ * Topic fetch dedicated to the Agent Topics management page. Its own
+ * resource and view (`agentTopicsViewMap`) so the heavier `withDetails`
+ * payload never collides with the sidebar's cheap fetch. Read the rows
+ * through `topicSelectors.agentTopicsView*`, never from this hook.
*/
useFetchAgentTopicsView = (
enable: boolean,
{
agentId,
- pageSize: customPageSize,
+ pageSize,
withDetails,
}: {
agentId?: string;
pageSize?: number;
withDetails?: boolean;
} = {},
- ): SWRResponse<{ items: ChatTopic[]; total: number }> => {
- const pageSize = customPageSize || 30;
- const containerKey = topicMapKey({ agentId });
- const hasValidAgent = !!agentId;
-
- return useClientDataSWRWithSync<{ items: ChatTopic[]; total: number }>(
- enable && hasValidAgent
- ? topicKeys.agentView(containerKey, {
- pageSize,
- ...(withDetails ? { withDetails: true } : {}),
- })
- : null,
- async () => {
- if (!agentId) return { items: [], total: 0 };
-
- const result = await topicService.getTopics({
- agentId,
- current: 0,
- pageSize,
- withDetails,
- });
-
- return { ...result, items: this.#applyPendingStatusWrites(result.items, 'server') };
- },
- {
- onData: (result) => {
- if (!hasValidAgent) return;
- const { total: totalCount } = result;
-
- const currentData = this.#get().agentTopicsViewMap[containerKey];
- const topics = this.#reconcileFetchedTopics(result.items, currentData?.items, 'cache');
-
- // Preserve appended pages on refresh β€” same convention as
- // `useFetchTopics` so the user keeps their scroll position after
- // an SWR revalidation.
- const isRefreshingExpandedList =
- !!currentData && currentData.currentPage > 0 && currentData.pageSize === pageSize;
-
- const nextItems = isRefreshingExpandedList
- ? (() => {
- const visibleCount = Math.min(currentData.items.length, totalCount);
- const topicIds = new Set(topics.map((item) => item.id));
- return [
- ...topics,
- ...currentData.items.filter((topic) => !topicIds.has(topic.id)),
- ].slice(0, visibleCount);
- })()
- : topics;
-
- const hasMore = totalCount > nextItems.length;
-
- if (
- currentData &&
- isEqual(nextItems, currentData.items) &&
- currentData.total === totalCount
- ) {
- return;
- }
-
- this.#set(
- {
- agentTopicsViewMap: {
- ...this.#get().agentTopicsViewMap,
- [containerKey]: {
- currentPage: isRefreshingExpandedList ? currentData.currentPage : 0,
- hasMore,
- isExpandingPageSize: false,
- isLoadingMore: false,
- loadMoreError: undefined,
- items: nextItems,
- pageSize,
- total: totalCount,
- withDetails,
- },
- },
- },
- false,
- n('useFetchAgentTopicsView(onData)', { containerKey }),
- );
- },
- },
+ ): ReplicaSyncResult =>
+ this.#topicAgentView.useSync(
+ agentId ? { agentId, pageSize: pageSize || 30, withDetails: withDetails || undefined } : null,
+ { enabled: enable },
);
- };
loadMoreAgentTopicsView = async (): Promise<void> => {
- const { activeAgentId, agentTopicsViewMap } = this.#get();
+ const { activeAgentId } = this.#get();
if (!activeAgentId) return;
-
const key = topicMapKey({ agentId: activeAgentId });
- const currentData = agentTopicsViewMap[key];
- if (!currentData || currentData.isLoadingMore) return;
-
- const nextPage = (currentData.currentPage || 0) + 1;
- const pageSize = currentData.pageSize;
- const withDetails = currentData.withDetails;
-
- this.#set(
- {
- agentTopicsViewMap: {
- ...agentTopicsViewMap,
- [key]: { ...currentData, isLoadingMore: true, loadMoreError: undefined },
- },
- },
- false,
- n('loadMoreAgentTopicsView(start)'),
- );
-
- try {
- const result = await topicService.getTopics({
- agentId: activeAgentId,
- current: nextPage,
- pageSize,
- withDetails,
- });
-
- const topics = this.#applyPendingStatusWrites(result.items, 'server');
- const nextItems = [...currentData.items, ...topics];
- const hasMore = result.total > nextItems.length;
-
- this.#set(
- {
- agentTopicsViewMap: {
- ...this.#get().agentTopicsViewMap,
- [key]: {
- ...currentData,
- currentPage: nextPage,
- hasMore,
- isLoadingMore: false,
- loadMoreError: undefined,
- items: nextItems,
- total: result.total,
- },
- },
- },
- false,
- n('loadMoreAgentTopicsView(success)'),
- );
- } catch (error) {
- this.#set(
- {
- agentTopicsViewMap: {
- ...this.#get().agentTopicsViewMap,
- [key]: {
- ...this.#get().agentTopicsViewMap[key]!,
- isLoadingMore: false,
- loadMoreError: error,
- },
- },
- },
- false,
- n('loadMoreAgentTopicsView(error)'),
- );
- }
+ const currentData = this.#get().agentTopicsViewMap[key];
+ await this.#topicAgentView.loadMore(key, {
+ agentId: activeAgentId,
+ pageSize: currentData?.pageSize || 30,
+ withDetails: currentData?.withDetails,
+ });
};
refreshAgentTopicsView = async (): Promise<void> => {
const { activeAgentId } = this.#get();
if (!activeAgentId) return;
- const containerKey = topicMapKey({ agentId: activeAgentId });
- await mutate(
- (key) => Array.isArray(key) && key[0] === topicKeys.agentView.root && key[1] === containerKey,
- );
+ await this.#topicAgentView.revalidate(topicMapKey({ agentId: activeAgentId }));
};
+ /**
+ * Next sidebar page with the params of the loaded head page. A bucket
+ * seeded outside `useFetchTopics` (e.g. `internal_updateTopics`) pages with
+ * its own descriptors.
+ */
loadMoreTopics = async (): Promise<void> => {
const { activeAgentId, activeGroupId, topicDataMap } = this.#get();
+ if (!activeAgentId && !activeGroupId) return;
const key = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
const currentData = topicDataMap[key];
- if ((!activeAgentId && !activeGroupId) || currentData?.isLoadingMore) return;
-
- const currentPage = currentData?.currentPage || 0;
- const nextPage = currentPage + 1;
-
- this.#set(
- {
- topicDataMap: {
- ...topicDataMap,
- [key]: { ...currentData!, isLoadingMore: true, loadMoreError: undefined },
- },
- },
- false,
- n('loadMoreTopics(start)'),
- );
-
- try {
- const pageSize = useGlobalStore.getState().status.topicPageSize || 20;
- const excludeTriggers = currentData?.excludeTriggers;
- const excludeStatuses = currentData?.excludeStatuses;
- // Carry `withDetails` from the initial fetch so subsequent pages have
- // the same column shape β€” otherwise the management page would mix
- // detail-rich rows with bare rows after scrolling.
- const withDetails = currentData?.withDetails;
- const result = await topicService.getTopics({
- agentId: activeAgentId,
- current: nextPage,
- excludeStatuses,
- excludeTriggers,
- groupId: activeGroupId,
- pageSize,
- withDetails,
- });
-
- const currentTopics = currentData?.items || [];
- const topics = this.#applyPendingStatusWrites(result.items, 'server');
- const nextItems = [...currentTopics, ...topics];
- const hasMore = result.total > nextItems.length;
-
- this.#set(
- {
- topicDataMap: {
- ...this.#get().topicDataMap,
- [key]: {
- currentPage: nextPage,
- excludeStatuses,
- excludeTriggers,
- hasMore,
- isInbox: currentData?.isInbox,
- isLoadingMore: false,
- loadMoreError: undefined,
- items: nextItems,
- pageSize,
- total: result.total,
- withDetails,
- },
- },
- },
- false,
- n('loadMoreTopics(success)'),
- );
- } catch (error) {
- this.#set(
- {
- topicDataMap: {
- ...this.#get().topicDataMap,
- [key]: {
- ...this.#get().topicDataMap[key]!,
- isLoadingMore: false,
- loadMoreError: error,
- },
- },
- },
- false,
- n('loadMoreTopics(error)'),
- );
- }
+ await this.#topicList.loadMore(key, {
+ agentId: activeAgentId,
+ excludeStatuses: currentData?.excludeStatuses,
+ excludeTriggers: currentData?.excludeTriggers,
+ groupId: activeGroupId,
+ isInbox: currentData?.isInbox,
+ pageSize: currentData?.pageSize || useGlobalStore.getState().status.topicPageSize || 20,
+ sortBy: currentData?.sortBy,
+ withDetails: currentData?.withDetails,
+ });
};
useSearchTopics = (
@@ -1775,17 +1584,7 @@ export class ChatTopicActionImpl {
if (!activeAgentId) return;
await topicService.removeTopicsByAgentId(activeAgentId, scope);
- this.#set(
- (state) => ({
- topicDetailMap: Object.fromEntries(
- Object.entries(state.topicDetailMap).filter(
- ([, topic]) => topic.sessionId !== activeAgentId,
- ),
- ),
- }),
- false,
- n('removeSessionTopics/detail'),
- );
+ this.#removeTopicDetails((topic) => topic.sessionId === activeAgentId);
await refreshTopic();
// drop every deleted topic's message cache (all belong to this agent)
void evictMessageCache((ctx) => ctx.agentId === activeAgentId);
@@ -1803,7 +1602,7 @@ export class ChatTopicActionImpl {
await topicService.removeTopicsByGroupId(groupId, scope);
// Topic detail rows don't carry their group id, so the safe invalidation
// boundary for a group-wide delete is the whole by-id detail cache.
- this.#set({ topicDetailMap: {} }, false, n('removeGroupTopics/detail'));
+ this.#removeTopicDetails(() => true);
await refreshTopic();
// drop every deleted topic's message cache (all belong to this group)
void evictMessageCache((ctx) => ctx.groupId === groupId);
@@ -1816,7 +1615,7 @@ export class ChatTopicActionImpl {
const { refreshTopic } = this.#get();
await topicService.removeAllTopic();
- this.#set({ topicDetailMap: {} }, false, n('removeAllTopics/detail'));
+ this.#removeTopicDetails(() => true);
await refreshTopic();
// every topic is gone β€” wipe all cached message lists
void evictMessageCache(() => true);
@@ -1896,22 +1695,15 @@ export class ChatTopicActionImpl {
*/
refreshTopic = async (ownerContainerKey?: string): Promise<void> => {
const { activeAgentId, activeGroupId } = this.#get();
- // Use topicMapKey to generate the same key used in useFetchTopics
- // Key format: topicKeys.list(containerKey, { isInbox, pageSize })
+ // Same container key the topic-list resource uses as its entry key.
const containerKey =
ownerContainerKey ?? topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
const agentViewKey =
ownerContainerKey ?? (activeAgentId ? topicMapKey({ agentId: activeAgentId }) : null);
- await mutate(
- (key) =>
- Array.isArray(key) &&
- ((key[0] === topicKeys.list.root &&
- typeof key[1] === 'string' &&
- key[1] === containerKey) ||
- (key[0] === topicKeys.agentView.root &&
- agentViewKey !== null &&
- key[1] === agentViewKey)),
- );
+ await Promise.all([
+ this.#topicList.revalidate(containerKey),
+ agentViewKey !== null && this.#topicAgentView.revalidate(agentViewKey),
+ ]);
};
internal_replaceTopicId = (params: {
@@ -1951,13 +1743,18 @@ export class ChatTopicActionImpl {
internal_updateTopic = async (id: string, data: Partial<ChatTopic>): Promise<void> => {
// The row is not necessarily in the active agent/group bucket β€” resolve the
- // one that holds it, so the optimistic write and the revalidation both land
- // where the topic is actually rendered (see `getTopicContainerKeyById`).
- const containerKey = topicSelectors.getTopicContainerKeyById(id)(this.#get());
-
- this.#get().internal_dispatchTopic({ type: 'updateTopic', id, value: data, containerKey });
+ // one that holds it, so the revalidation lands where the topic is actually
+ // rendered (see `getTopicContainerKeyById`).
+ const { activeAgentId, activeGroupId } = this.#get();
+ const containerKey =
+ topicSelectors.getTopicContainerKeyById(id)(this.#get()) ??
+ topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
- await topicService.updateTopic(id, data);
+ // One overlay per resource holding the topic (sidebar, management page,
+ // detail); all commit or all roll back with the single server call.
+ await this.#topicEntity.optimistic(id, patchTopic(data), () =>
+ topicService.updateTopic(id, data),
+ );
await this.#get().refreshTopic(containerKey);
};
@@ -2038,40 +1835,9 @@ export class ChatTopicActionImpl {
return topicId;
};
- /**
- * Mirror an optimistic topic patch into the PERSISTED topic-list cache.
- *
- * `topic:` keys are persisted to IndexedDB by the tiered SWR provider (see
- * `CACHE_TIERS`), and that cached page is what the sidebar paints on a cold
- * boot, before any revalidation lands. Optimistic dispatches only touched the
- * Zustand maps, so the terminal status a run writes when it ends ('unread' /
- * 'active') never reached the cache: the last FETCHED snapshot β€” taken while
- * the run was still `running` β€” stayed there, and a reload repainted a
- * finished topic with the running spinner until the revalidation corrected it
- * a moment later. Same write-through idea as
- * `#writeThroughMessageCache` in the message slice.
- *
- * Only `updateTopic` is mirrored. It patches a row a fetch already produced,
- * so it cannot leak a client-only row into a cache that outlives the session
- * β€” unlike an optimistic `addTopic` / `replaceTopicId`, whose placeholder is
- * reconciled per session by `#reconcileFetchedTopics`. Deletions already go
- * through `refreshTopic`, which revalidates the same keys.
- */
- #writeThroughTopicListCache = (containerKey: string, payload: ChatTopicDispatch): void => {
- if (payload.type !== 'updateTopic') return;
-
- void mutate(
- (key) => Array.isArray(key) && key[0] === topicKeys.list.root && key[1] === containerKey,
- (cached?: { items: ChatTopic[]; total: number }) => {
- if (!cached?.items) return cached;
-
- const items = topicReducer(cached.items, payload);
- // `topicReducer` returns the same reference when the patch is a no-op
- // (e.g. the row isn't on this cached page), so the entry stays untouched.
- return items === cached.items ? cached : { ...cached, items };
- },
- { revalidate: false },
- );
+ #removeTopicDetails = (predicate: (topic: ChatTopic) => boolean): void => {
+ for (const [id, topic] of Object.entries(this.#get().topicDetailMap))
+ if (predicate(topic)) this.#topicDetail.remove(id);
};
/**
@@ -2082,6 +1848,8 @@ export class ChatTopicActionImpl {
* user switched agents (see `updateTopicStatus`).
*/
internal_dispatchTopic = (payload: ChatTopicDispatch, action?: any): void => {
+ // Devtools names now come from the resource bindings (`t/topicList/update` …).
+ void action;
// Track the optimistic-row lifecycle here, at the single funnel every
// add / replace / delete goes through, so a caller cannot register a
// placeholder and then forget to clear it.
@@ -2118,97 +1886,49 @@ export class ChatTopicActionImpl {
groupId: scopedGroupId,
scope: payload.scope,
});
- const currentData = this.#get().topicDataMap[key];
- const nextItems = topicReducer(currentData?.items, payload);
-
- // Mirror the optimistic update into the Agent Topics management page's
- // bucket if it has been populated for the same key. Without this mirror,
- // bulk actions (favorite/status/delete) on the management page would
- // appear to do nothing until the SWR revalidation finished.
- const viewMap = this.#get().agentTopicsViewMap;
- const viewData = viewMap[key];
- const nextViewItems = viewData ? topicReducer(viewData.items, payload) : undefined;
- const viewChanged = viewData ? !isEqual(nextViewItems, viewData.items) : false;
-
- const detailMap = this.#get().topicDetailMap ?? {};
- const detailId = payload.type === 'addTopic' ? undefined : payload.id;
- const detailTopic = detailId ? detailMap[detailId] : undefined;
- let nextDetailMap = detailMap;
-
- if (payload.type === 'updateTopic' && detailTopic) {
- nextDetailMap = {
- ...detailMap,
- [payload.id]: { ...detailTopic, ...payload.value },
- };
- } else if (payload.type === 'deleteTopic' && detailTopic) {
- const { [payload.id]: _deleted, ...remainingDetailMap } = detailMap;
- nextDetailMap = remainingDetailMap;
- } else if (payload.type === 'replaceTopicId' && detailTopic) {
- const { [payload.id]: _replaced, ...remainingDetailMap } = detailMap;
- nextDetailMap = {
- ...remainingDetailMap,
- [payload.nextId]: { ...detailTopic, ...payload.value, id: payload.nextId },
- };
- }
-
- // Mirror the patch into the persisted topic-list cache too β€” see
- // `#writeThroughTopicListCache`. Runs before the unchanged early-return
- // below: the cache can hold rows this bucket never loaded (a cold boot
- // paints from it before any bucket exists), so "nothing changed in the
- // store" says nothing about the cached page.
- this.#writeThroughTopicListCache(key, payload);
-
- // no need to update if all maps are unchanged
- const mainChanged = !isEqual(nextItems, currentData?.items);
- const detailChanged = nextDetailMap !== detailMap;
- if (!mainChanged && !viewChanged && !detailChanged) return;
-
- const currentTotal = currentData?.total ?? currentData?.items?.length ?? 0;
- const total =
- payload.type === 'addTopic'
- ? currentTotal + 1
- : payload.type === 'deleteTopic'
- ? Math.max(nextItems.length, currentTotal - 1)
- : currentTotal;
-
- const nextState: Record<string, unknown> = {};
-
- if (detailChanged) nextState.topicDetailMap = nextDetailMap;
-
- if (mainChanged) {
- nextState.topicDataMap = {
- ...this.#get().topicDataMap,
- [key]: {
- ...currentData,
- currentPage: currentData?.currentPage ?? 0,
- hasMore: total > nextItems.length,
- isInbox: currentData?.isInbox,
- items: nextItems,
- total,
- },
- };
- }
- if (viewChanged && viewData && nextViewItems) {
- const viewTotal = viewData.total ?? viewData.items?.length ?? 0;
- const viewNextTotal =
- payload.type === 'addTopic'
- ? viewTotal + 1
- : payload.type === 'deleteTopic'
- ? Math.max(nextViewItems.length, viewTotal - 1)
- : viewTotal;
- nextState.agentTopicsViewMap = {
- ...viewMap,
- [key]: {
- ...viewData,
- hasMore: viewNextTotal > nextViewItems.length,
- items: nextViewItems,
- total: viewNextTotal,
- },
- };
+ switch (payload.type) {
+ // Status / title patches and deletions are entity facts: they reach every
+ // resource holding the topic and are persisted, so the next cold boot
+ // never repaints them stale (e.g. a finished run's spinner).
+ case 'updateTopic': {
+ this.#topicEntity.update(payload.id, patchTopic(payload.value));
+ return;
+ }
+ case 'deleteTopic': {
+ this.#topicEntity.remove(payload.id);
+ return;
+ }
+ // Adds and id swaps are list-structure placeholders until the server
+ // list confirms them: memory only, in the target container.
+ case 'addTopic': {
+ this.#topicList.update(key, (bucket) => applyTopicDispatchToBucket(bucket, payload), {
+ persist: false,
+ });
+ // The management page only gains the row once it has loaded that agent.
+ this.#topicAgentView.update(
+ key,
+ (bucket) => bucket && applyTopicDispatchToBucket(bucket, payload),
+ { persist: false },
+ );
+ return;
+ }
+ case 'replaceTopicId': {
+ for (const slice of [this.#topicList, this.#topicAgentView])
+ slice.update(key, (bucket) => applyTopicDispatchToBucket(bucket, payload), {
+ persist: false,
+ });
+ const detail = this.#get().topicDetailMap[payload.id];
+ if (detail && payload.nextId !== payload.id) {
+ this.#topicDetail.remove(payload.id);
+ this.#topicDetail.update(
+ payload.nextId,
+ () => ({ ...detail, ...payload.value, id: payload.nextId }),
+ { persist: false },
+ );
+ }
+ }
}
-
- this.#set(nextState, false, action ?? n(`dispatchTopic/${payload.type}`));
};
internal_updateTopics = (
@@ -2224,57 +1944,41 @@ export class ChatTopicActionImpl {
): void => {
const { total, pageSize, currentPage = 0, append = false, groupId } = params;
const key = topicMapKey({ agentId, groupId });
- const currentData = this.#get().topicDataMap[key];
- // Append mode keeps the existing items (optimistic rows included) in front,
- // so only pass them for reconciliation on full replacement.
- const items = this.#reconcileFetchedTopics(
- params.items,
- append ? undefined : currentData?.items,
- 'cache',
- );
- const nextItems = append ? [...(currentData?.items || []), ...items] : items;
+ this.#topicList.update(
+ key,
+ (currentData) => {
+ // Append mode keeps the existing items (optimistic rows included) in
+ // front, so only pass them for reconciliation on full replacement.
+ const items = this.#reconcileFetchedTopics(
+ params.items,
+ append ? undefined : currentData?.items,
+ 'cache',
+ );
+ const nextItems = append ? [...(currentData?.items || []), ...items] : items;
- this.#set(
- {
- topicDataMap: {
- ...this.#get().topicDataMap,
- [key]: {
- currentPage,
- excludeStatuses: currentData?.excludeStatuses,
- excludeTriggers: currentData?.excludeTriggers,
- hasMore: total > nextItems.length,
- isInbox: currentData?.isInbox,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: nextItems,
- pageSize,
- total,
- },
- },
+ return {
+ currentPage,
+ excludeStatuses: currentData?.excludeStatuses,
+ excludeTriggers: currentData?.excludeTriggers,
+ hasMore: total > nextItems.length,
+ isInbox: currentData?.isInbox,
+ isExpandingPageSize: false,
+ isLoadingMore: false,
+ items: nextItems,
+ pageSize,
+ sortBy: currentData?.sortBy,
+ total,
+ };
},
- false,
- n('internal_updateTopics', { key, append }),
+ { persist: false },
);
};
internal_updateTopicData = (key: string, data: Partial<TopicData>): void => {
- const currentData = this.#get().topicDataMap[key];
- if (!currentData) return;
-
- this.#set(
- {
- topicDataMap: {
- ...this.#get().topicDataMap,
- [key]: {
- ...currentData,
- ...data,
- },
- },
- },
- false,
- n('internal_updateTopicData', { key, data }),
- );
+ this.#topicList.update(key, (currentData) => currentData && { ...currentData, ...data }, {
+ persist: false,
+ });
};
}
diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.ts
index 49ecced7f51..8aa54ab6eec 100644
--- a/src/store/chat/slices/topic/initialState.ts
+++ b/src/store/chat/slices/topic/initialState.ts
@@ -1,9 +1,11 @@
-import { type ChatTopic } from '@/types/topic';
+import { createReplicaState, type ReplicaPagedData, type ReplicaState } from '@/libs/replica';
+import { type ChatTopic, type TopicQuerySortBy } from '@/types/topic';
/**
- * Unified topic data structure for each agent
+ * Unified topic data structure for each agent: the generic local-first paged
+ * view plus topic query descriptors.
*/
-export interface TopicData {
+export interface TopicData extends ReplicaPagedData<ChatTopic, number> {
currentPage: number;
excludeStatuses?: string[];
excludeTriggers?: string[];
@@ -24,6 +26,8 @@ export interface TopicData {
* or cases where total items < pageSize.
*/
pageSize: number;
+ /** Server-side ordering the bucket was fetched with (part of its query identity). */
+ sortBy?: TopicQuerySortBy;
total: number;
/**
* Tracks whether the first fetch for this container asked the server for
@@ -44,6 +48,8 @@ export interface ChatTopicState {
* lands last wins, tangling both views.
*/
agentTopicsViewMap: Record<string, TopicData>;
+ /** Local-first bookkeeping for `agentTopicsViewMap`. */
+ agentTopicsViewReplica: ReplicaState<TopicData>;
/**
* whether all topics drawer is open
*/
@@ -77,8 +83,12 @@ export interface ChatTopicState {
* keeps the real title instead of degrading to the "new topic" placeholder.
*/
topicDetailMap: Record<string, ChatTopic>;
+ /** Local-first bookkeeping for `topicDetailMap`. */
+ topicDetailReplica: ReplicaState<ChatTopic>;
/** Topics with effort selections queued or being persisted. */
topicEffortUpdatingIds: string[];
+ /** Local-first bookkeeping for `topicDataMap` (scope, optimistic overlays). */
+ topicListReplica: ReplicaState<TopicData>;
/**
* Internal ref-count for topic loading owners. A topic can be loading because
* the agent is running and because title-summary is streaming at the same time.
@@ -92,6 +102,7 @@ export interface ChatTopicState {
export const initialTopicState: ChatTopicState = {
activeTopicId: null as any,
agentTopicsViewMap: {},
+ agentTopicsViewReplica: createReplicaState<TopicData>(),
creatingTopicIds: [],
allTopicsDrawerOpen: false,
creatingTopic: false,
@@ -99,6 +110,8 @@ export const initialTopicState: ChatTopicState = {
searchTopics: [],
topicDataMap: {},
topicDetailMap: {},
+ topicDetailReplica: createReplicaState<ChatTopic>(),
+ topicListReplica: createReplicaState<TopicData>(),
topicLoadingIdCounts: {},
topicLoadingIds: [],
topicEffortUpdatingIds: [],
diff --git a/src/store/chat/slices/topic/projection.ts b/src/store/chat/slices/topic/projection.ts
new file mode 100644
index 00000000000..717d6e3caa3
--- /dev/null
+++ b/src/store/chat/slices/topic/projection.ts
@@ -0,0 +1,152 @@
+import isEqual from 'fast-deep-equal';
+
+import { definePagedReplica, defineReplica } from '@/libs/replica';
+import { topicMapKey } from '@/store/chat/utils/topicMapKey';
+import type { ChatTopic, TopicQuerySortBy } from '@/types/topic';
+
+import type { TopicData } from './initialState';
+import { type ChatTopicDispatch, topicReducer } from './reducer';
+
+export interface TopicListParams {
+ agentId?: string;
+ excludeStatuses?: string[];
+ excludeTriggers?: string[];
+ groupId?: string;
+ isInbox?: boolean;
+ pageSize: number;
+ sortBy?: TopicQuerySortBy;
+ withDetails?: boolean;
+}
+
+export interface TopicAgentViewParams {
+ agentId: string;
+ pageSize: number;
+ withDetails?: boolean;
+}
+
+/** Sidebar page size when the caller does not name one. */
+export const DEFAULT_TOPIC_PAGE_SIZE = 20;
+
+/**
+ * The one canonical shape of a sidebar list request.
+ *
+ * Shared by the rendering hook, the secondary panels and the pre-paint hydrate
+ * (route loader). The persisted row is keyed by `key` + `query`, so a caller
+ * that normalizes differently reads a row the sidebar never asks for β€” and the
+ * hydrate silently becomes a no-op.
+ */
+export const normalizeTopicListParams = (
+ input: Partial<TopicListParams>,
+): TopicListParams | null => {
+ const {
+ agentId,
+ excludeStatuses,
+ excludeTriggers,
+ groupId,
+ isInbox,
+ pageSize,
+ sortBy,
+ withDetails,
+ } = input;
+
+ if (!agentId && !groupId) return null;
+
+ return {
+ agentId,
+ excludeStatuses: excludeStatuses?.length ? excludeStatuses : undefined,
+ excludeTriggers: excludeTriggers?.length ? excludeTriggers : undefined,
+ groupId,
+ isInbox,
+ pageSize: pageSize || DEFAULT_TOPIC_PAGE_SIZE,
+ sortBy,
+ withDetails: withDetails || undefined,
+ };
+};
+
+const topicPaging = {
+ direction: 'forward',
+ getId: (topic: ChatTopic) => topic.id,
+ mode: 'offset',
+ // A reload repaints what the first network page would show, never a stale tail.
+ persist: { pages: 1 },
+} as const;
+
+/**
+ * Sidebar topic list, one entry per container (`agent_<id>` / `group_<id>` …).
+ * The view is `topicDataMap[containerKey]`, so every existing selector keeps
+ * reading the same place. Filters are the query identity: a projection taken
+ * under other filters never paints (e.g. completed topics after hiding them).
+ */
+export const topicListResource = definePagedReplica<TopicListParams, ChatTopic, number, TopicData>({
+ key: ({ agentId, groupId }) => topicMapKey({ agentId, groupId }),
+ name: 'topicList',
+ paging: topicPaging,
+ query: ({ excludeStatuses, excludeTriggers, isInbox, sortBy, withDetails }) => ({
+ excludeStatuses,
+ excludeTriggers,
+ isInbox: Boolean(isInbox),
+ sortBy,
+ withDetails: Boolean(withDetails),
+ }),
+ storage: 'indexedDB',
+ version: 2,
+});
+
+/**
+ * Agent Topics management page (`/agent/:aid/topics`): a different shape of
+ * the same entity β€” `withDetails` columns and a larger page β€” so it is its
+ * own resource with its own view (`agentTopicsViewMap`) instead of a mirror.
+ */
+export const topicAgentViewResource = definePagedReplica<
+ TopicAgentViewParams,
+ ChatTopic,
+ number,
+ TopicData
+>({
+ key: ({ agentId }) => topicMapKey({ agentId }),
+ name: 'topicAgentView',
+ paging: topicPaging,
+ query: ({ withDetails }) => ({ withDetails: Boolean(withDetails) }),
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** By-id topic detail cache (`topicDetailMap[topicId]`), for topics outside loaded lists. */
+export const topicDetailResource = defineReplica<string, ChatTopic, ChatTopic | null>({
+ key: (topicId) => topicId,
+ name: 'topicDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Apply a topic dispatch to one container bucket (counts and `hasMore` included). */
+export const applyTopicDispatchToBucket = (
+ bucket: TopicData | undefined,
+ payload: ChatTopicDispatch,
+): TopicData | undefined => {
+ // Nothing to patch: an update/delete for an unloaded container must not
+ // create an empty bucket (it would read as "loaded, no topics" and block
+ // the persisted projection from hydrating).
+ if (!bucket && payload.type !== 'addTopic') return bucket;
+
+ const items = topicReducer(bucket?.items, payload);
+ if (bucket && isEqual(items, bucket.items)) return bucket;
+
+ const currentTotal = bucket?.total ?? bucket?.items?.length ?? 0;
+ const total =
+ payload.type === 'addTopic'
+ ? currentTotal + 1
+ : payload.type === 'deleteTopic'
+ ? Math.max(items.length, currentTotal - 1)
+ : currentTotal;
+
+ return {
+ ...bucket,
+ currentPage: bucket?.currentPage ?? 0,
+ hasMore: total > items.length,
+ isInbox: bucket?.isInbox,
+ items,
+ pageSize: bucket?.pageSize as number,
+ total,
+ };
+};
diff --git a/src/store/chat/slices/topic/topicListCache.integration.test.ts b/src/store/chat/slices/topic/topicListCache.integration.test.ts
index 44acf534b04..2270608d7d4 100644
--- a/src/store/chat/slices/topic/topicListCache.integration.test.ts
+++ b/src/store/chat/slices/topic/topicListCache.integration.test.ts
@@ -4,12 +4,12 @@
* After a run ends, a reload briefly repainted the topic row with the running
* spinner before it vanished again.
*
- * The chain under test is the real one: `useFetchTopics` β†’ tiered SWR provider
- * β†’ IndexedDB β†’ "reload" (fresh provider) β†’ first paint before the network
- * answers. The run's terminal status is written optimistically (no refetch
- * follows it), so unless that write also reaches the persisted cache, the
- * cached page keeps the `running` snapshot taken mid-run and the sidebar paints
- * a spinner on a finished topic.
+ * The chain under test is the real one: `useFetchTopics` β†’ local-first topic
+ * list resource β†’ IndexedDB query projection β†’ "reload" (fresh store + SWR
+ * cache) β†’ first paint before the network answers. The run's terminal status
+ * is written optimistically (no refetch follows it), so unless that write also
+ * reaches the persisted projection, the cached page keeps the `running`
+ * snapshot taken mid-run and the sidebar paints a spinner on a finished topic.
*/
import { randomUUID } from 'node:crypto';
@@ -19,14 +19,15 @@ import { createElement, useEffect } from 'react';
import { type Cache, SWRConfig, useSWRConfig } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cacheScope, createReplicaState } from '@/libs/replica';
import { localDataCache } from '@/libs/swr/localDataCache';
import { createCacheProvider } from '@/libs/swr/localStorageProvider';
import { setScopedMutate } from '@/libs/swr/mutate';
import { topicService } from '@/services/topic';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
-import type { ChatTopic } from '@/types/topic';
import { useChatStore } from '../../store';
+import { topicListResource } from './projection';
vi.mock('@/services/topic', () => ({
topicService: { getTopics: vi.fn() },
@@ -36,6 +37,7 @@ const SCOPE_PREFIX = 'topic-cache-user:personal';
const AGENT_ID = 'agent-lobe-14032';
const CONTAINER_KEY = topicMapKey({ agentId: AGENT_ID });
+/** SWR provider as in the app: `topic:` (agent view, search) still persists via SWR. */
const makeProvider = (scope: string) =>
createCacheProvider({
debounceMs: 5,
@@ -63,24 +65,33 @@ const wrapper =
const runningTopic = { id: 'tpc-lobe-14032', status: 'running', title: 'ζŠšε·žζ˜Žε€©ε€©ζ°”ζŸ₯θ―’' };
-const cachedTopicStatus = async (scope: string): Promise<string | undefined> => {
- const entries = await localDataCache.entriesByScope(scope);
- for (const entry of entries) {
- if (!entry.key.includes('topic:list')) continue;
- const items = (entry.data as { data?: { items?: ChatTopic[] } })?.data?.items;
- const topic = items?.find((item) => item.id === runningTopic.id);
- if (topic) return topic.status ?? undefined;
- }
- return undefined;
+// Default sidebar params (no filters) β€” rows are stored per query.
+const SIDEBAR_STORAGE_KEY = topicListResource.storageKey({ agentId: AGENT_ID, pageSize: 20 });
+
+const persistedTopicStatus = async (
+ scope: string,
+ topicId = runningTopic.id,
+): Promise<string | undefined> => {
+ const projection = await topicListResource.storage!.get({ queryKey: SIDEBAR_STORAGE_KEY, scope });
+ return projection?.data.items.find((item) => item.id === topicId)?.status ?? undefined;
};
+/** A reload: memory is gone, only the persisted projection survives. */
+const reloadStore = () =>
+ act(() => {
+ useChatStore.setState({ topicDataMap: {}, topicListReplica: createReplicaState() });
+ });
+
describe('persisted topic list across a reload', () => {
const scopes = new Set<string>();
- const createScope = () => {
- const scope = `${SCOPE_PREFIX}:${randomUUID()}`;
+ const useScope = (scope: string) => {
scopes.add(scope);
+ vi.spyOn(cacheScope, 'get').mockReturnValue(scope);
+ vi.spyOn(cacheScope, 'use').mockReturnValue(scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
return scope;
};
+ const createScope = () => useScope(`${SCOPE_PREFIX}:${randomUUID()}`);
beforeEach(() => {
act(() => {
@@ -88,12 +99,18 @@ describe('persisted topic list across a reload', () => {
activeAgentId: AGENT_ID,
activeGroupId: undefined,
topicDataMap: {},
+ topicListReplica: createReplicaState(),
});
});
});
afterEach(async () => {
- await Promise.all([...scopes].map((scope) => localDataCache.clearScope(scope)));
+ await Promise.all(
+ [...scopes].flatMap((scope) => [
+ localDataCache.clearScope(scope),
+ topicListResource.storage!.remove({ queryKey: SIDEBAR_STORAGE_KEY, scope }),
+ ]),
+ );
scopes.clear();
vi.restoreAllMocks();
vi.clearAllMocks();
@@ -104,13 +121,14 @@ describe('persisted topic list across a reload', () => {
// --- session 1: the list is fetched while the run is still going ---------
vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);
- const provider1 = makeProvider(scope);
const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
- wrapper: wrapper(provider1),
+ wrapper: wrapper(makeProvider(scope)),
});
- await waitFor(() => expect(session1.result.current.data?.items).toHaveLength(1));
- await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('running'));
+ await waitFor(() =>
+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items).toHaveLength(1),
+ );
+ await waitFor(async () => expect(await persistedTopicStatus(scope)).toBe('running'));
// --- the run ends: an optimistic status write, with no refetch behind it -
act(() => {
@@ -121,26 +139,24 @@ describe('persisted topic list across a reload', () => {
});
});
- await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('active'));
+ await waitFor(async () => expect(await persistedTopicStatus(scope)).toBe('active'));
session1.unmount();
- // --- session 2 ("reload"): a slow network, so the cached page paints -----
- act(() => {
- useChatStore.setState({ topicDataMap: {} });
- });
+ // --- session 2 ("reload"): a slow network, so the persisted page paints --
+ reloadStore();
vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);
- const provider2 = makeProvider(scope);
- await provider2.hydrateScope?.();
-
const session2 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
- wrapper: wrapper(provider2),
+ wrapper: wrapper(makeProvider(scope)),
});
await waitFor(() =>
expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items).toHaveLength(1),
);
expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0].status).toBe('active');
+ // Background loading does not hide the hydrated list.
+ expect(session2.result.current.isValidating).toBe(true);
+ expect(session2.result.current.isHydrated).toBe(true);
session2.unmount();
});
@@ -152,15 +168,16 @@ describe('persisted topic list across a reload', () => {
vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);
- const provider1 = makeProvider(scope);
const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
- wrapper: wrapper(provider1),
+ wrapper: wrapper(makeProvider(scope)),
});
- await waitFor(() => expect(session1.result.current.data?.items).toHaveLength(1));
- await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('running'));
+ await waitFor(() =>
+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items).toHaveLength(1),
+ );
+ await waitFor(async () => expect(await persistedTopicStatus(scope)).toBe('running'));
- // The terminal write wins in Zustand and the persisted cache first.
+ // The terminal write wins in Zustand and the persisted projection first.
act(() => {
useChatStore.getState().internal_pinTopicStatus({
agentId: AGENT_ID,
@@ -168,46 +185,41 @@ describe('persisted topic list across a reload', () => {
topicId: runningTopic.id,
});
});
- await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('active'));
- const cacheSetSpy = vi.spyOn(localDataCache, 'set');
+ await waitFor(async () => expect(await persistedTopicStatus(scope)).toBe('active'));
+ const persistSpy = vi.spyOn(topicListResource.storage!, 'set');
// A list request that started before the terminal write returns afterwards.
- // The pending-status pin keeps the mounted sidebar correct, but the raw SWR
- // response must not put `running` back into IndexedDB behind it.
+ // The pending-status pin keeps the mounted sidebar correct, and the server
+ // replace must not put `running` back into IndexedDB behind it.
await act(async () => {
- await session1.result.current.mutate();
+ await session1.result.current.revalidate();
});
expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0].status).toBe('active');
- await waitFor(() => expect(cacheSetSpy).toHaveBeenCalled());
- await Promise.all(cacheSetSpy.mock.results.map(({ value }) => value));
- expect(await cachedTopicStatus(scope)).toBe('active');
+ await waitFor(() => expect(persistSpy).toHaveBeenCalled());
+ await Promise.all(persistSpy.mock.results.map(({ value }) => value));
+ expect(await persistedTopicStatus(scope)).toBe('active');
// The normalized first response must not be mistaken for server
// confirmation. A second older response can still be in flight and must be
// pinned too.
- cacheSetSpy.mockClear();
+ persistSpy.mockClear();
await act(async () => {
- await session1.result.current.mutate();
+ await session1.result.current.revalidate();
});
- await waitFor(() => expect(cacheSetSpy).toHaveBeenCalled());
- await Promise.all(cacheSetSpy.mock.results.map(({ value }) => value));
- expect(await cachedTopicStatus(scope)).toBe('active');
+ await waitFor(() => expect(persistSpy).toHaveBeenCalled());
+ await Promise.all(persistSpy.mock.results.map(({ value }) => value));
+ expect(await persistedTopicStatus(scope)).toBe('active');
session1.unmount();
// Regression: after the 15-second pending pin elapsed, navigating away and
- // back remounted the sidebar from that stale IndexedDB snapshot and restored
- // the yellow running spinner until the network response arrived.
+ // back remounted the sidebar from a stale snapshot and restored the yellow
+ // running spinner until the network response arrived.
nowSpy.mockReturnValue(now + 16_000);
- act(() => {
- useChatStore.setState({ topicDataMap: {} });
- });
+ reloadStore();
vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);
- const provider2 = makeProvider(scope);
- await provider2.hydrateScope?.();
-
const session2 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
- wrapper: wrapper(provider2),
+ wrapper: wrapper(makeProvider(scope)),
});
await waitFor(() =>
@@ -238,7 +250,9 @@ describe('persisted topic list across a reload', () => {
{ wrapper: wrapper(provider) },
);
await waitFor(() =>
- expect(primedAgentView.result.current.data?.items[0].status).toBe('active'),
+ expect(useChatStore.getState().agentTopicsViewMap[CONTAINER_KEY]?.items[0].status).toBe(
+ 'active',
+ ),
);
primedAgentView.unmount();
@@ -251,8 +265,10 @@ describe('persisted topic list across a reload', () => {
const sidebar = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
wrapper: wrapper(provider),
});
- await waitFor(() => expect(sidebar.result.current.data?.items[0].status).toBe('running'));
- await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('running'));
+ await waitFor(() =>
+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0].status).toBe('running'),
+ );
+ await waitFor(async () => expect(await persistedTopicStatus(scope)).toBe('running'));
act(() => {
useChatStore.getState().internal_pinTopicStatus({
@@ -261,7 +277,7 @@ describe('persisted topic list across a reload', () => {
topicId: runningTopic.id,
});
});
- await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('active'));
+ await waitFor(async () => expect(await persistedTopicStatus(scope)).toBe('active'));
const replayedAgentView = renderHook(
() =>
@@ -280,12 +296,75 @@ describe('persisted topic list across a reload', () => {
// If the cached management row cleared the pin, this stale sidebar response
// would restore `running` in both Zustand and IndexedDB.
await act(async () => {
- await sidebar.result.current.mutate();
+ await sidebar.result.current.revalidate();
});
expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0].status).toBe('active');
- await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('active'));
+ await waitFor(async () => expect(await persistedTopicStatus(scope)).toBe('active'));
replayedAgentView.unmount();
sidebar.unmount();
});
+
+ it('patches the persisted list of a container that is not loaded (Codex P1)', async () => {
+ const scope = createScope();
+ // Own id: other tests leave pending status pins on `runningTopic`.
+ const topic = { ...runningTopic, id: 'tpc-unloaded-container' };
+ vi.mocked(topicService.getTopics).mockResolvedValue({ items: [topic], total: 1 } as any);
+ const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
+ wrapper: wrapper(makeProvider(scope)),
+ });
+ await waitFor(async () => expect(await persistedTopicStatus(scope, topic.id)).toBe('running'));
+ session1.unmount();
+
+ // The user navigated elsewhere: the owning bucket is no longer in memory.
+ reloadStore();
+ act(() => useChatStore.setState({ activeAgentId: 'another-agent' }));
+
+ // The run finishes for the unloaded container.
+ act(() => {
+ useChatStore.getState().internal_dispatchTopic({
+ agentId: AGENT_ID,
+ id: topic.id,
+ type: 'updateTopic',
+ value: { status: 'unread' },
+ });
+ });
+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]).toBeUndefined();
+ await waitFor(async () => expect(await persistedTopicStatus(scope, topic.id)).toBe('unread'));
+
+ // The next visit hydrates the terminal status, not the stale spinner.
+ act(() => useChatStore.setState({ activeAgentId: AGENT_ID }));
+ vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);
+ const visit = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
+ wrapper: wrapper(makeProvider(scope)),
+ });
+ await waitFor(() =>
+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0]?.status).toBe('unread'),
+ );
+ visit.unmount();
+ });
+
+ it('does not repaint another identity’s persisted list after a scope switch', async () => {
+ const scopeA = createScope();
+ vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);
+ const sessionA = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
+ wrapper: wrapper(makeProvider(scopeA)),
+ });
+ // (status may carry an earlier test's pending pin β€” only presence matters)
+ await waitFor(async () => expect(await persistedTopicStatus(scopeA)).toBeDefined());
+ sessionA.unmount();
+
+ // Same device, another user (or workspace membership) β€” same container key.
+ const scopeB = useScope(`${SCOPE_PREFIX}:${randomUUID()}`);
+ vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);
+ const sessionB = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
+ wrapper: wrapper(makeProvider(scopeB)),
+ });
+
+ await waitFor(() => expect(sessionB.result.current.isHydrated).toBe(true));
+ // Memory from scope A is cleared and scope B has nothing persisted.
+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]).toBeUndefined();
+ expect(useChatStore.getState().topicListReplica.scope).toBe(scopeB);
+ sessionB.unmount();
+ });
});
diff --git a/src/store/trash/action.test.ts b/src/store/trash/action.test.ts
index 34f73defbc3..912ac5d46e1 100644
--- a/src/store/trash/action.test.ts
+++ b/src/store/trash/action.test.ts
@@ -75,6 +75,9 @@ describe('TrashAction', () => {
const filter = filterCall![0] as (key: unknown) => boolean;
expect(filter(['topic:list', 'x', {}])).toBe(true);
expect(filter(['agent:list', true])).toBe(true);
+ // Local-first sync keys (topic list) and the agent sidebar sync key
+ expect(filter(['replica:sync', 'topicList', 1, 'scope', 'agent_x', {}])).toBe(true);
+ expect(filter(['agentSync:list', true, 'scope'])).toBe(true);
expect(filter(['trash:list', 'all'])).toBe(false);
expect(filter('not-an-array')).toBe(false);
});
diff --git a/src/store/trash/action.ts b/src/store/trash/action.ts
index bfd40385a97..0603b3044e2 100644
--- a/src/store/trash/action.ts
+++ b/src/store/trash/action.ts
@@ -20,12 +20,16 @@ type Setter = StoreSetter<TrashStore>;
/** SWR key roots whose lists can regain rows after a restore. */
const RESTORE_AFFECTED_KEY_PREFIXES = [
'agent:',
+ // Agent sidebar sync keys (#18913) live outside `agent:` so they skip SWR persistence.
+ 'agentSync:',
'document:',
'file:',
'group:',
'home:',
'image:',
'knowledgeBase:',
+ // Replicas (topic list, …) sync through `replica:sync` keys (`@lobechat/replica`).
+ 'replica:',
'page',
'project',
'recent:',