π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(replica): one settle pipeline for sync and imperative fetches (#20831)
Arvin Xu69fb5977745a
diff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.mdindex 0e49c5e8df9..9f765008992 100644--- a/.agents/skills/zustand/SKILL.md+++ b/.agents/skills/zustand/SKILL.md@@ -39,8 +39,9 @@ Server lists and details the UI paints go through `@/libs/replica`, not a hand-w2. Add two state fields per replica: the view (`xxxMap: Record<key, TData>`) and its bookkeeping (`xxxReplica: createReplicaState()`).3. Bind it in the private class: `createReplicaSlice(resource, { get, set, stateKey: 'xxxReplica', view: recordLens('xxxMap'), β¦ })`. When the same entity lives in several replicas (list row + detail), link them with `linkReplicaEntity([list, detail])`.4. Read: `slice.useSync(params)` returns only fetch flags (`isHydrated`, `isValidating`, `error`, `revalidate`). Data comes from selectors over `xxxMap`. "Entry is `undefined`" is the loading signal β do not add `xxxInit` flags or `loadingXxxIds`.-5. Cold start without a skeleton: `useSync` hydrates only after the component mounts. For a list that must paint from the local copy, add a `preHydrate` action (`ensureScope` + `hydrate`) and call it from the route's `loader` through a lazy wrapper (`src/spa/router/pageListLoader.ts`, `agentChatTopicListLoader.ts`) bounded by `PRE_PAINT_HYDRATE_TIMEOUT`.-6. Write: `slice.optimistic(key, apply, serverCall)` or `entity.optimistic(id, fn | 'remove', serverCall)`. A failed call rolls back to the confirmed value, so deletes are optimistic too. Rows that exist only on the client (temp ids) are declared with `isClientOnly` and seeded with `update(key, fn, { persist: false })`.+5. Read with no view mounted (hover prefetch, refresh after a mutation): `await slice.fetch(params)` (`{ fresh: true }` after a write). Never call the service and `slice.replace(...)` by hand, because that skips the scope, removal, clear and superseded-request guards. Side effects of every response (not-found maps, seeding another store) go in the slice `effects` (`onApplied` / `onMissing` / `onPurge` / `onError`) with `isMissing`, not in one hook's `onSuccess`.+6. Cold start without a skeleton: `useSync` hydrates only after the component mounts. For a list that must paint from the local copy, add a `preHydrate` action (`ensureScope` + `hydrate`) and call it from the route's `loader` through a lazy wrapper (`src/spa/router/pageListLoader.ts`, `agentChatTopicListLoader.ts`) bounded by `PRE_PAINT_HYDRATE_TIMEOUT`.+7. Write: `slice.optimistic(key, apply, serverCall)` or `entity.optimistic(id, fn | 'remove', serverCall)`. A failed call rolls back to the confirmed value, so deletes are optimistic too. Rows that exist only on the client (temp ids) are declared with `isClientOnly` and seeded with `update(key, fn, { persist: false })`.Outside test seeding, write a replica's view only through its slice. A plain `set` bypasses the engine's bookkeeping (persistence, rollback base, entity links).diff --git a/packages/replica/README.md b/packages/replica/README.mdindex 78f7f48130e..e7fe54dd1b7 100644--- a/packages/replica/README.md+++ b/packages/replica/README.md@@ -53,6 +53,39 @@ A persisted row is only rewritten when its value changes: a persist whose valueInside LobeHub, use `@/libs/replica`. It presets the cache scope, IndexedDB / localStorage storage and the app's SWR driver.+## Fetching without a mounted view++`slice.revalidate(key)` only re-runs the `useSync` queries that are mounted. A store that needs the data while no view is mounted β a hover prefetch, a refresh after a mutation on a route without the list β calls `slice.fetch(params)` instead of calling the service and `replace` by hand:++```ts+const { applied, data, missing } = await slice.fetch(params); // joins a request in flight+await slice.fetch(params, { fresh: true }); // after a mutation: new request, retires older ones+```++Every head response, from `useSync` or `fetch`, goes through one settle pipeline. A request captures its scope, the `clear()` generation, the entry's removal generation and its query when it starts. The response is dropped when any of them moved on (identity switch, `clear()`, `remove` / a pruned entity, a view now showing another query) or when a newer response for the entry already applied. Otherwise it is folded in with `replace`; an `isMissing` answer removes the entry, and an `isMissing` answer captured under a scope the store has since left purges that scope's row instead. `fetch` resolves `{ applied, data, missing }` and rejects when the request fails.++- **Dedupe.** `fetch` joins a request already in flight for the same entry, whether a `useSync` or another `fetch` started it. The request settles once, so effects do not run twice. `{ fresh: true }` starts a new request and retires the older ones, because those may still hold the pre-mutation value.+- **Captured scope.** A flow that fans out from an earlier response (a warmup fetching replies for the roots it got) passes `{ scope }` captured at its start. Each step then settles into that scope. Once the scope is no longer active, `fetch` rejects with `ReplicaScopeChangedError` and sends no request, because the request would read the new identity's data under the old identity's label.+- **Driver cache.** After `fetch` applies a response, it seeds the driver's cache under the sync key (`driver.seed`; for SWR that is `mutate(key, data, { revalidate: false })`). It skips the seed while a `useSync` request for that key is in flight: SWR discards an in-flight request that a write overtakes, so seeding then would drop that request's newer response. SWR still revalidates a later mount unless the sync sets `revalidateIfStale: false`. The value is already in the store, so that revalidation only confirms it.+- **Effects.** Side effects that every response needs go on the slice, not on one view's callbacks:++ ```ts+ createReplicaSlice(resource, {+ effects: {+ onApplied: (data, params, ctx) => {}, // folded into the active scope+ onMissing: (params, ctx) => {}, // `isMissing`, removed from the active scope+ onPurge: (params, ctx) => {}, // `isMissing` captured under a scope left behind+ onError: (error, params, { isActive, key, scope }) => {},+ },+ isMissing: (data) => data === null,+ // β¦+ });+ ```++ They run for `useSync` responses and `fetch` responses alike. A `useSync` request settles on its own response even when the hook has moved to another key and the driver skips its callback. `useSync`'s per-call `onSuccess` / `onError` remain for UI callbacks of that one view, and `onSuccess` is skipped for a key the hook has left.++Use `revalidate` when the views that show the data are mounted and should refetch on their own schedule. Use `fetch` when the caller needs the data now, needs to know whether it applied, or may run with nothing mounted.+## InvalidationPersisted rows are kept per entry key **and** per query (`key?<query>`), so a resource can hold several rows for one key. Never delete through a plain `set` or by clearing SWR keys: the persisted rows survive and a reload paints the deleted data. Use the primitive that matches what is gone:@@ -102,4 +135,4 @@ Message-like resources page backward by cursor, with windows whose length change| `slice.update(key, fn, { persist: false })` + `slice.persist(key)` | Stream into memory, then persist the confirmed value once. || `splitPagedLens({ itemsField, metaField, derive })` | Keep raw rows where readers expect them, paging bookkeeping beside them, and derived fields (a parsed display list) in the same commit. |-`useSync(params, options)` forwards a sync schedule (`refreshInterval`, `dedupingInterval`, `revalidateIfStale`, `revalidateOnFocus`, β¦) to the driver, and runs `onSuccess` / `onError` side effects after a response is folded in. On a cold start with no network (offline / slow), `onHydrated` runs the same "success" handling off the persisted value the hydrate paints, since there is no response for `onSuccess` to run on.+`useSync(params, options)` forwards a sync schedule (`refreshInterval`, `dedupingInterval`, `revalidateIfStale`, `revalidateOnFocus`, β¦) to the driver, and runs `onSuccess` / `onError` side effects after a response is folded in (resource-wide side effects belong in the slice `effects`, see above). On a cold start with no network (offline / slow), `onHydrated` runs the same "success" handling off the persisted value the hydrate paints, since there is no response for `onSuccess` to run on.diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.tsindex 44b54d67a1d..50d8df83a05 100644--- a/packages/replica/src/core/engine.ts+++ b/packages/replica/src/core/engine.ts@@ -112,6 +112,9 @@ export interface ReplicaEngineOptions<TParams, TData, TFetched> {viewFields?: (params: TParams) => Partial<TData>;}+/** What a head response did once folded in (see `applyHead`). */+export type ReplicaHeadOutcome = 'dropped' | 'missing' | 'replaced';+export interface OptimisticMutationOptions<TData, TResult> {/** Turn the server result into the confirmed value; defaults to re-applying `apply`. */confirm?: (result: TResult) => (data: TData) => TData;@@ -787,6 +790,9 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>();};+ /** Non-paged: whether a (prepared) head response is a terminal absence (`isMissing`). */+ const isMissingHead = (incoming: TFetched): boolean => !paging && !!options.isMissing?.(incoming);+const mergeHead = (key: string,incoming: TFetched,@@ -806,20 +812,30 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(return confirmed !== undefined && isEqual(next, confirmed) ? undefined : next;};- const replace = (params: TParams, fetched: TFetched, scope = resource.scope.get()) => {+ /**+ * Fold a head response in and report what it was: dropped by `prepareHead`,+ * a terminal absence (`isMissing`, applied as a removal) or a replacement.+ * `changed` is whether the store moved. `replace` is the boolean shorthand;+ * the zustand slice's settle pipeline reads the outcome to pick its effects.+ */+ const applyHead = (+ params: TParams,+ fetched: TFetched,+ scope = resource.scope.get(),+ ): { changed: boolean; outcome: ReplicaHeadOutcome } => {const key = resource.key(params);const incoming = options.prepareHead? options.prepareHead(fetched, port.read(key), params): fetched;- if (incoming === undefined) return false;+ if (incoming === undefined) return { changed: false, outcome: 'dropped' };// A response that says the entry is gone clears it outright: the merge path// would keep β and re-persist β the confirmed value it is replacing. It also// arms the hydration guard, so a persisted read still in flight cannot bring// the dropped value back.- if (!paging && options.isMissing?.(incoming)) {+ if (isMissingHead(incoming)) {// Route through `remove` so a repeated "missing" is a no-op and a response// captured under another scope is dropped rather than applied here.- return remove(key, scope);+ return { changed: remove(key, scope), outcome: 'missing' };}const query = resource.query(params);const entry = getSlot().entries[key];@@ -842,9 +858,12 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(type: 'replace',});if (applied) forgetRestoredEntities(scope, getConfirmed(key));- return applied;+ return { changed: applied, outcome: 'replaced' };};+ const replace = (params: TParams, fetched: TFetched, scope = resource.scope.get()) =>+ applyHead(params, fetched, scope).changed;+/*** Confirmed local write: patches the view (and the base under any overlay).* Pass `source: 'seed'` for a provisional row (a list row standing in for a@@ -1469,6 +1488,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(});return {+ applyHead,beginEntityOptimistic,beginOptimistic,clear,@@ -1483,6 +1503,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(getConfirmed,hydrate,insertHead,+ isMissingHead,loadMore,optimistic,patchStoredEntity,diff --git a/packages/replica/src/zustand/createReplicaSlice.fetch.test.ts b/packages/replica/src/zustand/createReplicaSlice.fetch.test.tsnew file mode 100644index 00000000000..accaf91332a--- /dev/null+++ b/packages/replica/src/zustand/createReplicaSlice.fetch.test.ts@@ -0,0 +1,454 @@+/**+ * @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 } from '../../tests/testDriver';+import { defineReplica } from '../core/defineReplica';+import { REPLICA_INDEX_KEY } from '../core/engine';+import { replicaKeys } from '../core/keys';+import { createReplicaState } from '../core/reducer';+import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';+import type { ReplicaEffects } from './createReplicaSlice';+import { createReplicaSlice, recordLens, ReplicaScopeChangedError } from './createReplicaSlice';+import type { ReplicaSyncDriver } from './driver';++type Value = string[] | null;++interface TestState {+ lists: Record<string, Value>;+ listsReplica: ReplicaState<Value>;+}++const scopeState = { current: 'user-1:personal' };+const scope: ReplicaScope = {+ canPersist: () => true,+ get: () => scopeState.current,+ use: () => scopeState.current,+};++const createMemoryStorage = () => {+ const rows = new Map<string, ReplicaRow<Value>>();+ const indexRows = new Map<string, ReplicaRow<Value>>();+ const read: ReplicaStorage<Value>['get'] = async ({ queryKey, scope }) =>+ queryKey === REPLICA_INDEX_KEY ? indexRows.get(scope) : rows.get(`${scope}|${queryKey}`);+ const storage: ReplicaStorage<Value> = {+ get: read,+ getStrict: read,+ remove: async ({ queryKey, scope }) => {+ if (queryKey === REPLICA_INDEX_KEY) return void indexRows.delete(scope);+ rows.delete(`${scope}|${queryKey}`);+ },+ set: async ({ queryKey, scope }, row) => {+ if (queryKey === REPLICA_INDEX_KEY) return void indexRows.set(scope, row);+ rows.set(`${scope}|${queryKey}`, row);+ },+ };+ return { rows, storage };+};++/** A fetcher whose responses resolve / reject on demand, in call order. */+const deferredFetcher = () => {+ const calls: { reject: (error: unknown) => void; resolve: (value: Value) => void }[] = [];+ const fetcher = vi.fn(+ () =>+ new Promise<Value>((resolve, reject) => {+ calls.push({ reject, resolve });+ }),+ );+ return { calls, fetcher };+};++const setup = ({+ driver = testDriver,+ effects,+ fetcher = vi.fn(async () => ['server'] as Value),+ storage = createMemoryStorage(),+}: {+ driver?: ReplicaSyncDriver;+ effects?: ReplicaEffects<{ id: string }, Value>;+ fetcher?: (params: { id: string }) => Promise<Value>;+ storage?: ReturnType<typeof createMemoryStorage>;+} = {}) => {+ const resource = defineReplica<{ id: string }, Value>({+ fetcher,+ key: ({ id }) => id,+ name: 'fetchList',+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, Value>(resource, {+ driver,+ effects,+ get: store.getState,+ // `null` is the server's "this entry does not exist".+ isMissing: (data) => data === null,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });+ return { slice, storage, store };+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);++const effectSpies = () => ({+ onApplied: vi.fn(),+ onError: vi.fn(),+ onMissing: vi.fn(),+ onPurge: vi.fn(),+});++beforeEach(() => {+ scopeState.current = 'user-1:personal';+});++describe('createReplicaSlice fetch', () => {+ it('applies the head with no view mounted, persists it and runs onApplied', async () => {+ const effects = effectSpies();+ const { slice, storage, store } = setup({ effects });++ const result = await slice.fetch({ id: 'a' });++ expect(result).toEqual({ applied: true, data: ['server'], missing: false });+ expect(store.getState().lists.a).toEqual(['server']);+ expect(effects.onApplied).toHaveBeenCalledWith(+ ['server'],+ { id: 'a' },+ { key: 'a', scope: 'user-1:personal', source: 'fetch' },+ );+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['server']));+ });++ it('drops a response captured under a scope the store has left, without effects', async () => {+ const { calls, fetcher } = deferredFetcher();+ const effects = effectSpies();+ const { slice, storage, store } = setup({ effects, fetcher });++ const pending = slice.fetch({ id: 'a' });+ scopeState.current = 'user-2:personal';+ calls[0].resolve(['previous identity']);++ await expect(pending).resolves.toMatchObject({ applied: false });+ expect(store.getState().lists.a).toBeUndefined();+ expect(effects.onApplied).not.toHaveBeenCalled();+ expect(storage.rows.size).toBe(0);+ });++ it('drops a response whose entry was removed while it was in flight', async () => {+ const { calls, fetcher } = deferredFetcher();+ const effects = effectSpies();+ const { slice, store } = setup({ effects, fetcher });++ const pending = slice.fetch({ id: 'a' });+ slice.remove('a');+ calls[0].resolve(['deleted on the server']);++ await expect(pending).resolves.toMatchObject({ applied: false });+ expect(store.getState().lists.a).toBeUndefined();+ expect(effects.onApplied).not.toHaveBeenCalled();+ });++ it('drops a response whose request started before a clear()', async () => {+ const { calls, fetcher } = deferredFetcher();+ const effects = effectSpies();+ const { slice, store } = setup({ effects, fetcher });++ const pending = slice.fetch({ id: 'a' });+ await slice.clear();+ calls[0].resolve(['wiped']);++ await expect(pending).resolves.toMatchObject({ applied: false });+ expect(store.getState().lists.a).toBeUndefined();+ expect(effects.onApplied).not.toHaveBeenCalled();+ });++ it('removes a terminal absence and runs onMissing in the active scope', async () => {+ const storage = createMemoryStorage();+ const effects = effectSpies();+ const { slice, store } = setup({ effects, fetcher: vi.fn(async () => null), storage });+ store.setState({ lists: { a: ['cached'] } });+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });++ await expect(slice.fetch({ id: 'a' })).resolves.toEqual({+ applied: true,+ data: null,+ missing: true,+ });++ expect(store.getState().lists.a).toBeUndefined();+ expect(effects.onMissing).toHaveBeenCalledWith(+ { id: 'a' },+ { key: 'a', scope: 'user-1:personal', source: 'fetch' },+ );+ expect(effects.onApplied).not.toHaveBeenCalled();+ await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));+ });++ it('purges a late terminal absence in the scope it was captured under, without onMissing', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['previous'], updatedAt: 1 });+ storage.rows.set('user-2:personal|a', { data: ['current'], updatedAt: 1 });+ const { calls, fetcher } = deferredFetcher();+ const effects = effectSpies();+ const { slice, store } = setup({ effects, fetcher, storage });+ store.setState({ lists: { a: ['current'] } });++ const pending = slice.fetch({ id: 'a' });+ scopeState.current = 'user-2:personal';+ calls[0].resolve(null);++ await expect(pending).resolves.toEqual({ applied: false, data: null, missing: true });+ // The row of the scope the request belonged to is goneβ¦+ await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));+ // β¦while the scope on screen keeps its own value and runs no effects.+ expect(storage.rows.get('user-2:personal|a')?.data).toEqual(['current']);+ expect(store.getState().lists.a).toEqual(['current']);+ expect(effects.onMissing).not.toHaveBeenCalled();+ // Linked resources purge their own rows of that scope.+ expect(effects.onPurge).toHaveBeenCalledWith(+ { id: 'a' },+ { key: 'a', scope: 'user-1:personal', source: 'fetch' },+ );+ });++ it('rejects on a failed request after routing it to effects.onError with the captured scope', async () => {+ const failure = new Error('offline');+ const { calls, fetcher } = deferredFetcher();+ const effects = effectSpies();+ const { slice } = setup({ effects, fetcher });++ const active = slice.fetch({ id: 'a' });+ calls[0].reject(failure);+ await expect(active).rejects.toBe(failure);+ expect(effects.onError).toHaveBeenLastCalledWith(+ failure,+ { id: 'a' },+ { isActive: true, key: 'a', scope: 'user-1:personal' },+ );++ const offScope = slice.fetch({ id: 'b' });+ scopeState.current = 'user-2:personal';+ calls[1].reject(failure);+ await expect(offScope).rejects.toBe(failure);+ expect(effects.onError).toHaveBeenLastCalledWith(+ failure,+ { id: 'b' },+ { isActive: false, key: 'b', scope: 'user-1:personal' },+ );+ });++ it('joins the request of a mounted useSync and settles it once', async () => {+ const { calls, fetcher } = deferredFetcher();+ const effects = effectSpies();+ const onSuccess = vi.fn();+ const { slice, store } = setup({ effects, fetcher });++ renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }), { wrapper });+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));++ const pending = slice.fetch({ id: 'a' });+ expect(fetcher).toHaveBeenCalledTimes(1);++ await act(async () => calls[0].resolve(['server']));+ await expect(pending).resolves.toEqual({ applied: true, data: ['server'], missing: false });++ expect(store.getState().lists.a).toEqual(['server']);+ await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));+ // The resource effects run once for the shared request, not per path.+ expect(effects.onApplied).toHaveBeenCalledTimes(1);+ expect(effects.onApplied.mock.calls[0][2]).toMatchObject({ source: 'sync' });+ });++ it('runs the resource effects for useSync responses too', async () => {+ const effects = effectSpies();+ const { slice } = setup({ effects });++ renderHook(() => slice.useSync({ id: 'a' }), { wrapper });++ await waitFor(() =>+ expect(effects.onApplied).toHaveBeenCalledWith(+ ['server'],+ { id: 'a' },+ { key: 'a', scope: 'user-1:personal', source: 'sync' },+ ),+ );+ });++ it('settles a useSync response the hook moved past, with its resource effects', async () => {+ const { calls, fetcher } = deferredFetcher();+ const effects = effectSpies();+ const onSuccess = vi.fn();+ const { slice, store } = setup({ effects, fetcher });++ const { rerender } = renderHook(({ id }) => slice.useSync({ id }, { onSuccess }), {+ initialProps: { id: 'a' },+ wrapper,+ });+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));+ rerender({ id: 'b' });+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));++ // `a` answers "gone" after the view moved to `b`: the driver no longer+ // calls this hook back for it, yet the absence is still settled.+ store.setState({ lists: { a: ['cached'] } });+ await act(async () => calls[0].resolve(null));++ expect(store.getState().lists.a).toBeUndefined();+ expect(effects.onMissing).toHaveBeenCalledWith(+ { id: 'a' },+ { key: 'a', scope: 'user-1:personal', source: 'sync' },+ );+ // The view's own callback is not run for a key it left.+ expect(onSuccess).not.toHaveBeenCalled();+ });++ it('releases the record of a sync request whose callback the driver skipped', async () => {+ const { calls, fetcher } = deferredFetcher();+ const { slice } = setup({ fetcher });++ const { rerender, unmount } = renderHook(({ id }) => slice.useSync({ id }), {+ initialProps: { id: 'a' },+ wrapper,+ });+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));+ rerender({ id: 'b' });+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));+ rerender({ id: 'c' });+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(3));+ unmount();++ // Every request answers after its hook moved on or unmounted: the driver+ // runs none of the callbacks that would have taken the records.+ await act(async () => {+ for (const call of calls) call.resolve(['server']);+ });+ await act(() => new Promise((resolve) => setTimeout(resolve, 10)));++ expect(slice.debugPendingSyncRequests()).toBe(0);+ });++ it('settles a fetch into the scope its caller captured, and refuses one that left it', async () => {+ const { calls, fetcher } = deferredFetcher();+ const { slice, store } = setup({ fetcher });++ const pending = slice.fetch({ id: 'a' }, { scope: 'user-1:personal' });+ scopeState.current = 'user-2:personal';+ calls[0].resolve(['previous identity']);+ await expect(pending).resolves.toMatchObject({ applied: false });++ // A later step of the same flow must not fetch the new identity's data+ // under the old identity's label.+ await expect(slice.fetch({ id: 'b' }, { scope: 'user-1:personal' })).rejects.toBeInstanceOf(+ ReplicaScopeChangedError,+ );+ expect(fetcher).toHaveBeenCalledTimes(1);+ expect(store.getState().lists).toEqual({});+ });++ it('a fresh fetch retires the requests started before it', async () => {+ const { calls, fetcher } = deferredFetcher();+ const { slice, store } = setup({ fetcher });++ const stale = slice.fetch({ id: 'a' });+ const fresh = slice.fetch({ id: 'a' }, { fresh: true });+ expect(fetcher).toHaveBeenCalledTimes(2);++ // The pre-mutation request answers first: it may not paint even briefly.+ calls[0].resolve(['before mutation']);+ await expect(stale).resolves.toMatchObject({ applied: false });+ expect(store.getState().lists.a).toBeUndefined();++ calls[1].resolve(['after mutation']);+ await expect(fresh).resolves.toMatchObject({ applied: true });+ expect(store.getState().lists.a).toEqual(['after mutation']);+ });++ it('keeps no retirement records once nothing older is in flight', async () => {+ const { slice } = setup();++ for (let index = 0; index < 50; index++) {+ await slice.fetch({ id: `doc-${index}` });+ await slice.fetch({ id: `doc-${index}` }, { fresh: true });+ }++ expect(slice.debugRetiredRequests()).toBe(0);+ });++ it('keeps a retirement while an older request is in flight, then prunes it', async () => {+ const { calls, fetcher } = deferredFetcher();+ const { slice, store } = setup({ fetcher });++ const older = slice.fetch({ id: 'a' });+ const newer = slice.fetch({ id: 'a' }, { fresh: true });+ calls[1].resolve(['newer']);+ await newer;+ // The older request is still pending: its retirement must survive pruning.+ expect(slice.debugRetiredRequests()).toBe(1);++ calls[0].resolve(['older']);+ await expect(older).resolves.toMatchObject({ applied: false });+ expect(store.getState().lists.a).toEqual(['newer']);+ expect(slice.debugRetiredRequests()).toBe(0);+ });++ it('drops an older response once a newer one for the entry has applied', async () => {+ const { calls, fetcher } = deferredFetcher();+ const { slice, store } = setup({ fetcher });++ const older = slice.fetch({ id: 'a' });+ const newer = slice.fetch({ id: 'a' }, { fresh: true });+ calls[1].resolve(['newer']);+ await newer;+ calls[0].resolve(['older']);++ await expect(older).resolves.toMatchObject({ applied: false });+ expect(store.getState().lists.a).toEqual(['newer']);+ });++ it('seeds the driver cache under the sync key only while no useSync request is in flight', async () => {+ const seed = vi.fn();+ const driver: ReplicaSyncDriver = { ...testDriver, seed };+ const { slice } = setup({ driver });++ await slice.fetch({ id: 'a' });++ expect(seed).toHaveBeenCalledWith(+ replicaKeys.sync('fetchList', 1, 'user-1:personal', 'a', { id: 'a' }),+ ['server'],+ );++ const { calls, fetcher } = deferredFetcher();+ const joined = setup({ driver, fetcher });+ seed.mockClear();+ renderHook(() => joined.slice.useSync({ id: 'b' }), { wrapper });+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));+ const pending = joined.slice.fetch({ id: 'b' });+ await act(async () => calls[0].resolve(['server']));+ await pending;+ // The mounted query fills its own cache entry.+ expect(seed).not.toHaveBeenCalled();+ });++ it('works with a driver that has no cache of its own', async () => {+ const driver: ReplicaSyncDriver = {+ revalidate: vi.fn(async () => undefined),+ useQuery: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),+ };+ const { slice, store } = setup({ driver });++ await expect(slice.fetch({ id: 'a' })).resolves.toMatchObject({ applied: true });+ expect(store.getState().lists.a).toEqual(['server']);+ });+});diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.tsindex 596f2e19e29..91a8fa981ae 100644--- a/packages/replica/src/zustand/createReplicaSlice.ts+++ b/packages/replica/src/zustand/createReplicaSlice.ts@@ -5,6 +5,7 @@ import { createReplicaEngine, type ReplicaEngineOptions } from '../core/engine';import { isReplicaSyncKey, replicaKeys } from '../core/keys';import type { ReplicaPagedData } from '../core/paging';import type { ReplicaViewWrite } from '../core/reducer';+import { DEFAULT_REMOVAL_TOMBSTONE_LIMIT } from '../core/tombstones';import type { ReplicaResource, ReplicaState } from '../core/types';import type { ReplicaSyncDriver, ReplicaSyncSchedule } from './driver';@@ -43,6 +44,12 @@ export interface CreateReplicaSliceOptions<TStore, TParams, TData, TFetched> ext> {/** Query cache that schedules fetches (see `createSWRDriver`). */driver: ReplicaSyncDriver;+ /**+ * Side effects of the resource itself, run by every head response β a+ * mounted `useSync` and an imperative `fetch` alike β after the response is+ * folded in (see {@link ReplicaEffects}).+ */+ effects?: ReplicaEffects<TParams, TFetched>;get: () => TStore;set: Setter<TStore>;/** Store field holding the {@link ReplicaState} bookkeeping slot. */@@ -70,6 +77,84 @@ export interface ReplicaSyncErrorContext {scope: string;}+/** Where a settled head response was captured, for {@link ReplicaEffects}. */+export interface ReplicaSettleContext {+ key: string;+ /** The cache scope the request was captured under (the active one, except for `onPurge`). */+ scope: string;+ /** Which path requested it: a mounted `useSync`, or `slice.fetch`. */+ source: 'fetch' | 'sync';+}++/**+ * Resource-level side effects of head responses. Unlike `useSync`'s per-call+ * `onSuccess` / `onError` (UI callbacks of one mounted view), these run for+ * every response the resource settles, whichever path requested it β so a+ * store that fetches while no view is mounted keeps the same side effects.+ *+ * They run only for a response that passed every guard (clear, removal, active+ * query, a newer response already applied) and, for `onApplied` / `onMissing`,+ * only when its captured scope is still the active one.+ */+export interface ReplicaEffects<TParams, TFetched> {+ /**+ * A response was folded into the active scope (`prepareHead` kept it and it+ * is not a terminal absence). Runs even when the value did not change.+ */+ onApplied?: (data: TFetched, params: TParams, context: ReplicaSettleContext) => void;+ /**+ * A failed head read. Like `useSync`'s `onError`, it is forwarded off-scope+ * too, with `isActive: false`: use the captured key / scope to clean up that+ * scope, and touch the view on screen only when `isActive`.+ */+ onError?: (error: unknown, params: TParams, context: ReplicaSyncErrorContext) => void;+ /**+ * The response was a terminal absence (`isMissing`) and the entry was+ * removed from the active scope. An absence captured under a scope the store+ * has left purges that scope's row and runs `onPurge` instead.+ */+ onMissing?: (params: TParams, context: ReplicaSettleContext) => void;+ /**+ * A terminal absence captured under a scope the store has since left. The+ * entry's row in that scope is already purged; purge what other resources+ * keep of it there (a linked list row). Never touch the view on screen.+ */+ onPurge?: (params: TParams, context: ReplicaSettleContext) => void;+}++export interface ReplicaFetchOptions {+ /**+ * Start a new request even when one for the same entry is in flight, and+ * retire every request started before it: a late response of an older one+ * is dropped instead of applied. Use it for refreshes after a mutation,+ * where an in-flight request may hold the pre-mutation value. By default+ * `fetch` joins the request in flight (a `useSync` one or another `fetch`).+ */+ fresh?: boolean;+ /**+ * The cache scope the fetch belongs to, captured by a caller that started a+ * multi-step flow earlier (a warmup fanning out from a parent response). The+ * response settles into that scope under the same off-scope rules as any+ * other. When the scope is no longer active the fetch rejects without a+ * request: it would read the new identity's data under the old one's label.+ * Defaults to the active scope.+ */+ scope?: string;+}++export interface ReplicaFetchResult<TFetched> {+ /**+ * Whether the response was settled into the active scope: folded in, or+ * applied as a terminal absence. `false` when a guard dropped it (scope+ * switch, `remove` / `clear` mid-flight, superseded) or `prepareHead` did.+ */+ applied: boolean;+ /** The response as fetched, also when it was not applied. */+ data: TFetched;+ /** The response was a terminal absence (`isMissing`), in whichever scope. */+ missing: boolean;+}+export interface ReplicaSyncOptions<TFetched = unknown,TData = unknown,@@ -91,7 +176,9 @@ export interface ReplicaSyncOptions<onHydrated?: (data: TData) => void;/*** Side effects of a response, run after it is folded into the replica- * (e.g. adopting an active id, or settling a "not found" state).+ * (e.g. adopting an active id). UI callbacks of this view only: effects every+ * response of the resource needs belong in the slice's `effects`, which+ * `fetch` runs too.*/onSuccess?: (data: TFetched) => void;}@@ -106,6 +193,61 @@ export interface ReplicaSyncResult {revalidate: () => Promise<unknown>;}+/** `slice.fetch` was asked to fetch for a scope that is no longer active. */+export class ReplicaScopeChangedError extends Error {+ constructor(name: string, scope: string) {+ super(`[replica] ${name}: scope ${scope} is no longer active`);+ this.name = 'ReplicaScopeChangedError';+ }+}++/** One head request, from `begin` to `settle`. */+interface ReplicaRequest<TParams, TFetched> {+ /** `clear()` generation of `scope` when the request started. */+ clearGeneration: number;+ key: string;+ params: TParams;+ /** Settles the request; set once it is sent. */+ promise?: Promise<TFetched>;+ /** Row key of the query it asks for (`headQuery` guard). */+ queryKey: string;+ /** `remove` generation of `scope` + `key` when the request started. */+ removalGeneration: number;+ /** Scope + sync key: requests of the same id dedupe and supersede each other. */+ requestId: string;+ /** The cache scope it was captured under. */+ scope: string;+ /** Start order across the slice. */+ seq: number;+ /** What it settled to; a request is settled once (a joined fetch and its sync share it). */+ settled?: ReplicaSettled;+ /** The response (or failure) it settled with. */+ settledWith?: unknown;+ source: 'fetch' | 'sync';+ syncKey: readonly unknown[];+}++interface ReplicaSettled {+ /** Settled into the active scope (folded in or removed as missing). */+ applied: boolean;+ /** Passed every guard; `isActive` says whether its scope is still on screen. */+ current: boolean;+ isActive: boolean;+ missing: boolean;+}++type ReplicaOutcome<TFetched> = { data: TFetched } | { error: unknown };++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.*@@ -119,6 +261,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(resource: ReplicaResource<TParams, TData, TFetched>,{driver,+ effects,get,set,stateKey,@@ -184,8 +327,16 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(},revalidate,});- const { clearGeneration, ensureScope, fetcher, hydrate, removalGeneration, replace, retain } =- engine;+ const {+ applyHead,+ clearGeneration,+ ensureScope,+ fetcher,+ hydrate,+ isMissingHead,+ removalGeneration,+ retain,+ } = engine;/*** Row key of the head query each entry last asked for. One entry backs a@@ -207,14 +358,296 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(const hydratedEntries = new Set<string>();const hydratedEntryId = (scope: string, key: string) => `${scope}\u0000${key}`;+ // ---- one settle pipeline ---------------------------------------------+ // Every head response β a mounted `useSync`, or `fetch` with no view mounted+ // β is captured by `begin` when its request starts and folded in by `settle`,+ // so every path applies the same guards and the same resource effects.++ let requestSeq = 0;++ /**+ * Requests whose start order is at or below this number are retired, per+ * request id: a newer response already applied, or a `fresh` fetch started+ * after them. Their late response would repaint an older value.+ *+ * An entry only matters while a request it retires is still unsettled:+ * every request started later has a higher sequence, so a missing entry+ * (read as 0) admits exactly the same responses. Entries are pruned as soon+ * as no sent request at or below them is pending, so the map holds only the+ * ids with an older request in flight.+ */+ const retiredThrough = new Map<string, number>();+ /** Sequences of the sent requests that have not settled yet, per request id. */+ const unsettled = new Map<string, Set<number>>();++ /** Drop the retirement of `requestId` once no request it retires is pending. */+ const pruneRetired = (requestId: string) => {+ const through = retiredThrough.get(requestId);+ if (through === undefined) return;+ for (const seq of unsettled.get(requestId) ?? []) if (seq <= through) return;+ retiredThrough.delete(requestId);+ };++ const retire = (requestId: string, seq: number) => {+ if ((retiredThrough.get(requestId) ?? 0) < seq) retiredThrough.set(requestId, seq);+ pruneRetired(requestId);+ // Backstop: never more ids than a removal tombstone window. Only an entry+ // with no older request pending may go β evicting one that still retires+ // a request in flight would let its stale response win.+ if (retiredThrough.size <= DEFAULT_REMOVAL_TOMBSTONE_LIMIT) return;+ for (const id of retiredThrough.keys()) {+ pruneRetired(id);+ if (retiredThrough.size <= DEFAULT_REMOVAL_TOMBSTONE_LIMIT) return;+ }+ };++ const trackUnsettled = ({ requestId, seq }: ReplicaRequest<TParams, TFetched>) => {+ const pending = unsettled.get(requestId) ?? new Set<number>();+ unsettled.set(requestId, pending);+ pending.add(seq);+ };++ const untrackUnsettled = ({ requestId, seq }: ReplicaRequest<TParams, TFetched>) => {+ const pending = unsettled.get(requestId);+ if (!pending?.delete(seq)) return;+ if (pending.size === 0) unsettled.delete(requestId);+ pruneRetired(requestId);+ };++ /** The latest request in flight per id, which a non-`fresh` `fetch` joins. */+ const inflight = new Map<string, ReplicaRequest<TParams, TFetched>>();+ /** `useSync` requests in flight per id (`fetch` seeds the driver only while none is). */+ const syncInflight = new Map<string, number>();++ /**+ * `useSync` request each sync id last started, settled by the driver's+ * callback. The driver settles one request per key at a time (a newer+ * request supersedes the older one), so the latest start is the one that+ * settles.+ */+ const syncRequests = new Map<string, ReplicaRequest<TParams, TFetched>>();++ const syncKeyOf = (params: TParams, scope: string, key: string) =>+ resource.syncKey?.(params) ??+ replicaKeys.sync(resource.name, resource.version, scope, key, params);++ /** Capture what a head request for `params` started under. */+ const begin = (+ params: TParams,+ scope: string,+ source: 'fetch' | 'sync',+ ): ReplicaRequest<TParams, TFetched> => {+ const key = resource.key(params);+ const syncKey = syncKeyOf(params, scope, key);+ return {+ clearGeneration: clearGeneration(scope),+ key,+ params,+ queryKey: resource.storageKey(params),+ removalGeneration: removalGeneration(scope, key),+ requestId: `${scope}\u0000${stableQueryKey(syncKey)}`,+ scope,+ seq: ++requestSeq,+ source,+ syncKey,+ };+ };++ /** Send the request and track it in flight until it settles. */+ const send = (request: ReplicaRequest<TParams, TFetched>) => {+ const { requestId } = request;+ const sent = fetcher!(request.params, undefined);+ // Tolerate a fetcher (a test double) that does not return a promise: the+ // driver still gets exactly what it returned.+ const promise = Promise.resolve(sent);+ request.promise = promise;+ // Until it settles, a retirement that covers it must be kept.+ trackUnsettled(request);+ inflight.set(requestId, request);+ if (request.source === 'sync')+ syncInflight.set(requestId, (syncInflight.get(requestId) ?? 0) + 1);+ const done = () => {+ if (inflight.get(requestId) === request) inflight.delete(requestId);+ if (request.source !== 'sync') return;+ const count = (syncInflight.get(requestId) ?? 1) - 1;+ if (count > 0) syncInflight.set(requestId, count);+ else syncInflight.delete(requestId);+ };+ promise.then(done, done);+ // A `useSync` request settles on its own response, not only through the+ // driver's callback: a driver skips that callback once the hook moved to+ // another key, unmounted, or a newer request superseded it β and the+ // resource effects (a terminal absence, a purge) must not depend on which+ // view is still mounted. The callback then reads the memoized result.+ if (request.source === 'sync')+ promise.then(+ (data) => settle(request, { data }),+ (error: unknown) => settle(request, { error }),+ );+ return sent;+ };++ /**+ * Whether the request still answers the query its entry shows. A `useSync`+ * request must match the query the entry last asked for (see `headQuery`). A+ * `fetch` may also land with no view mounted, but never over a view that+ * shows another query of the key.+ */+ const isActiveQuery = ({ key, queryKey, source }: ReplicaRequest<TParams, TFetched>) => {+ const head = headQuery.get(key);+ return source === 'sync' ? head === queryKey : head === undefined || head === queryKey;+ };++ const settleOnce = (+ request: ReplicaRequest<TParams, TFetched>,+ outcome: ReplicaOutcome<TFetched>,+ ): ReplicaSettled => {+ const { key, params, scope } = request;+ /**+ * Whether the entry is still on the scope the request was captured under.+ *+ * A response can settle after an identity/workspace switch. `replace` drops+ * it β the engine refuses off-scope actions β but no side effect may run+ * either: it carries the previous identity's state (onboarding redirect,+ * display snapshot, analytics identify, settings writes). The captured+ * key/scope is not enough on its own, because a switch to a scope that+ * reads the same key/query satisfies the other guards.+ */+ const isActive = resource.scope.get() === scope;+ const dropped: ReplicaSettled = { applied: false, current: false, isActive, missing: false };++ // Discard a response that started before a `clear()` of its scope or a+ // `remove` of its entry (it holds wiped data), one for a query the entry+ // has moved past (the newer query owns the view, see `headQuery`), and one+ // older than a response already applied or a `fresh` fetch.+ if (+ request.clearGeneration !== clearGeneration(scope) ||+ request.removalGeneration !== removalGeneration(scope, key) ||+ request.seq <= (retiredThrough.get(request.requestId) ?? 0) ||+ !isActiveQuery(request)+ )+ return dropped;++ if ('error' in outcome) {+ // Forwarded even off-scope: the captured `key`/`scope` lets a consumer+ // purge that scope's row (a late NOT_FOUND / FORBIDDEN) without touching+ // the scope on screen; `isActive` tells it whether the failure also+ // belongs to the view on screen.+ effects?.onError?.(outcome.error, params, { isActive, key, scope });+ return { ...dropped, current: true };+ }++ if (!isActive) {+ // Off-scope: never fold a value into the scope on screen. A terminal+ // absence still purges its own scope's row (`remove` routes it there), so+ // a switch back cannot hydrate a value the server no longer has.+ const missing = isMissingHead(outcome.data);+ if (missing) {+ remove(key, scope);+ effects?.onPurge?.(params, { key, scope, source: request.source });+ }+ return { ...dropped, current: true, missing };+ }++ retire(request.requestId, request.seq - 1);+ const { outcome: folded } = applyHead(params, outcome.data, scope);+ const context: ReplicaSettleContext = { key, scope, source: request.source };+ if (folded === 'replaced') effects?.onApplied?.(outcome.data, params, context);+ else if (folded === 'missing') effects?.onMissing?.(params, context);+ return {+ applied: folded !== 'dropped',+ current: true,+ isActive,+ missing: folded === 'missing',+ };+ };++ /**+ * Fold a settled head request into the replica: apply every guard, then+ * `replace` / remove a terminal absence (in the captured scope) / purge one+ * captured off-scope, then run the resource effects. A request is settled+ * once: a `fetch` that joined a `useSync` request shares its result.+ */+ const settle = (+ request: ReplicaRequest<TParams, TFetched>,+ outcome: ReplicaOutcome<TFetched>,+ ): ReplicaSettled => {+ if (request.settled) return request.settled;+ request.settledWith = 'error' in outcome ? outcome.error : outcome.data;+ request.settled = settleOnce(request, outcome);+ untrackUnsettled(request);+ if (request.source === 'sync') releaseSyncRequest(request);+ return request.settled;+ };+/**- * `clear()` generation each in-flight head request started under, by sync- * key. A response to a request that started before a `clear()` of its scope- * holds wiped data and is discarded. The driver settles one request per key- * at a time (a newer request supersedes the older one), so the latest start- * is the one that settles.+ * Drop a settled `useSync` request's record once its driver callback had its+ * chance to read it. The record is normally taken by that callback, but the+ * driver skips it when the hook changed key, unmounted or was superseded β+ * the request still settles on its own promise, and its record (holding the+ * response) must not stay behind. A driver runs the callback in the same+ * turn the response resolves (SWR does, in microtasks), so a macrotask later+ * the record is only a leak.*/- const requestGeneration = new Map<string, { clear: number; removal: number }>();+ const releaseSyncRequest = (request: ReplicaRequest<TParams, TFetched>) => {+ setTimeout(() => {+ if (syncRequests.get(request.requestId) === request) syncRequests.delete(request.requestId);+ }, 0);+ };++ /**+ * Fetch the head of an entry now and settle it like a `useSync` response β+ * for stores that need the data while no view is mounted (a hover prefetch,+ * a refresh after a mutation on a route without the list). `revalidate` only+ * re-runs mounted queries.+ *+ * Joins a request in flight for the same entry unless `fresh`. Resolves with+ * what was fetched and whether it was applied; rejects when the request+ * fails, after routing the failure through `effects.onError`.+ */+ const fetch = async (+ params: TParams,+ { fresh = false, scope = resource.scope.get() }: ReplicaFetchOptions = {},+ ): Promise<ReplicaFetchResult<TFetched>> => {+ if (!fetcher) throw new Error(`[replica] ${resource.name} has no fetcher`);+ if (scope !== resource.scope.get()) throw new ReplicaScopeChangedError(resource.name, scope);+ let request = begin(params, scope, 'fetch');+ const joined = fresh ? undefined : inflight.get(request.requestId);+ if (joined) request = joined;+ else {+ if (fresh) retire(request.requestId, request.seq - 1);+ send(request);+ }++ let data: TFetched;+ try {+ data = await request.promise!;+ } catch (error) {+ settle(request, { error });+ throw error;+ }+ const settled = settle(request, { data });+ // Seed the driver's cache with what this fetch applied, unless a `useSync`+ // request of the key is in flight: it fills the cache itself, and a write+ // overtaking it could make the driver discard its newer response.+ if (settled.applied && request.source === 'fetch' && !syncInflight.has(request.requestId))+ driver.seed?.(request.syncKey, data);+ return { applied: settled.applied, data, missing: settled.missing };+ };++ /**+ * Forget the key's head query as well as the entry. A `useSync` request+ * already in flight for it would otherwise pass the settle guards (the+ * marker still matches), `replace` the entry and persist pre-mutation rows+ * back over an invalidation that has already completed. (The engine's+ * removal generation drops a `fetch` captured before the removal.)+ */+ const remove = (key: string, scope?: string) => {+ // Only the active scope's marker belongs to the entry on screen; an+ // off-scope removal (see `engine.remove`) must not drop it.+ if (scope === undefined || scope === resource.scope.get()) headQuery.delete(key);+ return engine.remove(key, scope);+ };/*** Hydrates the persisted row once per scope/key/query, then lets the driver@@ -318,77 +751,45 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(});}, [active, key, scope, hydration.data]);- const syncKey =- active && fetcher- ? (resource.syncKey?.(params!) ??- replicaKeys.sync(resource.name, resource.version, scope, key!, params))- : null;- const requestId = () => `${scope}\u0000${stableQueryKey(syncKey)}`;- /** Whether the request settling now still belongs to the entry's active query. */- const isActiveQuery = () => queryKey !== undefined && headQuery.get(key!) === queryKey;- /**- * Whether the settling request started after the latest `clear()` of its- * scope and after the latest removal of its entry (a deleted / pruned entry- * must not be recreated by a response that was already in flight).- */- const isSinceClear = () => {- const id = requestId();- const started = requestGeneration.get(id);- requestGeneration.delete(id);- return (- started === undefined ||- (started.clear === clearGeneration(scope) &&- started.removal === removalGeneration(scope, key!))- );+ const syncKey = active && fetcher ? syncKeyOf(params!, scope, key!) : null;+ /** The request settling now: the one this sync id last started. */+ const takeRequest = (response: unknown) => {+ const requestId = `${scope}\u0000${stableQueryKey(syncKey)}`;+ const request = syncRequests.get(requestId);+ syncRequests.delete(requestId);+ // The request already settled on its own response, and the driver now+ // reports that same response: read the memoized result.+ if (request && (!request.settled || request.settledWith === response)) return request;+ // A response the driver settles without having run our fetcher (a+ // cache-shared key), or one the recorded request did not produce, is+ // captured now: nothing it started under is known.+ return begin(params!, scope, 'sync');};- /**- * Whether the entry is still on the scope the request was captured under.- *- * A response can settle after an identity/workspace switch. `replace` drops- * it β the engine refuses off-scope actions β but the caller's `onSuccess`- * must not run either: it carries the previous identity's side effects- * (onboarding redirect, display snapshot, analytics identify, settings- * writes). The captured key/scope is not enough on its own, because a switch- * to a scope that reads the same key/query satisfies both guards above.- */- const isActiveScope = () => resource.scope.get() === scope;const sync = driver.useQuery<TFetched>(syncKey,() => {- requestGeneration.set(requestId(), {- clear: clearGeneration(scope),- removal: removalGeneration(scope, key!),- });- return fetcher!(params!, undefined);+ const request = begin(params!, scope, 'sync');+ syncRequests.set(request.requestId, request);+ return send(request);},{...schedule,- // A failure of a query the entry has moved past (or of a request from- // before a clear) must not surface on the query now on screen. Unlike- // success, an off-scope failure is still forwarded: the captured- // key/scope is bound so a late terminal answer (NOT_FOUND / FORBIDDEN)- // can purge *its own* scope's persisted row via `remove(key, scope)`- // without touching the scope now on screen β dropping it would leave- // that row to hydrate again when the user switches back.- // Always installed, so a failed request's generation record is dropped- // even when the caller has no error side effects.+ // Always installed, so a failed request is settled (and its capture+ // dropped) even when the caller has no error side effects. A failure+ // of a query the entry has moved past (or of a request from before a+ // clear) never surfaces on the query now on screen; an off-scope one is+ // still forwarded with the captured key/scope (see `settle`).onError: (error: unknown) => {- if (!isSinceClear() || !isActiveQuery()) return;- // Forwarded even off-scope: the captured `key`/`scope` lets a consumer- // purge that scope's row. `isActive` tells it whether the failure also- // belongs to the view on screen.- onError?.(error, { isActive: isActiveScope(), key, scope });+ const settled = settle(takeRequest(error), { error });+ if (settled.current) onError?.(error, { isActive: settled.isActive, key, scope });},onSuccess: (data) => {- // Discard a head response the entry has moved past (the newer query- // owns the view, see `headQuery`), one that started before a clear, or- // one captured under a scope the store has since left.- if (!isSinceClear() || !isActiveQuery() || !isActiveScope()) return;- replace(params!, data, scope);- // The same holds for a key the hook has moved past (g1 β g2 while- // g1's request is in flight): the response still fills g1's own- // entry, but its side effects would re-adopt g1 over the g2 view.+ const settled = settle(takeRequest(data), { data });+ if (!settled.current || !settled.isActive) return;+ // A key the hook has moved past (g1 β g2 while g1's request is in+ // flight): the response still fills g1's own entry, but this view's+ // side effects would re-adopt g1 over the g2 view.if (activeKey.current !== key) return;onSuccess?.(data);},@@ -413,18 +814,12 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(return {...engine,- /**- * Forget the key's head query as well as the entry. A request already in- * flight for it would otherwise pass the `onSuccess` guard below (the marker- * still matches), `replace` the entry and persist pre-mutation rows back over- * an invalidation that has already completed.- */- remove: (key: string, scope?: string) => {- // Only the active scope's marker belongs to the entry on screen; an- // off-scope removal (see `engine.remove`) must not drop it.- if (scope === undefined || scope === resource.scope.get()) headQuery.delete(key);- return engine.remove(key, scope);- },+ /** @internal Records of `useSync` requests not yet released (leak checks in tests). */+ debugPendingSyncRequests: () => syncRequests.size,+ /** @internal Retirement records still held (leak checks in tests). */+ debugRetiredRequests: () => retiredThrough.size,+ fetch,+ remove,useSync,};};diff --git a/packages/replica/src/zustand/driver.ts b/packages/replica/src/zustand/driver.tsindex 96d2a2bb49b..110c31ffe7e 100644--- a/packages/replica/src/zustand/driver.ts+++ b/packages/replica/src/zustand/driver.ts@@ -41,6 +41,18 @@ export interface ReplicaQueryResult<T> {export interface ReplicaSyncDriver {/** Re-run every mounted query whose key matches. */revalidate: (match: (key: unknown) => boolean) => Promise<unknown>;+ /**+ * Write a head response that `slice.fetch` requested outside `useQuery` into+ * the query cache under its sync key, without re-running the query β so a+ * `useQuery` of that key sees the latest data (a `revalidateIfStale: false`+ * mount does not refetch it). Optional: a driver without a cache of its own+ * leaves it out; requests still dedupe in the slice.+ *+ * The slice calls it only while no `useQuery` request of the key is in+ * flight. A cache that discards in-flight requests a write overtakes (SWR+ * does) would otherwise drop a newer response than the one written.+ */+ seed?: (key: readonly unknown[], data: unknown) => void;useQuery: <T>(key: readonly unknown[] | null,fetcher: () => Promise<T>,@@ -62,10 +74,21 @@ export const createSWRDriver = ({mutate,useSWR,}: {- mutate: (match: (key: any) => boolean) => Promise<unknown>;+ /**+ * SWR's (scoped) `mutate`. Called as `mutate(match)` to revalidate, and as+ * `mutate(key, data, { revalidate: false })` to seed β pass the arguments+ * through unchanged: SWR tells a revalidation from a write by their count.+ */+ mutate: (+ ...args: [match: (key: any) => boolean] | [key: unknown, data: unknown, options: object]+ ) => Promise<unknown>;useSWR: SWRLikeHook;}): ReplicaSyncDriver => ({revalidate: (match) => mutate(match),+ // Populate the cache only: re-running the query would refetch what was just fetched.+ seed: (key, data) => {+ void mutate(key, data, { revalidate: false }).catch(() => undefined);+ },useQuery: (key, fetcher, { once, onError, onSuccess, ...schedule }) =>useSWR(key, fetcher, {...Object.fromEntries(Object.entries(schedule).filter(([, value]) => value !== undefined)),diff --git a/packages/replica/tests/testDriver.ts b/packages/replica/tests/testDriver.tsindex 08a093fd9c6..71d7466dab8 100644--- a/packages/replica/tests/testDriver.ts+++ b/packages/replica/tests/testDriver.ts@@ -2,5 +2,8 @@ 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 });+/** SWR driver for tests: plain `useSWR`, matcher revalidation and seeding on the default cache. */+export const testDriver = createSWRDriver({+ mutate: (...args) => (mutate as (...args: unknown[]) => Promise<unknown>)(...args),+ useSWR,+});diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.tsindex 467b7caf3dc..7bd97200e2f 100644--- a/src/libs/replica/index.ts+++ b/src/libs/replica/index.ts@@ -112,7 +112,8 @@ export const definePagedReplica = <// 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),+ // Arguments pass through as given: SWR tells a revalidation from a write by their count.+ mutate: (...args) => (mutate as (...args: unknown[]) => Promise<unknown>)(...args),useSWR: (key, fetcher, config) => useClientDataSWR(key, fetcher, config),});diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex b64b6e1afc6..fa4358271e6 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -1569,6 +1569,39 @@ describe('AgentSlice Actions', () => {});expect(agentService.getAgentConfigById).toHaveBeenCalledTimes(1);});++ it('settles a prefetched "not found" the way the page sync does', async () => {+ vi.mocked(agentService.getAgentConfigById).mockResolvedValue(null as any);++ await act(async () => {+ await useAgentStore.getState().prefetchAgentConfig('agent-prefetch-gone');+ });++ expect(useAgentStore.getState().agentNotFoundMap['agent-prefetch-gone']).toBe(true);+ expect(useAgentStore.getState().agentMap['agent-prefetch-gone']).toBeUndefined();+ });++ it('does not let a late prefetch resurrect an agent the page settled as not found', async () => {+ const agentId = 'agent-prefetch-late';+ let resolvePrefetch!: (value: unknown) => void;+ vi.mocked(agentService.getAgentConfigById)+ .mockImplementationOnce(() => new Promise((resolve) => (resolvePrefetch = resolve)) as any)+ .mockResolvedValue(null as any);++ const prefetch = useAgentStore.getState().prefetchAgentConfig(agentId);+ // Navigation mounts the page's own sync, which learns the agent is gone.+ renderHook(() => useAgentStore().useFetchAgentConfig(true, agentId), { wrapper: withSWR });+ await waitFor(() => expect(useAgentStore.getState().agentNotFoundMap[agentId]).toBe(true));++ // The hover prefetch started earlier and answers last, with the old config.+ await act(async () => {+ resolvePrefetch({ id: agentId, title: 'Stale' });+ await prefetch;+ });++ expect(useAgentStore.getState().agentMap[agentId]).toBeUndefined();+ expect(useAgentStore.getState().agentNotFoundMap[agentId]).toBe(true);+ });});describe('useHydrateAgentConfig', () => {diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex 9c0f668f5bb..b87ee634a7a 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -149,11 +149,23 @@ export class AgentSliceActionImpl {fetcher: async ({ agentId }) =>(await agentService.getAgentConfigById(agentId)) as LobeAgentConfig | null,get,+ // A successful fetch that resolves to null means the agent doesn't+ // exist or the caller lost access (e.g. a workspace agent switched back+ // to private) β a settled state, not "still loading". Every path that+ // fetches the config (the sync hooks and `prefetchAgentConfig`) settles+ // it the same way.+ effects: {+ onApplied: (_data, { agentId }) => this.#clearAgentNotFound(agentId),+ onMissing: ({ agentId }) => this.#markAgentNotFound(agentId),+ },+ // `null` drops the cached config (and its persisted row): surfaces+ // reading `agentMap` (title/avatar in the sidebar or header) must not+ // keep showing an agent the viewer lost access to next to the 404.+ isMissing: (incoming) => !incoming,// The endpoint returns a complete, authoritative profile: replace the// entry instead of patching it, so fields cleared on the server (e.g.- // `editorData: null`) don't survive from an older local copy. `null`- // (not found) is settled by the sync hooks; an unchanged profile keeps- // its reference.+ // `editorData: null`) don't survive from an older local copy. An+ // unchanged profile keeps its reference.merge: (incoming, confirmed) =>!incoming || isEqual(incoming, confirmed) ? undefined : incoming,set,@@ -171,19 +183,6 @@ export class AgentSliceActionImpl {this.#config.replace({ agentId }, data as LobeAgentConfig, scope);};- /** Fetch result of `useFetchAgentConfig` / `useHydrateAgentConfig`. */- #settleAgentConfigFetch = (agentId: string, data: LobeAgentConfig | null): boolean => {- // A successful fetch that resolves to null means the agent doesn't- // exist or the caller lost access (e.g. a workspace agent switched- // back to private) β a settled state, not "still loading".- if (!data) {- this.#markAgentNotFound(agentId);- return false;- }- this.#clearAgentNotFound(agentId);- return true;- };-#toAgentConfigSyncResult = (sync: ReplicaSyncResult, agentId: string): AgentConfigSyncResult => ({...sync,isLoading: sync.isValidating && !this.#get().agentMap[agentId],@@ -503,7 +502,8 @@ export class AgentSliceActionImpl {);},onSuccess: (data) => {- if (!this.#settleAgentConfigFetch(agentId, data)) return;+ // Not found is settled by the resource effects.+ if (!data) return;// Only adopt the fetched agent as the active one when nothing is// active yet. The active agent is owned by the route-level sync// (AgentIdSync on desktop/mobile, the popup pages' own setState).@@ -514,7 +514,7 @@ export class AgentSliceActionImpl {// back to the inbox ("Lobe AI") agent. A response of a previous scope// never lands in `agentMap`, so it adopts nothing either.if (!this.#get().activeAgentId && this.#get().agentMap[agentId]) {- this.#set({ activeAgentId: data!.id }, false, 'fetchAgentConfig');+ this.#set({ activeAgentId: data.id }, false, 'fetchAgentConfig');}this.#clearAgentConfigError(agentId);},@@ -548,9 +548,9 @@ export class AgentSliceActionImpl {*/prefetchAgentConfig = async (agentId: string): Promise<void> => {if (!agentId || this.#get().agentMap[agentId]) return;- const scope = getCacheScope();- const data = await agentService.getAgentConfigById(agentId);- if (data) this.#replaceConfirmedAgentConfig(agentId, scope, data as LobeAgentConfig);+ // Joins the page's own sync when it is already in flight; the replica+ // applies the scope / removal / clear guards and the not-found effects.+ await this.#config.fetch({ agentId });};#markAgentNotFound = (agentId: string) => {@@ -562,9 +562,9 @@ export class AgentSliceActionImpl {false,'markAgentNotFound',);- // Also drop the previously cached config (and its persisted row): surfaces- // reading `agentMap` (title/avatar in the sidebar or header) must not keep- // showing an agent the viewer lost access to next to the 404 content area.+ // Also forget the head query of the dropped config (the `null` response+ // already removed it and its persisted row): a request in flight from+ // before must not repaint the agent next to the 404 content area.this.#config.remove(agentId);};@@ -601,9 +601,9 @@ export class AgentSliceActionImpl {isLogin: boolean | undefined,agentId: string,): AgentConfigSyncResult => {+ // The not-found state is settled by the resource effects.const sync = this.#config.useSync(agentId ? { agentId } : null, {enabled: isLogin === true && !isChatGroupSessionId(agentId),- onSuccess: (data) => void this.#settleAgentConfigFetch(agentId, data),});return this.#toAgentConfigSyncResult(sync, agentId);diff --git a/src/store/agent/slices/builtin/action.ts b/src/store/agent/slices/builtin/action.tsindex 97e2f5c7148..87ea27b5cff 100644--- a/src/store/agent/slices/builtin/action.ts+++ b/src/store/agent/slices/builtin/action.ts@@ -99,8 +99,14 @@ export class BuiltinAgentSliceActionImpl {this.#get = get;this.#builtin = createReplicaSlice(builtinAgentResource, {actionPrefix: 'builtinAgent',+ // Every confirmed builtin re-seeds `agentMap`, whichever path fetched it+ // (the mount-time sync or `refreshBuiltinAgent`). Only for the active+ // scope: a response of a previous identity never reaches it.+ effects: { onApplied: (item) => this.#seedAgentMap(item) },fetcher: fetchBuiltinAgent,get,+ // A row without an id cannot be resolved by slug: keep what is cached.+ prepareHead: (item) => (item?.id ? item : undefined),set,stateKey: 'builtinAgentReplica',view: builtinAgentLens,@@ -147,17 +153,13 @@ export class BuiltinAgentSliceActionImpl {** Imperative by design: unlike the mount-time `useInitBuiltinAgent` sync, it* does not depend on a mounted subscriber, so the create-Agent / create-Page- * flows can ensure a slug resolves on demand.- *- * The scope is captured before the await: when the identity changes while the- * request is in flight, the late response is not written into the new scope,- * matching the guard the swap-era code applied with `scope === getCacheScope()`.+ * flows can ensure a slug resolves on demand. It runs after edits, so it+ * never reuses a request already in flight (`fresh`): that one may hold the+ * pre-edit value. The replica drops a response that lands after an identity+ * switch, a removal or a clear.*/refreshBuiltinAgent = async (slug: string): Promise<void> => {- const scope = cacheScope.get();- const data = await fetchBuiltinAgent({ slug });- if (!data?.id) return;- this.internal_replaceBuiltinAgent(slug, data, scope);+ await this.#builtin.fetch({ slug }, { fresh: true });};useInitBuiltinAgent = (diff --git a/src/store/agent/slices/builtin/replica.test.ts b/src/store/agent/slices/builtin/replica.test.tsindex d18c5c99c72..fab4aa05675 100644--- a/src/store/agent/slices/builtin/replica.test.ts+++ b/src/store/agent/slices/builtin/replica.test.ts@@ -231,6 +231,32 @@ describe('builtin agent replica', () => {).toBeUndefined();});+ it('does not let a sync request from before an edit overwrite the post-edit refresh', async () => {+ const answers: ((value: any) => void)[] = [];+ vi.mocked(agentService.getBuiltinAgent).mockImplementation(+ () => new Promise((resolve) => answers.push(resolve)),+ );++ // The mounted sync asks first, then an edit refreshes the builtin.+ renderHook(() => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }), {+ wrapper,+ });+ await waitFor(() => expect(answers).toHaveLength(1));+ const refresh = useAgentStore.getState().refreshBuiltinAgent('inbox');+ // The refresh never reuses the pre-edit request.+ expect(answers).toHaveLength(2);++ await act(async () => {+ answers[1](builtin('inbox-1', { name: 'Edited chief' }));+ await refresh;+ });+ // The pre-edit read answers last.+ await act(async () => answers[0](builtin('inbox-1', { name: 'Old chief' })));++ expect(useAgentStore.getState().builtinAgentMap.inbox).toMatchObject({ name: 'Edited chief' });+ expect(useAgentStore.getState().agentMap['inbox-1']).toMatchObject({ name: 'Edited chief' });+ });+it('confirms a meta-edit response on the builtin without a network round-trip', () => {act(() => {useAgentStore.setState({diff --git a/src/store/agentGroup/action.ts b/src/store/agentGroup/action.tsindex 45b4b780425..6cb2a32ee83 100644--- a/src/store/agentGroup/action.ts+++ b/src/store/agentGroup/action.ts@@ -135,6 +135,8 @@ class ChatGroupInternalAction implements ResetableStore {#droppedGroupIds: string[] = [];/** Bumped by every `loadGroups`; a late reconcile only runs for the latest. */#listLoadSeq = 0;+ /** The hydrate a starting `loadGroups` request waits for (see the list fetcher). */+ #listHydration: Promise<boolean> | undefined;constructor(set: Setter, get: () => ChatGroupStore, _api?: unknown) {// keep signature aligned with StateCreator params: (set, get, api)@@ -144,8 +146,24 @@ class ChatGroupInternalAction implements ResetableStore {this.#get = get;this.#groupList = createReplicaSlice(agentGroupListResource, {actionPrefix: 'agentGroupList',+ // The authoritative list reconciles `groupMap`, whichever path fetched+ // it (the mounted sync or `loadGroups`).+ effects: { onApplied: (groups) => this.#reconcileGroupMap(groups) },entity: agentGroupsEntity,- fetcher: () => chatGroupService.getGroups(),+ fetcher: async () => {+ // The persisted-list hydrate `loadGroups` started alongside this+ // request (captured now, see there).+ const hydration = this.#listHydration;+ const groups = await chatGroupService.getGroups();+ // Let a hydrate that is about to land paint first β the list `merge`+ // reads the hydrated rows to learn which ids the response drops β but+ // never let a stalled storage read hold back an authoritative response+ // that already arrived: creation flows await `loadGroups()` before+ // they navigate. A hydrate that lands after the replace is a no-op (it+ // only fills an empty slot).+ if (hydration) await settleWithin(hydration, PRE_PAINT_HYDRATE_TIMEOUT);+ return groups;+ },get,// The list is the authoritative parent of every detail, so remember the// rows a `replace` drops: a group that only ever hydrated from the@@ -165,22 +183,29 @@ class ChatGroupInternalAction implements ResetableStore {});this.#groupDetail = createReplicaSlice(agentGroupDetailResource, {actionPrefix: 'agentGroupDetail',- entity: agentGroupDetailEntity,- fetcher: async ({ groupId }) => {- const scope = this.#captureScope();- const groupDetail = await chatGroupService.getGroupDetail(groupId);- // `null` is a terminal "gone / no access" answer. Record it here, per- // key, rather than only in the hook's success callback: that callback- // is skipped once the hook moved to another group (or the driver drops- // it), and the stale detail would then be kept and replayed offline.- if (!groupDetail) this.#settleGroupGone(groupId, scope);- return groupDetail;+ // Resource-level, so every response settles them β a mounted sync (even+ // one the hook has moved past, whose own callback is skipped) and+ // `internal_fetchGroupDetail` alike. `null` is a terminal "gone / no+ // access" answer: the replica removes the detail in the scope the+ // request started under, and these drop the group from the other views.+ effects: {+ onApplied: (_detail, { groupId }) => this.#clearGroupNotFound(groupId),+ onMissing: ({ groupId }) => {+ this.#removeStaleGroup(groupId);+ this.#markGroupNotFound(groupId);+ },+ // A scope left behind keeps its view untouched β it is not on screen β+ // but its persisted list row drops the group too, so switching back+ // cannot hydrate it into the sidebar (indefinitely, offline, until+ // `getGroups()` answers). The replica already purged its detail row.+ onPurge: ({ groupId }, { scope }) => this.#groupRows.remove(groupId, { scope }),},+ entity: agentGroupDetailEntity,+ fetcher: ({ groupId }) => chatGroupService.getGroupDetail(groupId),get,- // The endpoint returns the complete, authoritative detail. `null` (gone /- // no access) is settled by the fetcher (see `#settleGroupGone`), not a- // value to paint. An unchanged detail keeps its reference so the group- // pages do not re-render.+ isMissing: (incoming) => !incoming,+ // The endpoint returns the complete, authoritative detail. An unchanged+ // detail keeps its reference so the group pages do not re-render.merge: (incoming, confirmed) =>!incoming || isEqual(incoming, confirmed) ? undefined : incoming,set,@@ -194,18 +219,6 @@ class ChatGroupInternalAction implements ResetableStore {this.#set(initialChatGroupState, false, n('reset'));};- /**- * The cache scope (`${userId}:${workspaceId}`) a request starts under. The- * full scope is what partitions the persisted replica rows, so it β not just- * the workspace id β is what an imperative response must be validated- * against: two users in personal mode share a `null` workspace, and a- * response started for one must never land in the other's partition.- */- #captureScope = (): string => cacheScope.get();-- /** Whether the identity a request started under is still the active one. */- #isStillInScope = (scope: string): boolean => cacheScope.get() === scope;-#removeStaleGroup = (groupId: string) => {const loaded = this.#get().groupMap[groupId] !== undefined;this.#groupRows.remove(groupId);@@ -215,24 +228,6 @@ class ChatGroupInternalAction implements ResetableStore {if (!loaded) this.#groupDetail.remove(groupId);};- /**- * A detail request answered "gone / no access" for `groupId` under `scope`.- * In the active scope the group leaves every view (and storage) and settles- * as not found. A scope left behind keeps its view untouched β it is not on- * screen β but its persisted detail and its persisted list row both drop the- * group, so switching back cannot hydrate it into the sidebar (indefinitely,- * offline, until `getGroups()` answers).- */- #settleGroupGone = (groupId: string, scope: string) => {- if (!this.#isStillInScope(scope)) {- this.#groupDetail.remove(groupId, scope);- this.#groupRows.remove(groupId, { scope });- return;- }- this.#removeStaleGroup(groupId);- this.#markGroupNotFound(groupId);- };-// A successful fetch that resolves to nothing means the group doesn't exist// or the caller lost access (e.g. switched back to private) β a settled// state the UI renders as a 404 card, not an error to retry.@@ -311,31 +306,16 @@ class ChatGroupInternalAction implements ResetableStore {this.#syncGroupAgents(groupDetail, { onlyIfNewer: true });};+ /**+ * Re-read a group's detail after a write, with or without a mounted page.+ * `fresh`: a request already in flight may hold the pre-write roster. The+ * replica applies the scope / removal / clear guards and settles a terminal+ * absence (see the slice `effects`); an applied detail is an explicit+ * refresh, so its roster always takes the server value.+ */internal_fetchGroupDetail = async (groupId: string) => {- const scope = this.#captureScope();- // The removal generation the request starts under: a group pruned or- // removed while the request is in flight must not be recreated by it (the- // same guard `useSync` applies to its own responses).- const removal = this.#groupDetail.removalGeneration(scope, groupId);- const groupDetail = await chatGroupService.getGroupDetail(groupId);- // A terminal "gone / no access" is settled in the scope the request started- // under β even after a switch, that scope's persisted detail is purged so- // switching back cannot hydrate the deleted / revoked group.- if (!groupDetail) {- this.#settleGroupGone(groupId, scope);- return;- }- // The request may resolve after a logout / account switch; its response- // belongs to the scope it started under, not the one active now.- if (!this.#isStillInScope(scope)) return;- // Removed while in flight: the response is older than the removal.- if (this.#groupDetail.removalGeneration(scope, groupId) !== removal) return;- this.#clearGroupNotFound(groupId);-- // Confirmed server detail: it paints the group page on the next visit too.- // The captured scope makes the write itself admit only its own identity.- this.#groupDetail.replace({ groupId }, groupDetail, scope);- this.#syncGroupAgents(groupDetail);+ const { applied, data } = await this.#groupDetail.fetch({ groupId }, { fresh: true });+ if (applied && data) this.#syncGroupAgents(data);};/**@@ -431,7 +411,7 @@ class ChatGroupInternalAction implements ResetableStore {* instead of being written (and persisted) into the next scope's partition.*/loadGroups = async () => {- const scope = this.#captureScope();+ const scope = cacheScope.get();// Drop the previous identity's list before anything else. After a workspace// switch the store stays mounted with `groupsInit` still true, so without// this the old workspace's groups linger through a slow / failed request and@@ -444,25 +424,25 @@ class ChatGroupInternalAction implements ResetableStore {: this.#groupList.hydrate(LIST_PARAMS, scope).finally(() => (hydrated = true));let hydrated = !hydration;// The persisted list ids, read alongside the hydrate. If the hydrate misses- // the bound below, the list `replace` cannot see which ids the response- // dropped (see `#droppedGroupIds`), so those are pruned from this snapshot.+ // the bound the fetcher waits for, the list `replace` cannot see which ids+ // the response dropped (see `#droppedGroupIds`), so those are pruned from+ // this snapshot.const persistedIds = hydration ? this.#readPersistedGroupIds(scope) : undefined;- const groups = await chatGroupService.getGroups();- // Let a hydrate that is about to land paint first, but never let a stalled- // storage read hold back an authoritative response that already arrived:- // creation flows await `loadGroups()` before they navigate. A hydrate that- // lands after the replace is a no-op (it only fills an empty slot).- if (hydration) await settleWithin(hydration, PRE_PAINT_HYDRATE_TIMEOUT);- if (!this.#isStillInScope(scope)) return;-- this.#groupList.replace(LIST_PARAMS, groups, scope);- this.#reconcileGroupMap(groups);+ // The request starts synchronously and captures the hydrate to wait for.+ // `fresh`: creation flows call this right after a write.+ this.#listHydration = hydration;+ const fetched = this.#groupList.fetch(LIST_PARAMS, { fresh: true });+ this.#listHydration = undefined;+ // Dropped by the replica (an identity switch, a clear) β and with it the+ // reconcile that `effects.onApplied` runs for an applied list.+ const { applied, data: groups } = await fetched;+ if (!applied) return;if (!hydrated && persistedIds) {const listedIds = new Set(groups.map((group) => group.id));void persistedIds.then((ids) => {// A newer list load (or an identity switch) owns the reconcile now.- if (load !== this.#listLoadSeq || !this.#isStillInScope(scope)) return;+ if (load !== this.#listLoadSeq || cacheScope.get() !== scope) return;const current = new Set(this.#get().groups.map((group) => group.id));for (const id of ids) {if (!listedIds.has(id) && !current.has(id)) this.#removeStaleGroup(id);@@ -510,18 +490,18 @@ class ChatGroupInternalAction implements ResetableStore {this.#groupDetail.useSync(groupId ? { groupId } : null, {enabled,onHydrated: (groupDetail) => this.#applyGroupDetail(groupId, groupDetail),- onSuccess: (groupDetail) => this.#applyGroupDetail(groupId, groupDetail),+ // Not found is settled by the slice `effects`; this view adopts the roster.+ onSuccess: (groupDetail) => {+ if (groupDetail) this.#applyGroupDetail(groupId, groupDetail);+ },});/*** Fetch orchestration only; the authoritative list reconciles `groupMap`- * through its `onSuccess`.+ * through the slice `effects`.*/useFetchGroups = (enabled: boolean, isLogin: boolean): ReplicaSyncResult =>- this.#groupList.useSync(LIST_PARAMS, {- enabled: enabled && isLogin,- onSuccess: (groups) => this.#reconcileGroupMap(groups),- });+ this.#groupList.useSync(LIST_PARAMS, { enabled: enabled && isLogin });}type PublicActions<T> = { [K in keyof T]: T[K] };diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.tsindex 3dc22ecba02..76d85117493 100644--- a/src/store/document/slices/document/action.ts+++ b/src/store/document/slices/document/action.ts@@ -464,27 +464,12 @@ export class DocumentActionImpl {* so navigation paints the editor from the projection instead of a skeleton.*/prefetchDocument = async (documentId: string): Promise<void> => {- // Capture the identity BEFORE the request. An account / workspace switch- // while it is in flight would otherwise make `replace` fall back to the new- // scope and write the old identity's document into its memory and IndexedDB- // partition. The regular `useSync` path captures the scope the same way; the- // engine drops an action whose scope is no longer active.- const scope = documentDetailResource.scope.get();+ // Goes through the replica's own fetcher (which keeps a newer adopted row)+ // and settle pipeline: a response captured under another identity is+ // dropped, and one older than a response a sync already applied β e.g. a+ // not-found the page settled while this was in flight β cannot regress it.try {- const before = this.#get().documentDetailMap[documentId];- const document = await documentService.getDocumentById(documentId);- // A sync or save that wrote the entry while this was in flight owns it- // now: it may hold a newer revision, or a confirmed absence. Never let a- // late prefetch regress it β e.g. resurrect the body of a document the- // sync has just settled as not-found.- if (this.#get().documentDetailMap[documentId] !== before) return;- // Otherwise the response refreshes the entry (a retained one may be stale- // from an earlier visit), unless it is strictly older than it.- this.#detail.replace(- documentId,- this.#keepNewerDetail(documentId, { document: document ?? null }),- scope,- );+ await this.#detail.fetch(documentId);} catch (error) {console.error('[DocumentStore] Failed to prefetch document:', error);}diff --git a/src/store/tool/slices/agentSkills/action.ts b/src/store/tool/slices/agentSkills/action.tsindex 2b4c95c2240..460806dc7b2 100644--- a/src/store/tool/slices/agentSkills/action.ts+++ b/src/store/tool/slices/agentSkills/action.ts@@ -100,19 +100,18 @@ export class AgentSkillsActionImpl {#isCurrentScope = (scope: string): boolean => this.#list.resource.scope.get() === scope;/**- * Fetch the list and write it straight into the replica. `refreshAgentSkills`- * is also called from flows where the list hook is not mounted (installing a+ * Fetch the list and settle it into the replica. `refreshAgentSkills` is+ * also called from flows where the list hook is not mounted (installing a* suggested skill from the create-agent modal), and it must populate the* store regardless, so this does not just revalidate the SWR entry.*- * The scope is captured before the request and passed to `replace`, so a- * response that resolves after an identity switch is dropped instead of being- * written (and persisted) into the next scope's partition.+ * It runs after mutations, so it never joins a request already in flight+ * (`fresh`): that one may hold the pre-mutation list. The replica drops a+ * response that resolves after an identity switch instead of writing (and+ * persisting) it into the next scope's partition.*/#refreshList = async (): Promise<void> => {- const scope = this.#captureScope();- const response = await agentSkillService.list();- this.#list.replace(LIST_PARAMS, response, scope);+ await this.#list.fetch(LIST_PARAMS, { fresh: true });};createAgentSkill = async (diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex 7d0fd6d7625..2175ca3a6b3 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -173,12 +173,14 @@ export class ConnectorActionImpl {* as it is read while the network confirms it in parallel, instead of* blanking to an empty array first.*- * The identity scope is captured when the request is issued and handed to- * `hydrate` / `replace` explicitly, because the replica reads the *active*- * scope at call time β i.e. after the response has already landed. A response- * that resolves after the scope moved on is then dropped by the replica- * itself (`dispatch` discards actions whose scope is no longer active),- * instead of being written into the next identity's partition.+ * The identity scope is captured when the request is issued: `fetch`+ * captures it itself and `hydrate` gets it explicitly, because the replica+ * reads the *active* scope at call time β i.e. after the response has already+ * landed. A response that resolves after the scope moved on is then dropped+ * by the replica's settle pipeline instead of being written into the next+ * identity's partition. The refresh never joins a request already in flight+ * (`fresh`): it runs after mutations, and that one may hold the pre-mutation+ * list.** The whole cache scope (user + workspace) is captured, not just the* workspace: two different signed-in users in personal context both have a@@ -206,10 +208,9 @@ export class ConnectorActionImpl {*/fetchConnectors = async (): Promise<void> => {const scope = cacheScope.get();- const pending = this.#connectors.fetcher!(LIST_PARAMS);+ const pending = this.#connectors.fetch(LIST_PARAMS, { fresh: true });if (!this.#get().isConnectorsInit) await this.#connectors.hydrate(LIST_PARAMS, scope);- const data = await pending;- this.#connectors.replace(LIST_PARAMS, data, scope);+ await pending;};/**@@ -234,10 +235,9 @@ export class ConnectorActionImpl {*/fetchAgentBoundConnectors = async (): Promise<void> => {const scope = cacheScope.get();- const pending = this.#agentBoundConnectors.fetcher!(LIST_PARAMS);+ const pending = this.#agentBoundConnectors.fetch(LIST_PARAMS, { fresh: true });if (!this.#get().isAgentBoundInit) await this.#agentBoundConnectors.hydrate(LIST_PARAMS, scope);- const data = await pending;- this.#agentBoundConnectors.replace(LIST_PARAMS, data, scope);+ await pending;};/**@@ -248,11 +248,10 @@ export class ConnectorActionImpl {fetchAgentConnectors = async (agentId: string): Promise<void> => {const scope = cacheScope.get();const params = { agentId };- const pending = this.#agentConnectors.fetcher!(params);+ const pending = this.#agentConnectors.fetch(params, { fresh: true });if (!this.#get().agentConnectorsInit[agentId])await this.#agentConnectors.hydrate(params, scope);- const data = await pending;- this.#agentConnectors.replace(params, data, scope);+ await pending;};/** Copy a user connector into an agent-owned, independently editable row. */diff --git a/src/store/tool/slices/plugin/action.ts b/src/store/tool/slices/plugin/action.tsindex fd4249a68a9..b2a3fbafc0e 100644--- a/src/store/tool/slices/plugin/action.ts+++ b/src/store/tool/slices/plugin/action.ts@@ -3,12 +3,7 @@ import { type LobeTool } from '@lobechat/types';import { type SWRResponse } from 'swr';import { MESSAGE_CANCEL_FLAT } from '@/const/message';-import {- cacheScope,- createReplicaSlice,- type ReplicaLens,- type ReplicaSyncResult,-} from '@/libs/replica';+import { createReplicaSlice, type ReplicaLens, type ReplicaSyncResult } from '@/libs/replica';import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';import { useClientDataSWR } from '@/libs/swr';import { pluginService } from '@/services/plugin';@@ -23,7 +18,6 @@ import {INSTALLED_PLUGINS_PARAMS,installedPluginsEntity,installedPluginsResource,- type InstalledPluginsResponse,toInstalledPluginsProjection,} from './projection';import { pluginSelectors } from './selectors';@@ -53,10 +47,6 @@ export const createPluginSlice = (set: Setter, get: () => ToolStore, _api?: unknexport class PluginActionImpl {readonly #get: () => ToolStore;- /** Responses of requests started at or before this sequence are dropped. */- #droppedThroughSeq = 0;- /** Start sequence of the last fetch, shared by `useSync` and `refreshPlugins`. */- #fetchSeq = 0;readonly #installedPlugins;readonly #set: Setter;@@ -67,10 +57,8 @@ export class PluginActionImpl {this.#installedPlugins = createReplicaSlice(installedPluginsResource, {actionPrefix: n('installedPlugins'),entity: installedPluginsEntity,- fetcher: () => this.#fetchInstalledPlugins(),+ fetcher: () => pluginService.getInstalledPlugins(),get,- merge: (incoming) => incoming.plugins,- prepareHead: (incoming) => this.#admitResponse(incoming),set,stateKey: 'installedPluginsReplica',// Settings and connection parameters never reach IndexedDB.@@ -107,25 +95,6 @@ export class PluginActionImpl {throw new Error('The installed plugins have not been loaded from the server');};- /** Every fetch path goes through here, so all responses share one order. */- #fetchInstalledPlugins = async (): Promise<InstalledPluginsResponse> => {- const seq = ++this.#fetchSeq;- const plugins = await pluginService.getInstalledPlugins();- return { plugins, seq };- };-- /**- * Admit a response only when its request started after every response- * already applied and after the latest mutation refresh. A mounted sync that- * started before an uninstall must not re-add the plugin (and persist it)- * when it settles late; an older refresh must not overwrite a newer one.- */- #admitResponse = (incoming: InstalledPluginsResponse): InstalledPluginsResponse | undefined => {- if (incoming.seq <= this.#droppedThroughSeq) return undefined;- this.#droppedThroughSeq = incoming.seq;- return incoming;- };-checkPluginsIsInstalled = async (_plugins: string[]): Promise<void> => {// Old plugin system has been deprecated, skip auto-installation};@@ -139,17 +108,13 @@ export class PluginActionImpl {* is mounted, so revalidating the mounted sync queries would resolve without* fetching anything. The scope is captured before the request so a response* that lands after a workspace switch is dropped instead of written into the- * next scope. Every mutation ends with this refresh, so it also retires the- * requests already in flight (sync or refresh): they started before the- * mutation and would paint the pre-mutation list. Rejects when the fetch- * fails.+ * next scope. Every mutation ends with this refresh, so it is `fresh`: it+ * retires the requests already in flight (sync or refresh), which started+ * before the mutation and would paint the pre-mutation list. Rejects when+ * the fetch fails.*/refreshPlugins = async (): Promise<void> => {- const scope = cacheScope.get();- this.#droppedThroughSeq = this.#fetchSeq;- const response = await this.#fetchInstalledPlugins();-- this.#installedPlugins.replace(INSTALLED_PLUGINS_PARAMS, response, scope);+ await this.#installedPlugins.fetch(INSTALLED_PLUGINS_PARAMS, { fresh: true });};/**diff --git a/src/store/tool/slices/plugin/projection.ts b/src/store/tool/slices/plugin/projection.tsindex 0974cb5853b..72f97b53875 100644--- a/src/store/tool/slices/plugin/projection.ts+++ b/src/store/tool/slices/plugin/projection.ts@@ -13,18 +13,6 @@ export type InstalledPluginsParams = Record<string, never>;export const INSTALLED_PLUGINS_PARAMS: InstalledPluginsParams = {};-/**- * One installed-plugins response, tagged with the order its request started- * in. The sync hook and the imperative refresh fetch independently, so a- * response may settle after a newer one (or after a mutation): the tag lets- * the slice drop it instead of painting β and persisting β an older list.- */-export interface InstalledPluginsResponse {- plugins: LobeTool[];- /** Start order of the request, shared by every fetch path. */- seq: number;-}-/*** Installed plugins (`user_installed_plugins`): read by the skill settings page,* the chat input tool picker, the agent profile and the MCP detail pages, and@@ -32,11 +20,7 @@ export interface InstalledPluginsResponse {* paints the persisted display projection on the first frame and lets the* network confirm the full records in the background.*/-export const installedPluginsResource = defineReplica<- InstalledPluginsParams,- LobeTool[],- InstalledPluginsResponse->({+export const installedPluginsResource = defineReplica<InstalledPluginsParams, LobeTool[]>({key: () => INSTALLED_PLUGINS_KEY,name: 'installedPlugins',storage: 'indexedDB',diff --git a/src/store/topicComment/action.ts b/src/store/topicComment/action.tsindex 914e189c3b8..8ec4f051aa2 100644--- a/src/store/topicComment/action.ts+++ b/src/store/topicComment/action.ts@@ -100,13 +100,6 @@ export class TopicCommentActionImpl {rootCommentId: params.rootCommentId,});- #prefetchReplies = async (rootCommentId: string, scope: string) => {- const params = { pageSize: TOPIC_COMMENT_PAGE_SIZE, rootCommentId };- const page = await this.#fetchReplies(params);- // `scope` was captured before the request (see `prefetchTopicComments`).- this.#replies.replace(params, page, scope);- };-#fetchThreads = (params: TopicCommentThreadsParams, cursor?: string) =>topicCommentService.listThreads({cursor,@@ -196,22 +189,26 @@ export class TopicCommentActionImpl {this.#prefetching.add(topicId);try {const params = { pageSize: TOPIC_COMMENT_PAGE_SIZE, topicId };- // Capture the partition before the request. A warmup that lands after a- // workspace / account switch must not paint, or persist, the previous- // identity's rows into the new one: resolving the scope at write time- // would target whatever partition is active when the response arrives.+ // The whole warmup belongs to the partition it started under. Every+ // fetch settles into it, so one that lands after a workspace / account+ // switch is dropped instead of painting (or persisting) the previous+ // identity's rows into the new one; and once the scope moved on, the+ // remaining roots β that identity's ids β are not fetched at all.const scope = topicCommentThreadResource.scope.get();- const threads = await this.#fetchThreads(params);- this.#thread.replace(params, threads, scope);+ const { applied, data: threads } = await this.#thread.fetch(params, { scope });+ if (!applied) return;const rootCommentIds = threads.items.flatMap(({ replyCount, root }) =>replyCount > 0 ? [root.id] : [],);for (let index = 0; index < rootCommentIds.length; index += PREFETCH_CONCURRENCY) {+ if (topicCommentThreadResource.scope.get() !== scope) return;await Promise.all(rootCommentIds.slice(index, index + PREFETCH_CONCURRENCY)- .map((rootCommentId) => this.#prefetchReplies(rootCommentId, scope)),+ .map((rootCommentId) =>+ this.#replies.fetch({ pageSize: TOPIC_COMMENT_PAGE_SIZE, rootCommentId }, { scope }),+ ),);}} catch {diff --git a/src/store/topicComment/replica.test.ts b/src/store/topicComment/replica.test.tsindex 636f6a74ef6..ada60d397da 100644--- a/src/store/topicComment/replica.test.ts+++ b/src/store/topicComment/replica.test.ts@@ -366,6 +366,46 @@ describe('topicComment replicas', () => {});});+ it('stops warming replies of the previous identity once the cache scope changed', async () => {+ // Five roots warm in two batches (four, then one). The identity changes+ // while the first batch is in flight: the second batch's root belongs to+ // the previous identity and must not be fetched β let alone written β+ // under the new one.+ const roots = ['root-1', 'root-2', 'root-3', 'root-4', 'root-5'];+ const resolvers: ((page: unknown) => void)[] = [];+ listThreadsSpy.mockResolvedValue({+ items: roots.map((id) => thread(id, 1)),+ nextCursor: null,+ });+ listRepliesSpy.mockImplementation(+ () => new Promise((resolve) => resolvers.push(resolve)) as any,+ );++ const prefetch = useTopicCommentStore.getState().prefetchTopicComments('topic-1');+ await waitFor(() => expect(resolvers).toHaveLength(4));++ const nextScope = `topic-user-${randomUUID()}:personal`;+ useScope(nextScope);++ await act(async () => {+ for (const [index, resolve] of resolvers.entries())+ resolve({+ items: [comment(`reply-${index}`, { parentCommentId: roots[index] })],+ nextCursor: null,+ total: 1,+ });+ await prefetch;+ });++ expect(listRepliesSpy).toHaveBeenCalledTimes(4);+ expect(useTopicCommentStore.getState().replyFeedMap).toEqual({});+ const row = await topicCommentReplyResource.storage!.get({+ queryKey: 'root-5',+ scope: nextScope,+ });+ expect(row).toBeUndefined();+ });+it('keeps one comment by id in the detail view and drops it from view and storage', async () => {act(() => useTopicCommentStore.getState().upsertTopicCommentDetail(comment('comment-1')));