Skip to content

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

♻️ refactor(userMemory): move the remaining memory slices onto @lobechat/replica, with replica-core persistence follow-ups (#20774)

Arvin Xud1b099c5bcd0
diff --git a/packages/replica/README.md b/packages/replica/README.md
index c0cf1e0ac9f..ce517e5cf4c 100644
--- a/packages/replica/README.md
+++ b/packages/replica/README.md
@@ -49,24 +49,45 @@ slice.optimistic(key, apply, serverCall);
A persisted read is asynchronous, so a list hydrated only by `useSync` paints its loading state for a few frames on a cold start. When that list must paint without a skeleton, seed it from the route loader before the route commits: `slice.ensureScope(scope)` + `slice.hydrate(params, scope)`, bounded by `settleWithin(…, PRE_PAINT_HYDRATE_TIMEOUT)` from `@/libs/replica/prePaint`. A later `useSync` hydrate is a no-op once the slot is filled.
+A persisted row is only rewritten when its value changes: a persist whose value is deep-equal to what the engine last wrote to (or hydrated from) that row is skipped, so an unchanged revalidation costs no storage write. A failed write, a delete, an entity patch, an eviction or a `clear()` forgets what the row holds, so the next persist writes it again. The engine only tracks its own writes: a row changed behind it (another tab) is corrected by the next changed value or the next session.
+
Inside LobeHub, use `@/libs/replica`. It presets the cache scope, IndexedDB / localStorage storage and the app's SWR driver.
## Invalidation
Persisted 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:
-| What is gone | Call | What it does |
-| ------------------------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| One entity (a deleted topic, file, memory) | `linkReplicaEntity(...).remove(id)` / `slice.removeEntity(id)` | Drops it from every loaded entry and from persisted rows of unloaded entries. A value hydrated later β€” even by a read already in flight β€” comes back without it until a server value holds it again. |
-| One entry key, under every filter / sort | `slice.remove(key)` | Drops the entry and every persisted query variant of the key. No variant hydrates again until a server `replace` for the key supersedes the removal. |
-| The whole resource ("delete all", a reset) | `slice.clear()` / `linkReplicaEntity(...).clear()` | Empties memory in one commit, deletes every persisted row and the index of the active scope, and drops hydrates and `useSync` responses that started before it. Resolves `true` once storage is purged. |
+| What is gone | Call | What it does |
+| ------------------------------------------ | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| One entity (a deleted topic, file, memory) | `linkReplicaEntity(...).remove(id)` / `slice.removeEntity(id)` | Drops it from every loaded entry and from persisted rows of unloaded entries. A value hydrated later β€” even by a read already in flight β€” comes back without it until a server value holds it again; if the persisted patch does not land (untrusted scope, unreadable storage), the guard stays for the session. |
+| One entry key, under every filter / sort | `slice.remove(key)` | Drops the entry and every persisted query variant of the key. No variant hydrates again until a server `replace` for the key supersedes the removal. |
+| The whole resource ("delete all", a reset) | `slice.clear()` / `linkReplicaEntity(...).clear()` | Empties memory in one commit, deletes every persisted row and the index of the active scope, and drops hydrates and `useSync` responses that started before it. Resolves `true` once storage is purged. |
`slice.updateEntity(id, (item) => undefined)` also drops the entity from loaded values and persisted rows, but it is a plain patch: only `removeEntity` (which `linkReplicaEntity.remove` and an optimistic `'remove'` call) guards hydrates already in flight.
-A `ReplicaStorage` must reject from `remove` when a delete did not land, and should implement `getStrict` (a read that rejects on I/O failure) so an unreadable index fails a purge instead of passing for an empty one. `get` and `set` stay best-effort. The engine then keeps the row indexed and the removal unpurged, so the next `remove(key)` / `clear()` retries it.
+A `ReplicaStorage` must reject from `remove` when a delete did not land, and must implement `getStrict` (a read that rejects on I/O failure) for any destructive pass to succeed: `remove(key)` variant scans, `clear()`, off-scope purges, entity patches of unloaded rows and evictions all read through it, so an unreadable index fails the pass instead of passing for an empty one. A storage without `getStrict` still hydrates and persists, but every destructive pass fails: `clear()` resolves `false`, a removal stays unpurged and is retried, an entity guard is kept. `get` and `set` stay best-effort. The engine then keeps the row indexed and the removal unpurged, so the next `remove(key)` / `clear()` retries it.
Prefer the narrowest call: an entity delete keeps the rest of every list; `remove(key)` is for a key whose whole value is gone or denied (NOT_FOUND / FORBIDDEN); `clear()` is for flows that invalidate everything the user has of that resource. `clear()` does not refetch: mounted views show their loading state until the next sync, so call `slice.revalidate()` after it when the server still has data to show.
+## Bounding persisted query variants
+
+Every distinct key + query a resource persists is its own row, so a resource keyed (or queried) by free text β€” a search, a market filter, a per-topic bundle β€” would grow storage with every query the user ever ran. Opt in to a cap instead of hand-rolling a recency window around `remove`:
+
+```ts
+const searchList = defineReplica<Params, Result>({
+ key: ({ keyword }) => keyword,
+ name: 'search',
+ persist: { maxEntries: 20 }, // at most 20 persisted rows per scope
+ // …
+});
+```
+
+- **What counts.** Persisted storage keys per scope: each `key?query` row counts once.
+- **Recency.** A hydrate, a persist, or an unchanged revalidation whose write is skipped marks the row as used. The order is kept in the per-scope index (oldest first), so it survives reloads. Rows an unbounded release indexed keep their append order.
+- **Eviction.** Past the cap, the oldest rows go: the row, its index entry, and the memory entry that answers it. An evicted entry is a cache miss. A revisit fetches it again; it is not a removal and does not block hydrates the way `remove` does.
+- **Never evicted.** A row with a mounted `useSync` (pinned for as long as it is mounted), an entry with pending optimistic writes, and an entry with a `loadMore` in flight. A view that renders an entry without `useSync` pins it with `slice.retain(key, storageKey)`, which returns the release.
+- **Failure.** A failed delete stays indexed and is picked again on the next use. An unreadable index (see `getStrict`) evicts nothing.
+
## Transcripts and other irregular pages
Message-like resources page backward by cursor, with windows whose length changes on every refresh. The paging config covers them:
diff --git a/packages/replica/src/core/defineReplica.ts b/packages/replica/src/core/defineReplica.ts
index e3b8111f037..ab88d1f935e 100644
--- a/packages/replica/src/core/defineReplica.ts
+++ b/packages/replica/src/core/defineReplica.ts
@@ -62,6 +62,17 @@ export interface DefineReplicaOptions<TParams, TData, TFetched = TData, TCursor
key: (params: TParams) => string;
name: string;
paging?: ReplicaPagingConfig<any, TCursor>;
+ /**
+ * Bound what the resource keeps in storage. `maxEntries` caps the persisted
+ * rows (storage keys: one per entry key and query) per scope; past it the
+ * least recently used rows are evicted β€” their persisted row, index entry
+ * and, when nothing holds it, their memory entry. Use rows (a hydrate or a
+ * persist, including a skipped unchanged one) count as recent, and the order
+ * lives in the persisted index, so it survives reloads. A row on screen (a
+ * mounted `useSync`, see `retain`), with pending optimistic writes or a
+ * `loadMore` in flight is never evicted. Unbounded by default.
+ */
+ persist?: { maxEntries?: number };
/**
* Entries that never touch storage (no hydrate, no persist) β€” e.g. scoped
* buckets whose rows must not land under an ordinary entry. Defaults to all.
@@ -99,6 +110,7 @@ export const defineReplica = <TParams, TData, TFetched = TData, TCursor = any>(
return {
fetcher: options.fetcher,
key: options.key,
+ maxPersistedEntries: options.persist?.maxEntries,
name: options.name,
namespace,
paging: options.paging,
diff --git a/packages/replica/src/core/engine.persistence.test.ts b/packages/replica/src/core/engine.persistence.test.ts
new file mode 100644
index 00000000000..450ac87f3a7
--- /dev/null
+++ b/packages/replica/src/core/engine.persistence.test.ts
@@ -0,0 +1,461 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import { createStore } from 'zustand/vanilla';
+
+import { testDriver } from '../../tests/testDriver';
+import { createReplicaSlice, recordLens } from '../zustand/createReplicaSlice';
+import { defineReplica } from './defineReplica';
+import { createReplicaEngine, REPLICA_INDEX_KEY, type ReplicaStorePort } from './engine';
+import { arrayEntity } from './entityAdapters';
+import { createReplicaState } from './reducer';
+import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from './types';
+
+interface Item {
+ id: string;
+}
+
+const SCOPE = 'u1';
+const scopeState = { current: SCOPE, trusted: true };
+const scope: ReplicaScope = {
+ canPersist: () => scopeState.trusted,
+ get: () => scopeState.current,
+ use: () => scopeState.current,
+};
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+const item = (id: string): Item => ({ id });
+
+/**
+ * In-memory storage keyed like the app adapters. `strict: false` builds a
+ * legacy adapter without `getStrict`; `failReads` makes reads of the listed row
+ * keys fail the way the app adapters do (`get` swallows into a miss,
+ * `getStrict` rejects).
+ */
+const createStorage = ({ strict = true }: { strict?: boolean } = {}) => {
+ const rows = new Map<string, ReplicaRow<any>>();
+ const failReads = new Set<string>();
+ const failRemoves = new Set<string>();
+ const failSets = new Set<string>();
+ const writes: string[] = [];
+ const id = ({ queryKey, scope }: { queryKey: string; scope: string }) => `${scope}|${queryKey}`;
+ const storage: ReplicaStorage<any> = {
+ get: async (key) => (failReads.has(key.queryKey) ? undefined : rows.get(id(key))),
+ remove: async (key) => {
+ if (failRemoves.has(key.queryKey)) throw new Error('delete failed');
+ rows.delete(id(key));
+ },
+ set: async (key, row) => {
+ if (failSets.has(key.queryKey)) throw new Error('write failed');
+ writes.push(key.queryKey);
+ rows.set(id(key), row);
+ },
+ };
+ if (strict)
+ storage.getStrict = async (key) => {
+ if (failReads.has(key.queryKey)) throw new Error('read failed');
+ return rows.get(id(key));
+ };
+ const index = () => (rows.get(`${SCOPE}|${REPLICA_INDEX_KEY}`)?.data as string[]) ?? [];
+ const dataKeys = () =>
+ [...rows.keys()]
+ .filter((key) => !key.endsWith(REPLICA_INDEX_KEY))
+ .map((key) => key.slice(SCOPE.length + 1))
+ .sort();
+ return { dataKeys, failReads, failRemoves, failSets, index, rows, storage, writes };
+};
+
+/** Minimal host: a record of views plus the bookkeeping slot. */
+const createHost = <T>() => {
+ let state: ReplicaState<T> = createReplicaState<T>();
+ let view: Record<string, T> = {};
+ const port: ReplicaStorePort<T> = {
+ commit: (writes, next) => {
+ for (const write of writes) {
+ if ('type' in write) view = {};
+ else if (write.data === undefined) {
+ const { [write.key]: _dropped, ...rest } = view;
+ view = rest;
+ } else view = { ...view, [write.key]: write.data };
+ }
+ state = next;
+ },
+ getState: () => state,
+ keys: () => Object.keys(view),
+ read: (key) => view[key],
+ };
+ return { port, state: () => state, view: () => view };
+};
+
+type ListParams = { id: string; q?: string };
+
+const setupList = (
+ storage: ReturnType<typeof createStorage>,
+ { maxEntries }: { maxEntries?: number } = {},
+) => {
+ const resource = defineReplica<ListParams, Item[]>({
+ key: ({ id }) => id,
+ name: 'list',
+ persist: { maxEntries },
+ query: ({ q }) => ({ q }),
+ scope,
+ storage: storage.storage,
+ version: 1,
+ });
+ const host = createHost<Item[]>();
+ const engine = createReplicaEngine(resource, {
+ entity: arrayEntity<Item>((entry) => entry.id),
+ port: host.port,
+ });
+ return { engine, host, resource };
+};
+
+const resetScope = () => {
+ scopeState.current = SCOPE;
+ scopeState.trusted = true;
+};
+
+describe('destructive passes need a strict read', () => {
+ it('fails a clear on a legacy storage without getStrict instead of reporting success', async () => {
+ resetScope();
+ const storage = createStorage({ strict: false });
+ const first = setupList(storage);
+ first.engine.replace({ id: 'a' }, [item('1')]);
+ first.engine.replace({ id: 'b' }, [item('2')]);
+ await flush();
+ // The index row cannot be read on this device: `get` swallows it into a miss.
+ storage.failReads.add(REPLICA_INDEX_KEY);
+
+ // A fresh session only knows the rows through the index.
+ const { engine } = setupList(storage);
+ expect(await engine.clear()).toBe(false);
+ expect(storage.dataKeys()).toEqual(['a?{}', 'b?{}']);
+ // Hydration stays off while the wipe is incomplete.
+ expect(await engine.hydrate({ id: 'a' })).toBe(false);
+ });
+
+ it('keeps a removal of a legacy storage unpurged, so every later removal retries it', async () => {
+ resetScope();
+ const storage = createStorage({ strict: false });
+ const first = setupList(storage);
+ first.engine.replace({ id: 'a', q: 'x' }, [item('1')]);
+ await flush();
+
+ const { engine } = setupList(storage);
+ expect(engine.remove('a')).toBe(true);
+ await flush();
+ // The variant is only known through the index, which cannot be read strictly.
+ expect(storage.dataKeys()).toEqual(['a?{"q":"x"}']);
+ // Not marked purged: the next removal is dispatched again rather than a no-op.
+ expect(engine.remove('a')).toBe(true);
+ });
+
+ it('never rewrites an unreadable index as just the new key, and retries the append', async () => {
+ resetScope();
+ const storage = createStorage();
+ const first = setupList(storage);
+ first.engine.replace({ id: 'a' }, [item('1')]);
+ first.engine.replace({ id: 'b' }, [item('2')]);
+ await flush();
+ expect(storage.index()).toEqual(['a?{}', 'b?{}']);
+
+ const { engine } = setupList(storage);
+ storage.failReads.add(REPLICA_INDEX_KEY);
+ engine.replace({ id: 'c' }, [item('3')]);
+ await flush();
+ // The earlier session's keys survive the failed read.
+ expect(storage.index()).toEqual(['a?{}', 'b?{}']);
+
+ storage.failReads.delete(REPLICA_INDEX_KEY);
+ engine.replace({ id: 'c' }, [item('3'), item('4')]);
+ await flush();
+ expect(storage.index()).toEqual(['a?{}', 'b?{}', 'c?{}']);
+ });
+});
+
+describe('removeEntity keeps its guard until the persisted patch lands', () => {
+ /** A session that persisted `b` (holding entity `1`), then a fresh engine. */
+ const persistedB = async () => {
+ const storage = createStorage();
+ const first = setupList(storage);
+ first.engine.replace({ id: 'b' }, [item('1'), item('2')]);
+ await flush();
+ return { storage, ...setupList(storage) };
+ };
+
+ it('a failed index read keeps the guard, so a later hydrate strips the entity', async () => {
+ resetScope();
+ const { engine, host, storage } = await persistedB();
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+ storage.failReads.add(REPLICA_INDEX_KEY);
+
+ engine.removeEntity('1');
+ await flush();
+ // The unloaded row still holds the deleted entity…
+ expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([item('1'), item('2')]);
+
+ // …but a hydrate that starts long after the failed patch never paints it.
+ expect(await engine.hydrate({ id: 'b' })).toBe(true);
+ expect(host.view().b).toEqual([item('2')]);
+ errors.mockRestore();
+ });
+
+ it('an untrusted scope keeps the guard, and a later successful removal releases it', async () => {
+ resetScope();
+ const { engine, host, storage } = await persistedB();
+ scopeState.trusted = false;
+
+ engine.removeEntity('1');
+ await flush();
+ expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([item('1'), item('2')]);
+ expect(await engine.hydrate({ id: 'b' })).toBe(true);
+ expect(host.view().b).toEqual([item('2')]);
+
+ // Once trusted, a repeated removal of an unloaded row lands its patch.
+ scopeState.trusted = true;
+ const fresh = setupList(storage);
+ fresh.engine.removeEntity('1');
+ await flush();
+ expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([item('2')]);
+ });
+});
+
+describe('redundant persist writes', () => {
+ const rowWrites = (storage: ReturnType<typeof createStorage>, queryKey: string) =>
+ storage.writes.filter((key) => key === queryKey).length;
+
+ it('skips a revalidation whose value equals what this session persisted', async () => {
+ resetScope();
+ const storage = createStorage();
+ const { engine } = setupList(storage);
+ engine.replace({ id: 'a' }, [item('1')]);
+ await flush();
+ // A fresh but deep-equal response.
+ engine.replace({ id: 'a' }, [item('1')]);
+ await flush();
+ expect(rowWrites(storage, 'a?{}')).toBe(1);
+
+ engine.replace({ id: 'a' }, [item('1'), item('2')]);
+ await flush();
+ expect(rowWrites(storage, 'a?{}')).toBe(2);
+ });
+
+ it('skips a revalidation equal to the row it hydrated, and writes one that differs', async () => {
+ resetScope();
+ const storage = createStorage();
+ storage.rows.set(`${SCOPE}|a?{}`, { data: [item('1')], updatedAt: 1 });
+ storage.rows.set(`${SCOPE}|b?{}`, { data: [item('old')], updatedAt: 1 });
+ const { engine } = setupList(storage);
+ await engine.hydrate({ id: 'a' });
+ await engine.hydrate({ id: 'b' });
+
+ engine.replace({ id: 'a' }, [item('1')]);
+ engine.replace({ id: 'b' }, [item('new')]);
+ await flush();
+ expect(rowWrites(storage, 'a?{}')).toBe(0);
+ expect(rowWrites(storage, 'b?{}')).toBe(1);
+ });
+
+ it('writes again after a failed write, a removal or a clear', async () => {
+ resetScope();
+ const storage = createStorage();
+ const { engine } = setupList(storage);
+ storage.failSets.add('a?{}');
+ engine.replace({ id: 'a' }, [item('1')]);
+ await flush();
+ storage.failSets.delete('a?{}');
+ engine.replace({ id: 'a' }, [item('1')]);
+ await flush();
+ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1')]);
+
+ engine.remove('a');
+ await flush();
+ expect(storage.rows.has(`${SCOPE}|a?{}`)).toBe(false);
+ engine.replace({ id: 'a' }, [item('1')]);
+ await flush();
+ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1')]);
+
+ expect(await engine.clear()).toBe(true);
+ engine.replace({ id: 'a' }, [item('1')]);
+ await flush();
+ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1')]);
+ });
+
+ it('writes again after an entity patch rewrote the row behind it', async () => {
+ resetScope();
+ const storage = createStorage();
+ const { engine } = setupList(storage);
+ engine.replace({ id: 'a' }, [item('1'), item('2')]);
+ // The entry moves on to another query: the first row is no longer loaded.
+ engine.replace({ id: 'a', q: 'x' }, [item('2')]);
+ await flush();
+
+ engine.updateEntity<Item>('1', () => ({ id: '1', renamed: true }) as Item);
+ await flush();
+ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([
+ { id: '1', renamed: true },
+ item('2'),
+ ]);
+
+ // Back to the first query with the original value: the row must be rewritten.
+ engine.replace({ id: 'a' }, [item('1'), item('2')]);
+ await flush();
+ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1'), item('2')]);
+ });
+});
+
+describe('bounded persisted entries (persist.maxEntries)', () => {
+ const bounded = (storage = createStorage()) => ({
+ storage,
+ ...setupList(storage, { maxEntries: 2 }),
+ });
+
+ it('evicts the least recently used row, its index entry and its idle memory entry', async () => {
+ resetScope();
+ const { engine, host, storage } = bounded();
+ engine.replace({ id: 'a' }, [item('1')]);
+ engine.replace({ id: 'b' }, [item('2')]);
+ await flush();
+ engine.replace({ id: 'c' }, [item('3')]);
+ await flush();
+
+ expect(storage.dataKeys()).toEqual(['b?{}', 'c?{}']);
+ expect(storage.index()).toEqual(['b?{}', 'c?{}']);
+ expect(Object.keys(host.view()).sort()).toEqual(['b', 'c']);
+ expect(host.state().entries.a).toBeUndefined();
+ });
+
+ it('counts an unchanged revalidation and a hydrate as a use', async () => {
+ resetScope();
+ const { engine, storage } = bounded();
+ engine.replace({ id: 'a' }, [item('1')]);
+ engine.replace({ id: 'b' }, [item('2')]);
+ await flush();
+ // `a` is revalidated with the same value: no row write, but it is now recent.
+ engine.replace({ id: 'a' }, [item('1')]);
+ await flush();
+ engine.replace({ id: 'c' }, [item('3')]);
+ await flush();
+ expect(storage.dataKeys()).toEqual(['a?{}', 'c?{}']);
+
+ // A later session hydrates `a`: `c` becomes the oldest.
+ const next = bounded(storage);
+ expect(await next.engine.hydrate({ id: 'a' })).toBe(true);
+ await flush();
+ next.engine.replace({ id: 'd' }, [item('4')]);
+ await flush();
+ expect(storage.dataKeys()).toEqual(['a?{}', 'd?{}']);
+ });
+
+ it('keeps recency across reloads through the persisted index', async () => {
+ resetScope();
+ const first = bounded();
+ first.engine.replace({ id: 'a' }, [item('1')]);
+ first.engine.replace({ id: 'b' }, [item('2')]);
+ await flush();
+ first.engine.replace({ id: 'a' }, [item('1'), item('x')]);
+ await flush();
+ expect(first.storage.index()).toEqual(['b?{}', 'a?{}']);
+
+ const { engine, storage } = bounded(first.storage);
+ engine.replace({ id: 'c' }, [item('3')]);
+ await flush();
+ expect(storage.dataKeys()).toEqual(['a?{}', 'c?{}']);
+ });
+
+ it('never evicts a retained row or an entry with pending writes', async () => {
+ resetScope();
+ const { engine, host, storage } = bounded();
+ engine.replace({ id: 'a' }, [item('1')]);
+ engine.replace({ id: 'b' }, [item('2')]);
+ await flush();
+ const release = engine.retain('a', 'a?{}');
+ const pending = engine.beginOptimistic('b', (data) => [...data, item('tmp')]);
+
+ engine.replace({ id: 'c' }, [item('3')]);
+ await flush();
+ // Both older rows are pinned: the cap waits rather than dropping them.
+ expect(storage.dataKeys()).toEqual(['a?{}', 'b?{}', 'c?{}']);
+ expect(host.view().a).toEqual([item('1')]);
+
+ pending.rollback();
+ release();
+ engine.replace({ id: 'd' }, [item('4')]);
+ await flush();
+ expect(storage.dataKeys()).toEqual(['c?{}', 'd?{}']);
+ expect(Object.keys(host.view()).sort()).toEqual(['c', 'd']);
+ });
+
+ it('keeps a row whose eviction delete failed indexed, and retries it on the next use', async () => {
+ resetScope();
+ const { engine, storage } = bounded();
+ storage.failRemoves.add('a?{}');
+ engine.replace({ id: 'a' }, [item('1')]);
+ engine.replace({ id: 'b' }, [item('2')]);
+ engine.replace({ id: 'c' }, [item('3')]);
+ await flush();
+ // `a` was picked but its delete failed: it stays indexed and stored.
+ expect(storage.index()).toEqual(['a?{}', 'b?{}', 'c?{}']);
+ expect(storage.dataKeys()).toEqual(['a?{}', 'b?{}', 'c?{}']);
+
+ storage.failRemoves.delete('a?{}');
+ engine.replace({ id: 'c' }, [item('3'), item('4')]);
+ await flush();
+ expect(storage.index()).toEqual(['b?{}', 'c?{}']);
+ expect(storage.dataKeys()).toEqual(['b?{}', 'c?{}']);
+ });
+
+ it('leaves an unbounded resource append-ordered and unevicted', async () => {
+ resetScope();
+ const storage = createStorage();
+ const { engine } = setupList(storage);
+ for (const id of ['a', 'b', 'c']) engine.replace({ id }, [item(id)]);
+ await flush();
+ engine.replace({ id: 'a' }, [item('a'), item('x')]);
+ await flush();
+ expect(storage.index()).toEqual(['a?{}', 'b?{}', 'c?{}']);
+ });
+});
+
+describe('useSync pins the entry it shows', () => {
+ it('a mounted useSync keeps its row and memory entry; unmounting releases them', async () => {
+ resetScope();
+ const storage = createStorage();
+ const resource = defineReplica<ListParams, Item[]>({
+ key: ({ id }) => id,
+ name: 'list',
+ persist: { maxEntries: 1 },
+ query: ({ q }) => ({ q }),
+ scope,
+ storage: storage.storage,
+ version: 1,
+ });
+ interface State {
+ lists: Record<string, Item[]>;
+ listsReplica: ReplicaState<Item[]>;
+ }
+ const store = createStore<State>()(() => ({ lists: {}, listsReplica: createReplicaState() }));
+ const slice = createReplicaSlice<State, ListParams, Item[]>(resource, {
+ driver: testDriver,
+ // No fetcher: only the pin is under test.
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+
+ const view = renderHook(() => slice.useSync({ id: 'a' }));
+ slice.replace({ id: 'a' }, [item('1')]);
+ slice.replace({ id: 'b' }, [item('2')]);
+ await flush();
+ await flush();
+ expect(storage.dataKeys()).toEqual(['a?{}', 'b?{}']);
+ expect(store.getState().lists.a).toEqual([item('1')]);
+
+ view.unmount();
+ slice.replace({ id: 'c' }, [item('3')]);
+ await flush();
+ await flush();
+ expect(storage.dataKeys()).toEqual(['c?{}']);
+ expect(Object.keys(store.getState().lists)).toEqual(['c']);
+ });
+});
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.ts
index de06f9ed3bf..95e3d801de2 100644
--- a/packages/replica/src/core/engine.ts
+++ b/packages/replica/src/core/engine.ts
@@ -18,7 +18,7 @@ import type { ReplicaAction, ReplicaEffect, ReplicaViewWrite } from './reducer';
import { replicaReducer } from './reducer';
import { createTombstones } from './tombstones';
import type { ReplicaResource, ReplicaState } from './types';
-import { ReplicaWriteQueue } from './writeQueue';
+import { readReplicaRowStrict, ReplicaWriteQueue } from './writeQueue';
/** Reserved storage key of the per-scope index of persisted rows. */
export const REPLICA_INDEX_KEY = '__replica:index';
@@ -182,8 +182,9 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
// count: it is released once its storage patch landed (`releasedAt`) and is
// dropped as soon as no hydrate that started before that point is pending.
// So memory stays bounded by in-flight reads, and no guard a pending read
- // still needs is ever evicted. A server value holding the entity again
- // (restored) lifts it early.
+ // still needs is ever evicted. A patch that did not land is never released:
+ // the unloaded row still holds the entity, so every later hydrate needs the
+ // guard. A server value holding the entity again (restored) lifts it early.
/** Logical clock shared by hydrate starts and guard releases. */
let guardClock = 0;
/** Start ticks of the hydrates in flight, per scope. */
@@ -249,20 +250,189 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
return seq;
};
+ // ---- last persisted value per row ---------------------------------------
+ // What this session knows a row holds in storage: the value it queued (until
+ // that write fails) or read back by a hydrate no write raced. A persist of a
+ // deep-equal value is skipped β€” an unchanged revalidation must not rewrite
+ // the same row. Every path that may change a row behind it (a delete, a
+ // patch, a clear, an eviction) forgets the row, so the next persist writes.
+ const storedValues = new Map<string, Map<string, unknown>>();
+ const rememberStored = (scope: string, queryKey: string, data: unknown) => {
+ const rows = storedValues.get(scope) ?? new Map<string, unknown>();
+ storedValues.set(scope, rows);
+ rows.set(queryKey, data);
+ };
+ const forgetStored = (scope: string, queryKeys: Iterable<string>) => {
+ const rows = storedValues.get(scope);
+ if (!rows) return;
+ for (const queryKey of queryKeys) rows.delete(queryKey);
+ if (rows.size === 0) storedValues.delete(scope);
+ };
+ const isStored = (scope: string, queryKey: string, data: unknown) => {
+ const rows = storedValues.get(scope);
+ return !!rows?.has(queryKey) && isEqual(rows.get(queryKey), data);
+ };
+
+ // ---- bounded persisted entries ----------------------------------------
+ // With `persist.maxEntries`, the index is kept in least-recently-used order
+ // (oldest first β€” the order an unbounded index is appended in, so rows an
+ // earlier release indexed keep their place) and every use of a row moves it
+ // to the end. Past the cap the oldest rows that nothing pins are evicted.
+ const maxEntries = resource.maxPersistedEntries;
+ /** Mounted readers per storage key and per entry key (see `retain`). */
+ const retainedRows = new Map<string, number>();
+ const retainedKeys = new Map<string, number>();
+ /** Rows whose eviction delete is queued, per scope. */
+ const evicting = new Map<string, Set<string>>();
+
+ const bump = (counts: Map<string, number>, id: string, by: number) => {
+ const next = (counts.get(id) ?? 0) + by;
+ if (next > 0) counts.set(id, next);
+ else counts.delete(id);
+ };
+
+ /**
+ * Pin an entry (and the row of the query it asks for) while something shows
+ * it: eviction never drops a retained row or the memory entry of a retained
+ * key. `useSync` retains for as long as it is mounted. Returns the release.
+ */
+ const retain = (key: string, queryKey: string = replicaStorageKey(key)) => {
+ bump(retainedKeys, key, 1);
+ bump(retainedRows, queryKey, 1);
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ bump(retainedKeys, key, -1);
+ bump(retainedRows, queryKey, -1);
+ };
+ };
+
+ /** Rows the memory of `scope` holds, by storage key β†’ entry key. */
+ const loadedRows = (scope: string) => {
+ const slot = getSlot();
+ const rows = new Map<string, string>();
+ if (slot.scope !== scope) return rows;
+ for (const [key, entry] of Object.entries(slot.entries))
+ rows.set(replicaStorageKey(key, entry.query), key);
+ return rows;
+ };
+
+ /** A row on screen, or whose entry has writes / a page load in flight. */
+ const isPinned = (queryKey: string, entryKey: string | undefined) =>
+ retainedRows.has(queryKey) ||
+ (entryKey !== undefined &&
+ (retainedKeys.has(entryKey) ||
+ (getSlot().entries[entryKey]?.pending.length ?? 0) > 0 ||
+ loadingMore.has(entryKey)));
+
+ /** The oldest unpinned rows past the cap (`keys` is oldest first). */
+ const pickEvictions = (scope: string, keys: string[], touched: string): string[] => {
+ const going = evicting.get(scope);
+ let excess = keys.length - maxEntries! - keys.filter((key) => going?.has(key)).length;
+ if (excess <= 0) return [];
+ const loaded = loadedRows(scope);
+ const picked: string[] = [];
+ for (const queryKey of keys) {
+ if (excess <= 0) break;
+ if (queryKey === touched || going?.has(queryKey)) continue;
+ if (isPinned(queryKey, loaded.get(queryKey))) continue;
+ picked.push(queryKey);
+ excess -= 1;
+ }
+ return picked;
+ };
+
+ /**
+ * Evict rows: drop the memory entries that answer them (one commit), then
+ * delete the rows. A row leaves the index only once its delete landed, so a
+ * failed eviction is picked again by a later use.
+ */
+ const evictRows = (scope: string, queryKeys: string[]) => {
+ if (resource.scope.get() !== scope || !resource.scope.canPersist()) return;
+ const going = evicting.get(scope) ?? new Set<string>();
+ evicting.set(scope, going);
+ const loaded = loadedRows(scope);
+ // Re-check: a row may have been pinned since it was picked.
+ const rows = queryKeys.filter(
+ (queryKey) => !going.has(queryKey) && !isPinned(queryKey, loaded.get(queryKey)),
+ );
+ if (rows.length === 0) return;
+ for (const queryKey of rows) going.add(queryKey);
+ const dropped = rows.flatMap((queryKey) => {
+ const key = loaded.get(queryKey);
+ return key === undefined ? [] : [key];
+ });
+ if (dropped.length > 0) {
+ const slot = getSlot();
+ const entries = { ...slot.entries };
+ for (const key of dropped) delete entries[key];
+ port.commit(
+ dropped.map((key) => ({ data: undefined, key })),
+ { entries, scope },
+ `${prefix}/evict`,
+ );
+ }
+ void deleteRows(scope, rows).finally(() => {
+ for (const queryKey of rows) going.delete(queryKey);
+ if (going.size === 0 && evicting.get(scope) === going) evicting.delete(scope);
+ });
+ };
+
+ /**
+ * A bounded resource used a row: move it to the end of the index and evict
+ * past the cap. No-op for an unbounded resource.
+ */
+ const touchStorageKey = (scope: string, queryKey: string) => {
+ if (!writeQueue || maxEntries === undefined) return;
+ const known = indexed.get(scope) ?? new Set<string>();
+ indexed.set(scope, known);
+ known.add(queryKey);
+ let picked: string[] = [];
+ void writeQueue
+ .update(
+ indexKey(scope),
+ (current) => {
+ const keys = (current?.data as unknown as string[] | undefined) ?? [];
+ const next = [...keys.filter((key) => key !== queryKey), queryKey];
+ picked = pickEvictions(scope, next, queryKey);
+ if (keys.length === next.length && keys.at(-1) === queryKey) return undefined;
+ return { data: next as unknown as TData, updatedAt: Date.now() };
+ },
+ { read: 'prefer-strict' },
+ )
+ .then((touched) => {
+ // Unreadable index: leave it untouched, retry the append on the next use.
+ if (!touched) return void known.delete(queryKey);
+ if (picked.length > 0) evictRows(scope, picked);
+ });
+ };
+
/** Record a persisted row in the index (queued after the row write). */
const trackStorageKey = (scope: string, queryKey: string) => {
if (!writeQueue) return;
noteWrite(scope, queryKey);
+ if (maxEntries !== undefined) return touchStorageKey(scope, queryKey);
const known = indexed.get(scope) ?? new Set<string>();
indexed.set(scope, known);
if (known.has(queryKey)) return;
known.add(queryKey);
- writeQueue.update(indexKey(scope), (current) => {
- const keys = new Set((current?.data as unknown as string[] | undefined) ?? []);
- if (keys.has(queryKey)) return undefined;
- keys.add(queryKey);
- return { data: [...keys] as unknown as TData, updatedAt: Date.now() };
- });
+ void writeQueue
+ .update(
+ indexKey(scope),
+ (current) => {
+ const keys = new Set((current?.data as unknown as string[] | undefined) ?? []);
+ if (keys.has(queryKey)) return undefined;
+ keys.add(queryKey);
+ return { data: [...keys] as unknown as TData, updatedAt: Date.now() };
+ },
+ { read: 'prefer-strict' },
+ )
+ // An unreadable index is left untouched (never rewritten as just this
+ // key); forget the key so the next write of the row retries the append.
+ .then((tracked) => {
+ if (!tracked) known.delete(queryKey);
+ });
};
/**
@@ -272,11 +442,9 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
* rows it could not enumerate.
*/
const readIndex = async (scope: string): Promise<string[]> => {
- const storage = resource.storage!;
- // Call through `storage`: a class-based storage needs its receiver.
- const row = await (storage.getStrict
- ? storage.getStrict(indexKey(scope))
- : storage.get(indexKey(scope)));
+ // A storage without `getStrict` rejects here: its `get` cannot tell an
+ // unreadable index from an empty one.
+ const row = await readReplicaRowStrict(resource.storage!, indexKey(scope));
return (row?.data as unknown as string[] | undefined) ?? [];
};
@@ -289,12 +457,16 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const known = indexed.get(scope);
for (const queryKey of queryKeys) known?.delete(queryKey);
const dropped = new Set(queryKeys);
- writeQueue.update(indexKey(scope), (current) => {
- const keys = (current?.data as unknown as string[] | undefined) ?? [];
- const next = keys.filter((queryKey) => !dropped.has(queryKey));
- if (!current || next.length === keys.length) return undefined;
- return { data: next as unknown as TData, updatedAt: Date.now() };
- });
+ writeQueue.update(
+ indexKey(scope),
+ (current) => {
+ const keys = (current?.data as unknown as string[] | undefined) ?? [];
+ const next = keys.filter((queryKey) => !dropped.has(queryKey));
+ if (!current || next.length === keys.length) return undefined;
+ return { data: next as unknown as TData, updatedAt: Date.now() };
+ },
+ { read: 'prefer-strict' },
+ );
};
/** Take rows whose delete landed out of the index, unless rewritten since. */
@@ -314,6 +486,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
*/
const deleteRows = (scope: string, queryKeys: string[]): Promise<boolean> => {
const queue = writeQueue!;
+ forgetStored(scope, queryKeys);
const queued = queryKeys.map((queryKey) => {
const seq = noteWrite(scope, queryKey);
return queue
@@ -385,7 +558,17 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
void deleteRows(effect.scope, [key.queryKey]);
continue;
}
- writeQueue.set(key, { data, updatedAt: Date.now() });
+ // The row already holds this value: an unchanged revalidation is no write.
+ if (isStored(effect.scope, key.queryKey, data)) {
+ touchStorageKey(effect.scope, key.queryKey);
+ continue;
+ }
+ rememberStored(effect.scope, key.queryKey, data);
+ void writeQueue.set(key, { data, updatedAt: Date.now() }).then((written) => {
+ // A failed write leaves the row as it was: the next persist must retry.
+ if (!written && storedValues.get(effect.scope)?.get(key.queryKey) === data)
+ forgetStored(effect.scope, [key.queryKey]);
+ });
trackStorageKey(effect.scope, key.queryKey);
}
};
@@ -419,6 +602,8 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const writes: ReplicaViewWrite<TData>[] = [];
const read = (key: string) => readThrough(writes, key);
if (slot.scope !== undefined && slot.scope !== activeScope) {
+ // Memory moves to another identity; what we knew of its rows can go.
+ storedValues.delete(slot.scope);
const reset = replicaReducer(slot, { scope: activeScope, type: 'resetScope' }, read);
writes.push(...reset.writes);
slot = reset.state;
@@ -513,17 +698,22 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const purge = scopePurges.get(scope);
if (purge && !(await purge)) return false;
const query = resource.query(params);
- const cached = await storage.get({ ...storageKey(key, query), scope });
+ const { queryKey } = storageKey(key, query);
+ const writesBefore = writeCounter;
+ const cached = await storage.get({ queryKey, scope });
if (!cached) return false;
// Re-check after the read: a removal or a clear that landed while it was in
// flight must not resurrect the row it just dropped.
if (isRemoved(scope, key) || clearGeneration(scope) !== generation) return false;
+ // The row holds what was read, unless a write was queued while reading.
+ if (writeCounter === writesBefore && !storedValues.get(scope)?.has(queryKey))
+ rememberStored(scope, queryKey, cached.data);
if (options.isHydratable && !options.isHydratable(cached.data, params)) return false;
// Entities deleted while the read was in flight may still be in the row.
const stored = withoutRemovedEntities(scope, cached.data);
if (stored === undefined) return false;
const data = overwrite ? keepClientOnlyRows(stored, port.read(key)) : stored;
- return dispatch({
+ const applied = dispatch({
data,
key,
overwrite,
@@ -533,6 +723,9 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
type: 'hydrate',
updatedAt: cached.updatedAt,
});
+ // A hydrated row is a used row (bounded resources keep LRU order).
+ if (applied && resource.scope.canPersist()) touchStorageKey(scope, queryKey);
+ return applied;
};
const viewMatchesFields = (current: TData | undefined, params: TParams) => {
@@ -688,6 +881,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const scope = resource.scope.get();
clearGenerations.set(scope, clearGeneration(scope) + 1);
port.commit([{ type: 'clear' }], { entries: {}, scope }, `${prefix}/clear`);
+ storedValues.delete(scope);
const purge = purgeScope(scope);
scopePurges.set(scope, purge);
return purge;
@@ -904,13 +1098,17 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
* Apply an entity change to persisted rows that memory does not hold (the
* memory path already persists loaded entries). Read-modify-write runs in
* the per-key write queue, so it sees every earlier write; a missing row is
- * never recreated. Resolves once the patches have settled.
+ * never recreated. Resolves once the patches have settled: `true` when every
+ * unloaded row is known to be patched (or nothing is persisted), `false` when
+ * a row may still hold the old entity (untrusted scope, unreadable index or
+ * row, a failed write, an identity switch mid-pass).
*/
- const patchStoredEntity = async <TItem>(
+ const patchStoredEntityRows = async <TItem>(
id: string,
fn: (item: TItem) => TItem | undefined,
- ): Promise<void> => {
- if (!writeQueue || !resource.scope.canPersist()) return;
+ ): Promise<boolean> => {
+ if (!writeQueue) return true;
+ if (!resource.scope.canPersist()) return false;
const scope = resource.scope.get();
const slot = getSlot();
const loaded = new Set(
@@ -923,34 +1121,47 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
keys = await readIndex(scope);
} catch (error) {
// Rows cannot be enumerated: nothing to patch. Loaded entries are already
- // updated, and a removal still guards later hydrates (`removeEntity`).
+ // updated, and a removal keeps guarding later hydrates (`removeEntity`).
console.error(`[replica:${resource.name}] failed to read the persisted index`, error);
- return;
+ return false;
}
// Identity changed while reading the index: those rows are not ours to touch.
- if (resource.scope.get() !== scope) return;
- const patches: Promise<void>[] = [];
+ if (resource.scope.get() !== scope) return false;
+ const patches: Promise<boolean>[] = [];
for (const queryKey of keys) {
if (loaded.has(queryKey)) continue;
const seq = noteWrite(scope, queryKey);
+ forgetStored(scope, [queryKey]);
let dropped = false;
const patch = writeQueue
- .update({ queryKey, scope }, (current) => {
- if (!current) return undefined;
- const next = mapEntity(current.data, id, fn);
- if (next === current.data) return undefined;
- if (next === undefined) {
- dropped = true;
- return null;
- }
- return { data: next, updatedAt: Date.now() };
- })
+ .update(
+ { queryKey, scope },
+ (current) => {
+ if (!current) return undefined;
+ const next = mapEntity(current.data, id, fn);
+ if (next === current.data) return undefined;
+ if (next === undefined) {
+ dropped = true;
+ return null;
+ }
+ return { data: next, updatedAt: Date.now() };
+ },
+ { read: 'strict' },
+ )
.then((written) => {
if (written && dropped) confirmDeleted(scope, [[queryKey, seq]]);
+ return written;
});
patches.push(patch);
}
- await Promise.all(patches);
+ return (await Promise.all(patches)).every(Boolean);
+ };
+
+ const patchStoredEntity = async <TItem>(
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ ): Promise<void> => {
+ await patchStoredEntityRows(id, fn);
};
/**
@@ -983,18 +1194,23 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
for (const queryKey of keys) {
if (loaded.has(queryKey)) continue;
const seq = noteWrite(scope, queryKey);
+ forgetStored(scope, [queryKey]);
let dropped = false;
const patch = writeQueue
- .update({ queryKey, scope }, (current) => {
- if (!current) return undefined;
- const next = fn(current.data);
- if (next === current.data || next === undefined) return undefined;
- if (next === null) {
- dropped = true;
- return null;
- }
- return { data: next, updatedAt: Date.now() };
- })
+ .update(
+ { queryKey, scope },
+ (current) => {
+ if (!current) return undefined;
+ const next = fn(current.data);
+ if (next === current.data || next === undefined) return undefined;
+ if (next === null) {
+ dropped = true;
+ return null;
+ }
+ return { data: next, updatedAt: Date.now() };
+ },
+ { read: 'strict' },
+ )
.then((written) => {
if (written && dropped) confirmDeleted(scope, [[queryKey, seq]]);
});
@@ -1003,13 +1219,16 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
await Promise.all(patches);
};
- /** `updateEntity`, returning the persisted-row patch (if any) to wait on. */
+ /**
+ * `updateEntity`, returning the persisted-row patch (if any) to wait on β€”
+ * `true` once every unloaded row is patched.
+ */
const applyEntity = <TItem>(
id: string,
fn: (item: TItem) => TItem | undefined,
{ persist = true }: { persist?: boolean } = {},
- ): Promise<void> | undefined => {
- const patch = persist ? patchStoredEntity(id, fn) : undefined;
+ ): Promise<boolean> | undefined => {
+ const patch = persist ? patchStoredEntityRows(id, fn) : undefined;
for (const key of entityKeys(id)) {
const current = port.read(key);
if (current === undefined) continue;
@@ -1052,7 +1271,18 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const patch = applyEntity(id, () => undefined, options);
// Without a storage patch (`persist: false`) only reads already in flight
// can hold the entity; with one, reads that start before it lands can too.
- if (patch) void patch.then(release, release);
+ // A patch that did not land (untrusted scope, unreadable index or row, a
+ // failed write, an identity switch) leaves the entity in an unloaded row:
+ // every later hydrate of that row could resurrect it, so the guard is kept
+ // β€” until a server value holds the entity again, or a later removal of the
+ // same id lands its patch.
+ if (patch)
+ void patch.then(
+ (patched) => {
+ if (patched) release();
+ },
+ () => undefined,
+ );
else release();
};
@@ -1091,6 +1321,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
removeEntity,
replace,
resource,
+ retain,
revalidate,
update,
updateEntity,
diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.ts
index 47e8a9d5aef..023a126254b 100644
--- a/packages/replica/src/core/types.ts
+++ b/packages/replica/src/core/types.ts
@@ -24,10 +24,14 @@ export interface ReplicaStorage<T> {
/**
* Strict read for destructive passes: like `get`, but **rejects** when the
* row could not be read (I/O error, unparsable value) instead of reporting a
- * miss. The engine reads its per-scope index through it before `remove` /
- * `clear`, so an unreadable index fails the purge rather than passing for an
- * empty one. Optional: without it `get` is used, which is only correct for a
- * storage whose `get` already rejects on failure.
+ * miss. The engine reads its per-scope index (and every row it patches)
+ * through it before `remove` / `clear` / an entity patch / an eviction, so an
+ * unreadable index fails the pass rather than passing for an empty one.
+ *
+ * Optional only for compatibility: a storage without it still hydrates and
+ * persists, but every destructive pass **fails** (`clear()` resolves `false`,
+ * a removal stays unpurged and is retried, an entity guard is kept) because
+ * the engine cannot tell a miss from a failed read through `get`.
*/
getStrict?: (key: ReplicaRowKey) => Promise<ReplicaRow<T> | undefined>;
/**
@@ -105,6 +109,8 @@ export interface ReplicaResource<TParams, TData, TFetched = TData, TCursor = any
/** Paged resources receive the page cursor (`undefined` = head page). */
fetcher?: (params: TParams, cursor?: TCursor) => Promise<TFetched>;
key: (params: TParams) => string;
+ /** Cap of persisted rows per scope (LRU eviction, see `DefineReplicaOptions.persist`). */
+ maxPersistedEntries?: number;
name: string;
/** Storage namespace β€” `name` + `version`, so a version bump orphans old rows. */
namespace: string;
diff --git a/packages/replica/src/core/writeQueue.test.ts b/packages/replica/src/core/writeQueue.test.ts
index b840141b2ba..ccea124c394 100644
--- a/packages/replica/src/core/writeQueue.test.ts
+++ b/packages/replica/src/core/writeQueue.test.ts
@@ -75,4 +75,30 @@ describe('ReplicaWriteQueue', () => {
await expect(queue.remove(key)).resolves.toBe(false);
await expect(queue.set(key, { data: 1, updatedAt: 1 })).resolves.toBe(true);
});
+
+ it('update reads best-effort by default, and strictly only when asked', async () => {
+ const set = vi.fn(async () => {});
+ const legacy: ReplicaStorage<number> = { get: async () => undefined, remove: vi.fn(), set };
+ const key = { queryKey: 'row', scope: 'scope' };
+ const queue = new ReplicaWriteQueue(legacy);
+ const next = () => ({ data: 1, updatedAt: 1 });
+
+ expect(await queue.update(key, next)).toBe(true);
+ expect(await queue.update(key, next, { read: 'prefer-strict' })).toBe(true);
+ // No `getStrict`: a strict read-modify-write refuses rather than guessing.
+ expect(await queue.update(key, next, { read: 'strict' })).toBe(false);
+ expect(set).toHaveBeenCalledTimes(2);
+
+ const failing = new ReplicaWriteQueue<number>({
+ get: async () => undefined,
+ getStrict: async () => {
+ throw new Error('read failed');
+ },
+ remove: vi.fn(),
+ set,
+ });
+ // A failed strict read never passes for a missing row.
+ expect(await failing.update(key, next, { read: 'prefer-strict' })).toBe(false);
+ expect(set).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/packages/replica/src/core/writeQueue.ts b/packages/replica/src/core/writeQueue.ts
index 89d12becc32..6557159d9ed 100644
--- a/packages/replica/src/core/writeQueue.ts
+++ b/packages/replica/src/core/writeQueue.ts
@@ -1,5 +1,22 @@
import type { ReplicaRow, ReplicaRowKey, ReplicaStorage } from './types';
+/**
+ * Strict read of one row (see `ReplicaStorage.getStrict`). Rejects when the
+ * storage has no strict read: its `get` swallows I/O failures into a miss, so a
+ * destructive pass reading through it could take an unreadable row (the index)
+ * for an empty one and report success for rows it never saw.
+ */
+export const readReplicaRowStrict = <T>(
+ storage: ReplicaStorage<T>,
+ key: ReplicaRowKey,
+): Promise<ReplicaRow<T> | undefined> =>
+ // Call through `storage`: a class-based storage needs its receiver.
+ storage.getStrict
+ ? storage.getStrict(key)
+ : Promise.reject(
+ new Error('[replica] storage has no `getStrict`: destructive passes are disabled'),
+ );
+
/**
* Serializes writes for one projection key. A later snapshot can never be overwritten by an
* earlier, slower IndexedDB write.
@@ -25,13 +42,25 @@ export class ReplicaWriteQueue<T> {
* Serialized read-modify-write: `fn` sees the row as of every earlier queued
* write for this key. Return a projection to write it, `null` to remove the
* row, or `undefined` to leave it untouched (a missing row stays missing).
+ *
+ * `read` picks how the row is read:
+ * - `'get'` (default): best-effort `get`, a failed read passes for a miss.
+ * - `'prefer-strict'`: `getStrict` when the storage has one, so a read failure
+ * fails the update (resolves `false`) instead of passing for a missing row
+ * that `fn` would then overwrite; `get` otherwise.
+ * - `'strict'`: `getStrict` only; a storage without it fails the update.
+ * Required for destructive passes (see `readReplicaRowStrict`).
*/
update = (
key: ReplicaRowKey,
fn: (current: ReplicaRow<T> | undefined) => ReplicaRow<T> | null | undefined,
+ { read = 'get' }: { read?: 'get' | 'prefer-strict' | 'strict' } = {},
): Promise<boolean> =>
this.#enqueue(key, async () => {
- const next = fn(await this.#storage.get(key));
+ const storage = this.#storage;
+ const strict = read === 'strict' || (read === 'prefer-strict' && !!storage.getStrict);
+ const current = await (strict ? readReplicaRowStrict(storage, key) : storage.get(key));
+ const next = fn(current);
if (next === null) await this.#storage.remove(key);
else if (next !== undefined) await this.#storage.set(key, next);
});
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.ts
index 23657a81fb2..7327613a50f 100644
--- a/packages/replica/src/zustand/createReplicaSlice.test.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts
@@ -34,11 +34,13 @@ const createMemoryStorage = (delays: Record<string, number> = {}) => {
const rows = new Map<string, ReplicaRow<string[]>>();
const writes: string[] = [];
const indexRows = new Map<string, ReplicaRow<string[]>>();
+ const read: ReplicaStorage<string[]>['get'] = async ({ queryKey, scope }) =>
+ queryKey === REPLICA_INDEX_KEY
+ ? (indexRows.get(scope) as ReplicaRow<string[]> | undefined)
+ : rows.get(`${scope}|${queryKey}`);
const storage: ReplicaStorage<string[]> = {
- get: async ({ queryKey, scope }) =>
- queryKey === REPLICA_INDEX_KEY
- ? (indexRows.get(scope) as ReplicaRow<string[]> | undefined)
- : rows.get(`${scope}|${queryKey}`),
+ get: read,
+ getStrict: read,
remove: async ({ queryKey, scope }) => {
if (queryKey === REPLICA_INDEX_KEY) return void indexRows.delete(scope);
rows.delete(`${scope}|${queryKey}`);
diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.ts
index ef92f80e34f..d71092e51c4 100644
--- a/packages/replica/src/zustand/createReplicaSlice.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.ts
@@ -129,7 +129,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
},
revalidate,
});
- const { clearGeneration, ensureScope, fetcher, hydrate, replace } = engine;
+ const { clearGeneration, ensureScope, fetcher, hydrate, replace, retain } = engine;
/**
* Row key of the head query each entry last asked for. One entry backs a
@@ -174,6 +174,11 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
if (active && key !== undefined && queryKey !== undefined) headQuery.set(key, queryKey);
}, [active, key, queryKey]);
+ // Pin the entry on screen against eviction (`persist.maxEntries`).
+ useLayoutEffect(() => {
+ if (active && key !== undefined && queryKey !== undefined) return retain(key, queryKey);
+ }, [active, key, queryKey]);
+
const hydration = driver.useQuery<boolean>(
active && resource.persisted && resource.persistKey(key!)
? replicaKeys.hydrate(resource.name, resource.version, scope, resource.storageKey(params!))
diff --git a/packages/replica/src/zustand/pagedSlice.test.ts b/packages/replica/src/zustand/pagedSlice.test.ts
index 326ff9d0eca..8d809b68f55 100644
--- a/packages/replica/src/zustand/pagedSlice.test.ts
+++ b/packages/replica/src/zustand/pagedSlice.test.ts
@@ -38,8 +38,11 @@ const scope: ReplicaScope = {
const createMemoryStorage = <T>() => {
const rows = new Map<string, ReplicaRow<T>>();
+ const read: ReplicaStorage<T>['get'] = async ({ queryKey, scope }) =>
+ rows.get(`${scope}|${queryKey}`);
const storage: ReplicaStorage<T> = {
- get: async ({ queryKey, scope }) => rows.get(`${scope}|${queryKey}`),
+ get: read,
+ getStrict: read,
remove: async ({ queryKey, scope }) => {
rows.delete(`${scope}|${queryKey}`);
},
diff --git a/src/features/Memory/index.ts b/src/features/Memory/index.ts
index b359ae37dfd..cb9bb394ea3 100644
--- a/src/features/Memory/index.ts
+++ b/src/features/Memory/index.ts
@@ -1,2 +1,3 @@
export { MemoryListBoundary } from './MemoryListBoundary';
-export { useResetMemoryList, type ViewMode } from './useResetMemoryList';
+
+export type ViewMode = 'grid' | 'timeline';
diff --git a/src/features/Memory/useCachedMemoryList.test.ts b/src/features/Memory/useCachedMemoryList.test.ts
deleted file mode 100644
index 409a90ac6a5..00000000000
--- a/src/features/Memory/useCachedMemoryList.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { renderHook, waitFor } from '@testing-library/react';
-import { type PropsWithChildren } from 'react';
-import { createElement } from 'react';
-import { type State, SWRConfig } from 'swr';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { userMemoryService } from '@/services/userMemory';
-import { useUserMemoryStore } from '@/store/userMemory';
-import { initialState } from '@/store/userMemory/initialState';
-
-import { useResetMemoryList } from './useResetMemoryList';
-
-const createSWRWrapper = () => {
- const value = {
- dedupingInterval: 60_000,
- provider: () => new Map<string, State>(),
- };
-
- return function SWRTestWrapper({ children }: PropsWithChildren) {
- return createElement(SWRConfig, { value }, children);
- };
-};
-
-const useActivitySearch = (query: string) => {
- const activities = useUserMemoryStore((state) => state.activities);
- const activitiesPage = useUserMemoryStore((state) => state.activitiesPage);
- const activitiesSearchLoading = useUserMemoryStore((state) => state.activitiesSearchLoading);
- const resetActivitiesList = useUserMemoryStore((state) => state.resetActivitiesList);
- const useFetchActivities = useUserMemoryStore((state) => state.useFetchActivities);
-
- useResetMemoryList({
- query,
- resetList: resetActivitiesList,
- viewMode: 'timeline',
- });
- useFetchActivities({ page: activitiesPage, pageSize: 12, q: query });
-
- return { activities, activitiesSearchLoading };
-};
-
-describe('cached memory list hydration', () => {
- beforeEach(() => {
- vi.restoreAllMocks();
- useUserMemoryStore.setState(initialState, false);
- });
-
- it('restores a cached search after switching away and back within the deduping interval', async () => {
- vi.spyOn(userMemoryService, 'queryActivities').mockImplementation(async (params) => ({
- items: [{ id: params?.q } as never],
- page: params?.page ?? 1,
- pageSize: params?.pageSize ?? 12,
- total: 1,
- }));
-
- const { rerender, result } = renderHook(({ query }) => useActivitySearch(query), {
- initialProps: { query: 'alpha' },
- wrapper: createSWRWrapper(),
- });
-
- await waitFor(() => {
- expect(result.current).toEqual({
- activities: [{ id: 'alpha' }],
- activitiesSearchLoading: false,
- });
- });
-
- rerender({ query: 'beta' });
- await waitFor(() => {
- expect(result.current).toEqual({
- activities: [{ id: 'beta' }],
- activitiesSearchLoading: false,
- });
- });
-
- rerender({ query: 'alpha' });
- await waitFor(() => {
- expect(result.current).toEqual({
- activities: [{ id: 'alpha' }],
- activitiesSearchLoading: false,
- });
- });
- expect(userMemoryService.queryActivities).toHaveBeenCalledTimes(2);
- });
-});
diff --git a/src/features/Memory/useResetMemoryList.test.ts b/src/features/Memory/useResetMemoryList.test.ts
deleted file mode 100644
index be0d0960312..00000000000
--- a/src/features/Memory/useResetMemoryList.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { renderHook } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { useResetMemoryList, type ViewMode } from './useResetMemoryList';
-
-describe('useResetMemoryList', () => {
- it('resets a timeline search when the backend uses its default sort', () => {
- const resetList = vi.fn();
-
- renderHook(() =>
- useResetMemoryList({
- query: 'late night',
- resetList,
- sort: undefined,
- viewMode: 'timeline',
- }),
- );
-
- expect(resetList).toHaveBeenCalledWith({ q: 'late night', sort: undefined });
- });
-
- it('does not reset when a view change keeps the effective sort unchanged', () => {
- const resetList = vi.fn();
- const initialProps: { viewMode: ViewMode } = { viewMode: 'timeline' };
- const { rerender } = renderHook(
- ({ viewMode }: { viewMode: ViewMode }) =>
- useResetMemoryList({
- query: 'late night',
- resetList,
- sort: undefined,
- viewMode,
- }),
- { initialProps },
- );
-
- rerender({ viewMode: 'grid' });
-
- expect(resetList).toHaveBeenCalledTimes(1);
- });
-
- it('resets when a view change activates an explicit grid sort', () => {
- const resetList = vi.fn();
- const initialProps: { viewMode: ViewMode } = { viewMode: 'timeline' };
- const { rerender } = renderHook(
- ({ viewMode }: { viewMode: ViewMode }) =>
- useResetMemoryList({
- query: 'late night',
- resetList,
- sort: 'scorePriority',
- viewMode,
- }),
- { initialProps },
- );
-
- rerender({ viewMode: 'grid' });
-
- expect(resetList).toHaveBeenNthCalledWith(2, {
- q: 'late night',
- sort: 'scorePriority',
- });
- });
-});
diff --git a/src/features/Memory/useResetMemoryList.ts b/src/features/Memory/useResetMemoryList.ts
deleted file mode 100644
index 2a240397f55..00000000000
--- a/src/features/Memory/useResetMemoryList.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { useLayoutEffect } from 'react';
-
-export type ViewMode = 'grid' | 'timeline';
-
-interface UseResetMemoryListOptions<Sort extends string> {
- query: string;
- resetList: (params: { q?: string; sort?: Sort }) => void;
- sort?: Sort;
- viewMode: ViewMode;
-}
-
-/**
- * Reset pagination before passive SWR hydration effects run for a new list query. An undefined
- * sort is the backend default, not a reason to skip a search reset.
- */
-export const useResetMemoryList = <Sort extends string>({
- query,
- resetList,
- sort,
- viewMode,
-}: UseResetMemoryListOptions<Sort>) => {
- const activeSort = viewMode === 'grid' ? sort : undefined;
-
- useLayoutEffect(() => {
- resetList({ q: query || undefined, sort: activeSort });
- }, [activeSort, query, resetList]);
-};
diff --git a/src/libs/queryProjectionStorage/indexedDB.ts b/src/libs/queryProjectionStorage/indexedDB.ts
index 891573c044a..184a059e903 100644
--- a/src/libs/queryProjectionStorage/indexedDB.ts
+++ b/src/libs/queryProjectionStorage/indexedDB.ts
@@ -26,16 +26,16 @@ export class IndexedDBQueryProjectionStorage<T> implements QueryProjectionStorag
}
};
- /**
- * Rejects when the delete did not land, unlike reads and writes: a caller
- * that removes a row the user deleted must be able to retry it.
- */
/** Like `get`, but rejects when the row could not be read (see `ReplicaStorage.getStrict`). */
getStrict = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {
await localDatabase.initialize();
return localDatabase.get<QueryProjection<T>>(COLLECTION, this.#key(key));
};
+ /**
+ * Rejects when the delete did not land, unlike reads and writes: a caller
+ * that removes a row the user deleted must be able to retry it.
+ */
remove = async (key: QueryProjectionKey): Promise<void> => {
await localDatabase.initialize();
await localDatabase.delete(COLLECTION, this.#key(key));
diff --git a/src/libs/queryProjectionStorage/types.ts b/src/libs/queryProjectionStorage/types.ts
index 772f3e90348..49fac7f6793 100644
--- a/src/libs/queryProjectionStorage/types.ts
+++ b/src/libs/queryProjectionStorage/types.ts
@@ -10,8 +10,12 @@ export interface QueryProjection<T> {
export interface QueryProjectionStorage<T> {
get: (key: QueryProjectionKey) => Promise<QueryProjection<T> | undefined>;
- /** Like `get`, but rejects when the row could not be read (destructive passes). */
- getStrict?: (key: QueryProjectionKey) => Promise<QueryProjection<T> | undefined>;
+ /**
+ * Like `get`, but rejects when the row could not be read. Required: a replica
+ * refuses destructive passes (remove / clear / entity patch / eviction) on a
+ * storage without it.
+ */
+ getStrict: (key: QueryProjectionKey) => Promise<QueryProjection<T> | undefined>;
/** Rejects when the delete did not land (reads and writes stay best-effort). */
remove: (key: QueryProjectionKey) => Promise<void>;
set: (key: QueryProjectionKey, projection: QueryProjection<T>) => Promise<void>;
diff --git a/src/libs/queryProjectionStorage/writeQueue.test.ts b/src/libs/queryProjectionStorage/writeQueue.test.ts
index eff23aafbf9..f65fca3d41c 100644
--- a/src/libs/queryProjectionStorage/writeQueue.test.ts
+++ b/src/libs/queryProjectionStorage/writeQueue.test.ts
@@ -10,6 +10,7 @@ describe('QueryProjectionWriteQueue', () => {
const calls: number[] = [];
const storage: QueryProjectionStorage<number> = {
get: vi.fn(),
+ getStrict: vi.fn(),
remove: vi.fn(),
set: vi.fn(async (_key, projection) => {
calls.push(projection.data);
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 4c3e14b3fc4..11ada9b726f 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -626,13 +626,6 @@ export const userMemoryKeys = {
'userMemory:experiences',
params,
]),
- /** Injection identities (distinct from the paginated `identityList`). */
- identities: def('userMemory:identities', () => ['userMemory:identities']),
- /** Paginated identity list for the memory home views. */
- identityList: def('userMemory:identityList', (params: unknown) => [
- 'userMemory:identityList',
- params,
- ]),
memoryDetail: def('userMemory:memoryDetail', (layer: string, id: string) => [
'userMemory:memoryDetail',
layer,
@@ -648,10 +641,6 @@ export const userMemoryKeys = {
cacheKey,
]),
tags: def('userMemory:tags', () => ['userMemory:tags']),
- topicMemories: def('userMemory:topicMemories', (topicId: string) => [
- 'userMemory:topicMemories',
- topicId,
- ]),
};
// ---- tool (skills / plugins / builtin / mcp / composio stores) -------------
diff --git a/src/routes/(main)/memory/activities/features/List/GridView/index.tsx b/src/routes/(main)/memory/activities/features/List/GridView/index.tsx
index f76f7ac0a4d..ff5de6c174f 100644
--- a/src/routes/(main)/memory/activities/features/List/GridView/index.tsx
+++ b/src/routes/(main)/memory/activities/features/List/GridView/index.tsx
@@ -15,12 +15,16 @@ interface GridViewProps {
const ActivitiesGridView = memo<GridViewProps>(({ activities, isLoading, onClick }) => {
const loadMoreActivities = useUserMemoryStore((s) => s.loadMoreActivities);
const activitiesHasMore = useUserMemoryStore((s) => s.activitiesHasMore);
+ // Load-more progress / failure of the query on screen (footer + retry).
+ const isLoadingMore = useUserMemoryStore((s) => Boolean(s.activityListData?.isLoadingMore));
+ const loadMoreError = useUserMemoryStore((s) => s.activityListData?.loadMoreError);
return (
<GridView
hasMore={activitiesHasMore}
- isLoading={isLoading}
+ isLoading={isLoading || isLoadingMore}
items={activities}
+ loadMoreError={loadMoreError}
renderItem={(activity: ActivityListItem) => (
<ActivityCard activity={activity} onClick={() => onClick(activity)} />
)}
diff --git a/src/routes/(main)/memory/activities/features/List/TimelineView/index.tsx b/src/routes/(main)/memory/activities/features/List/TimelineView/index.tsx
index 38ed2f9749b..b3ae5d533ab 100644
--- a/src/routes/(main)/memory/activities/features/List/TimelineView/index.tsx
+++ b/src/routes/(main)/memory/activities/features/List/TimelineView/index.tsx
@@ -19,13 +19,17 @@ const ActivityTimelineView = memo<ActivityTimelineViewProps>(
({ activities, isLoading, onCardClick }) => {
const loadMoreActivities = useUserMemoryStore((s) => s.loadMoreActivities);
const activitiesHasMore = useUserMemoryStore((s) => s.activitiesHasMore);
+ // Load-more progress / failure of the query on screen (footer + retry).
+ const isLoadingMore = useUserMemoryStore((s) => Boolean(s.activityListData?.isLoadingMore));
+ const loadMoreError = useUserMemoryStore((s) => s.activityListData?.loadMoreError);
return (
<GenericTimelineView
data={activities}
groupBy="day"
hasMore={activitiesHasMore}
- isLoading={isLoading}
+ isLoading={isLoading || isLoadingMore}
+ loadMoreError={loadMoreError}
renderHeader={(periodKey: string) => <PeriodHeader groupBy="day" periodKey={periodKey} />}
renderItem={(activity: ActivityListItem) => (
<TimelineItemWrapper>
diff --git a/src/routes/(main)/memory/activities/index.tsx b/src/routes/(main)/memory/activities/index.tsx
index 9a6019396f7..70458a798a0 100644
--- a/src/routes/(main)/memory/activities/index.tsx
+++ b/src/routes/(main)/memory/activities/index.tsx
@@ -5,7 +5,7 @@ import { type FC } from 'react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { MemoryListBoundary, useResetMemoryList } from '@/features/Memory';
+import { MemoryListBoundary } from '@/features/Memory';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
@@ -35,10 +35,7 @@ const ActivitiesArea = memo(() => {
const activitiesPage = useUserMemoryStore((s) => s.activitiesPage);
const activitiesInit = useUserMemoryStore((s) => s.activitiesInit);
const activitiesTotal = useUserMemoryStore((s) => s.activitiesTotal);
- const activitiesSearchError = useUserMemoryStore((s) => s.activitiesSearchError);
- const activitiesSearchLoading = useUserMemoryStore((s) => s.activitiesSearchLoading);
const useFetchActivities = useUserMemoryStore((s) => s.useFetchActivities);
- const resetActivitiesList = useUserMemoryStore((s) => s.resetActivitiesList);
const sortOptions = [
{ label: t('filter.sort.createdAt'), value: 'capturedAt' },
@@ -47,14 +44,10 @@ const ActivitiesArea = memo(() => {
const apiSort = sortValue === 'capturedAt' ? undefined : (sortValue as 'startsAt');
- useResetMemoryList({
- query: searchValue,
- resetList: resetActivitiesList,
- sort: apiSort,
- viewMode,
- });
-
- const { data, isLoading, mutate } = useFetchActivities({
+ // Each search / sort is its own replica entry: the hook selects it before
+ // paint, so the previous query's rows never show under this one. `error` is
+ // this query's failure while it has nothing painted.
+ const { data, error, isLoading, mutate } = useFetchActivities({
page: activitiesPage,
pageSize: 12,
q: searchValue || undefined,
@@ -106,10 +99,9 @@ const ActivitiesArea = memo(() => {
/>
<MemoryListBoundary
data={data}
- error={activitiesSearchError}
+ error={error}
isInitialized={activitiesInit}
isLoading={isLoading}
- isResetting={activitiesSearchLoading}
loading={<Loading viewMode={viewMode} />}
onRetry={() => void mutate()}
>
diff --git a/src/routes/(main)/memory/contexts/features/List/GridView/index.tsx b/src/routes/(main)/memory/contexts/features/List/GridView/index.tsx
index 04960968639..9545d780c41 100644
--- a/src/routes/(main)/memory/contexts/features/List/GridView/index.tsx
+++ b/src/routes/(main)/memory/contexts/features/List/GridView/index.tsx
@@ -15,13 +15,17 @@ interface GridViewProps {
const ContextsGridView = memo<GridViewProps>(({ contexts, isLoading, onClick }) => {
const loadMoreContexts = useUserMemoryStore((s) => s.loadMoreContexts);
const contextsHasMore = useUserMemoryStore((s) => s.contextsHasMore);
+ // Load-more progress / failure of the query on screen (footer + retry).
+ const isLoadingMore = useUserMemoryStore((s) => Boolean(s.contextListData?.isLoadingMore));
+ const loadMoreError = useUserMemoryStore((s) => s.contextListData?.loadMoreError);
return (
<GridView
defaultColumnCount={2}
hasMore={contextsHasMore}
- isLoading={isLoading}
+ isLoading={isLoading || isLoadingMore}
items={contexts}
+ loadMoreError={loadMoreError}
renderItem={(context) => <ContextCard context={context} onClick={() => onClick(context)} />}
onLoadMore={loadMoreContexts}
/>
diff --git a/src/routes/(main)/memory/contexts/features/List/TimelineView/index.tsx b/src/routes/(main)/memory/contexts/features/List/TimelineView/index.tsx
index 11c5093d618..f7f14fa1c30 100644
--- a/src/routes/(main)/memory/contexts/features/List/TimelineView/index.tsx
+++ b/src/routes/(main)/memory/contexts/features/List/TimelineView/index.tsx
@@ -18,13 +18,17 @@ interface ContextTimelineViewProps {
const ContextTimelineView = memo<ContextTimelineViewProps>(({ contexts, isLoading, onClick }) => {
const loadMoreContexts = useUserMemoryStore((s) => s.loadMoreContexts);
const contextsHasMore = useUserMemoryStore((s) => s.contextsHasMore);
+ // Load-more progress / failure of the query on screen (footer + retry).
+ const isLoadingMore = useUserMemoryStore((s) => Boolean(s.contextListData?.isLoadingMore));
+ const loadMoreError = useUserMemoryStore((s) => s.contextListData?.loadMoreError);
return (
<GenericTimelineView
data={contexts}
groupBy="day"
hasMore={contextsHasMore}
- isLoading={isLoading}
+ isLoading={isLoading || isLoadingMore}
+ loadMoreError={loadMoreError}
renderHeader={(periodKey) => <PeriodHeader groupBy="day" periodKey={periodKey} />}
renderItem={(context) => (
<TimelineItemWrapper>
diff --git a/src/routes/(main)/memory/contexts/index.tsx b/src/routes/(main)/memory/contexts/index.tsx
index 664440e3574..a5466d38bc6 100644
--- a/src/routes/(main)/memory/contexts/index.tsx
+++ b/src/routes/(main)/memory/contexts/index.tsx
@@ -5,7 +5,7 @@ import { type FC } from 'react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { MemoryListBoundary, useResetMemoryList } from '@/features/Memory';
+import { MemoryListBoundary } from '@/features/Memory';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
@@ -35,10 +35,7 @@ const ContextsArea = memo(() => {
const contextsPage = useUserMemoryStore((s) => s.contextsPage);
const contextsInit = useUserMemoryStore((s) => s.contextsInit);
const contextsTotal = useUserMemoryStore((s) => s.contextsTotal);
- const contextsSearchError = useUserMemoryStore((s) => s.contextsSearchError);
- const contextsSearchLoading = useUserMemoryStore((s) => s.contextsSearchLoading);
const useFetchContexts = useUserMemoryStore((s) => s.useFetchContexts);
- const resetContextsList = useUserMemoryStore((s) => s.resetContextsList);
const sortOptions = [
{ label: t('filter.sort.createdAt'), value: 'capturedAt' },
@@ -50,15 +47,11 @@ const ContextsArea = memo(() => {
const apiSort =
sortValue === 'capturedAt' ? undefined : (sortValue as 'scoreImpact' | 'scoreUrgency');
- useResetMemoryList({
- query: searchValue,
- resetList: resetContextsList,
- sort: apiSort,
- viewMode,
- });
-
// Call SWR hook to fetch data
- const { data, isLoading, mutate } = useFetchContexts({
+ // Each search / sort is its own replica entry: the hook selects it before
+ // paint, so the previous query's rows never show under this one. `error` is
+ // this query's failure while it has nothing painted.
+ const { data, error, isLoading, mutate } = useFetchContexts({
page: contextsPage,
pageSize: 12,
q: searchValue || undefined,
@@ -111,10 +104,9 @@ const ContextsArea = memo(() => {
/>
<MemoryListBoundary
data={data}
- error={contextsSearchError}
+ error={error}
isInitialized={contextsInit}
isLoading={isLoading}
- isResetting={contextsSearchLoading}
loading={<Loading viewMode={viewMode} />}
onRetry={() => void mutate()}
>
diff --git a/src/routes/(main)/memory/features/GridView/index.tsx b/src/routes/(main)/memory/features/GridView/index.tsx
index 8bd7e64a5ca..a53f6abca0b 100644
--- a/src/routes/(main)/memory/features/GridView/index.tsx
+++ b/src/routes/(main)/memory/features/GridView/index.tsx
@@ -4,8 +4,8 @@ import { type ReactNode } from 'react';
import { memo } from 'react';
import { VirtuosoGrid } from 'react-virtuoso';
-import Loading from '@/routes/(main)/memory/features/Loading';
-
+import LoadMoreFooter from '../LoadMoreFooter';
+import { autoLoadMoreProps, resolveLoadMoreFooter } from '../loadMoreFooterState';
import { useScrollParent } from '../TimeLineView/useScrollParent';
interface GridViewProps<T> {
@@ -23,6 +23,10 @@ interface GridViewProps<T> {
*/
isLoading?: boolean;
items: T[];
+ /**
+ * Failure of the last "load more" request; rendered with a retry below the rows
+ */
+ loadMoreError?: unknown;
/**
* Max item width in pixels
*/
@@ -46,10 +50,12 @@ function GridViewInner<T extends { id: string }>({
maxItemWidth = 240,
hasMore,
isLoading,
+ loadMoreError,
onLoadMore,
renderItem,
}: GridViewProps<T>) {
const scrollParent = useScrollParent();
+ const footer = resolveLoadMoreFooter({ isLoading, loadMoreError });
if (!items || items.length === 0) {
return null;
@@ -58,14 +64,21 @@ function GridViewInner<T extends { id: string }>({
return (
<VirtuosoGrid
customScrollParent={scrollParent}
- data={items}
- endReached={hasMore && onLoadMore ? onLoadMore : undefined}
+ {...autoLoadMoreProps({ hasMore, items, loadMoreError, onLoadMore })}
increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
overscan={48}
style={{ minHeight: '100%' }}
components={{
- Footer: isLoading
- ? () => <Loading rows={defaultColumnCount} viewMode={'grid'} />
+ Footer: footer
+ ? () => (
+ <LoadMoreFooter
+ loadMoreError={loadMoreError}
+ rows={defaultColumnCount}
+ state={footer}
+ viewMode={'grid'}
+ onRetry={onLoadMore}
+ />
+ )
: undefined,
// eslint-disable-next-line @eslint-react/no-nested-component-definitions
List: (({ ref, ...props }: DivProps & { ref?: React.RefObject<HTMLDivElement | null> }) => (
diff --git a/src/routes/(main)/memory/features/LoadMoreFooter.tsx b/src/routes/(main)/memory/features/LoadMoreFooter.tsx
new file mode 100644
index 00000000000..29b96e3b6d1
--- /dev/null
+++ b/src/routes/(main)/memory/features/LoadMoreFooter.tsx
@@ -0,0 +1,32 @@
+import { Flexbox } from '@lobehub/ui';
+import { memo } from 'react';
+
+import AsyncError from '@/components/AsyncError';
+
+import Loading from './Loading';
+import { type LoadMoreFooterState } from './loadMoreFooterState';
+import { type ViewMode } from './ViewModeSwitcher';
+
+interface LoadMoreFooterProps {
+ loadMoreError?: unknown;
+ onRetry?: () => void;
+ rows?: number;
+ state: LoadMoreFooterState;
+ viewMode: ViewMode;
+}
+
+/** Footer of a paginated memory list: page loading rows or an inline retry. */
+const LoadMoreFooter = memo<LoadMoreFooterProps>(
+ ({ loadMoreError, onRetry, rows, state, viewMode }) => {
+ if (state === 'loading') return <Loading rows={rows} viewMode={viewMode} />;
+ if (state !== 'error') return null;
+
+ return (
+ <Flexbox align={'center'} paddingBlock={12}>
+ <AsyncError error={loadMoreError} variant={'inline'} onRetry={onRetry} />
+ </Flexbox>
+ );
+ },
+);
+
+export default LoadMoreFooter;
diff --git a/src/routes/(main)/memory/features/TimeLineView/index.tsx b/src/routes/(main)/memory/features/TimeLineView/index.tsx
index 6879dea1c8a..34ab1190533 100644
--- a/src/routes/(main)/memory/features/TimeLineView/index.tsx
+++ b/src/routes/(main)/memory/features/TimeLineView/index.tsx
@@ -7,8 +7,9 @@ import { memo, useMemo } from 'react';
import { GroupedVirtuoso } from 'react-virtuoso';
import { useIsDark } from '@/hooks/useIsDark';
-import Loading from '@/routes/(main)/memory/features/Loading';
+import LoadMoreFooter from '../LoadMoreFooter';
+import { autoLoadMoreProps, resolveLoadMoreFooter } from '../loadMoreFooterState';
import { useScrollParent } from './useScrollParent';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -55,6 +56,10 @@ interface TimelineViewProps<
* Whether data is currently loading
*/
isLoading?: boolean;
+ /**
+ * Failure of the last "load more" request; rendered with a retry below the rows
+ */
+ loadMoreError?: unknown;
/**
* Callback when end is reached
*/
@@ -80,12 +85,14 @@ function TimelineViewInner<
getDateForGrouping,
hasMore,
isLoading,
+ loadMoreError,
onLoadMore,
renderHeader,
renderItem,
}: TimelineViewProps<T>) {
const isDarkMode = useIsDark();
const scrollParent = useScrollParent();
+ const footer = resolveLoadMoreFooter({ isLoading, loadMoreError });
const { groupCounts, sortedPeriods, groupedItems } = useMemo(() => {
const format = groupBy === 'month' ? 'YYYY-MM' : 'YYYY-MM-DD';
@@ -143,13 +150,22 @@ function TimelineViewInner<
<div className={cx(styles.timelineLine, isDarkMode && styles.timelineLine_dark)} />
<GroupedVirtuoso
customScrollParent={scrollParent}
- endReached={hasMore && onLoadMore ? onLoadMore : undefined}
+ {...autoLoadMoreProps({ hasMore, items: groupedItems, loadMoreError, onLoadMore })}
groupCounts={groupCounts}
increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
overscan={24}
style={{ minHeight: '100%' }}
components={{
- Footer: isLoading ? () => <Loading viewMode={'timeline'} /> : undefined,
+ Footer: footer
+ ? () => (
+ <LoadMoreFooter
+ loadMoreError={loadMoreError}
+ state={footer}
+ viewMode={'timeline'}
+ onRetry={onLoadMore}
+ />
+ )
+ : undefined,
}}
groupContent={(index) => {
const periodKey = sortedPeriods[index];
diff --git a/src/routes/(main)/memory/features/loadMoreFooterState.test.ts b/src/routes/(main)/memory/features/loadMoreFooterState.test.ts
new file mode 100644
index 00000000000..5bc5fcdceed
--- /dev/null
+++ b/src/routes/(main)/memory/features/loadMoreFooterState.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import { autoLoadMoreProps, canAutoLoadMore, resolveLoadMoreFooter } from './loadMoreFooterState';
+
+describe('resolveLoadMoreFooter', () => {
+ it('shows the loading rows while a page is in flight', () => {
+ expect(resolveLoadMoreFooter({ isLoading: true })).toBe('loading');
+ expect(resolveLoadMoreFooter({ isLoading: true, loadMoreError: new Error('x') })).toBe(
+ 'loading',
+ );
+ });
+
+ it('shows the failure of the last page so it can be retried', () => {
+ expect(resolveLoadMoreFooter({ loadMoreError: new Error('offline') })).toBe('error');
+ });
+
+ it('renders nothing once every page settled', () => {
+ expect(resolveLoadMoreFooter({})).toBeUndefined();
+ });
+});
+
+describe('canAutoLoadMore', () => {
+ it('requests the next page at the end of the list while there is more', () => {
+ expect(canAutoLoadMore({ hasMore: true })).toBe(true);
+ expect(canAutoLoadMore({ hasMore: false })).toBe(false);
+ });
+
+ it('waits for an explicit retry after a failed page', () => {
+ expect(canAutoLoadMore({ hasMore: true, loadMoreError: new Error('offline') })).toBe(false);
+ });
+});
+
+describe('autoLoadMoreProps', () => {
+ const onLoadMore = () => {};
+
+ // Virtuoso re-fires endReached only when [lastIndex, data] changes: after a
+ // delete collapses two loaded pages back to the head page, the end index is
+ // the one the head page already reported, so the trigger must be keyed on the
+ // rendered page set or the next page is never requested again.
+ it('keys the end-of-list trigger on the rendered page set', () => {
+ const headPage = Array.from({ length: 12 }, (_, i) => ({ id: `r${i}` }));
+ const collapsedHead = headPage.filter((row) => row.id !== 'r5').concat({ id: 'r12' });
+
+ const before = autoLoadMoreProps({ hasMore: true, items: headPage, onLoadMore });
+ const after = autoLoadMoreProps({ hasMore: true, items: collapsedHead, onLoadMore });
+
+ expect(before.data).toBe(headPage);
+ expect(after.data).toBe(collapsedHead);
+ expect(after.data.length - 1).toBe(before.data.length - 1);
+ expect(after.data).not.toBe(before.data);
+ expect(after.endReached).toBe(onLoadMore);
+ });
+
+ it('disarms the trigger when there is nothing more or the last page failed', () => {
+ expect(autoLoadMoreProps({ hasMore: false, items: [], onLoadMore }).endReached).toBeUndefined();
+ expect(
+ autoLoadMoreProps({ hasMore: true, items: [], loadMoreError: new Error('x'), onLoadMore })
+ .endReached,
+ ).toBeUndefined();
+ });
+});
diff --git a/src/routes/(main)/memory/features/loadMoreFooterState.ts b/src/routes/(main)/memory/features/loadMoreFooterState.ts
new file mode 100644
index 00000000000..b911bcd4f3f
--- /dev/null
+++ b/src/routes/(main)/memory/features/loadMoreFooterState.ts
@@ -0,0 +1,59 @@
+interface LoadMoreFooterParams {
+ /** A page (head revalidation or "load more") is in flight. */
+ isLoading?: boolean;
+ /** Failure of the last "load more" request. */
+ loadMoreError?: unknown;
+}
+
+export type LoadMoreFooterState = 'error' | 'loading' | undefined;
+
+/**
+ * What a paginated memory list renders below its rows: the loading rows while a
+ * page is in flight, otherwise the failure of the last "load more" (with a
+ * retry) β€” the item count did not change, so the virtualized list would never
+ * reach its end again on its own.
+ */
+export const resolveLoadMoreFooter = ({
+ isLoading,
+ loadMoreError,
+}: LoadMoreFooterParams): LoadMoreFooterState => {
+ if (isLoading) return 'loading';
+ if (loadMoreError) return 'error';
+ return undefined;
+};
+
+/**
+ * Whether reaching the end of the list may request the next page. A failed page
+ * waits for an explicit retry instead of re-firing on every scroll to the end.
+ */
+export const canAutoLoadMore = ({
+ hasMore,
+ loadMoreError,
+}: {
+ hasMore?: boolean;
+ loadMoreError?: unknown;
+}): boolean => Boolean(hasMore) && !loadMoreError;
+
+/**
+ * The end-of-list props of a paginated memory list's Virtuoso.
+ *
+ * Virtuoso only re-fires `endReached` when `[lastIndex, data]` changes. Without
+ * `data`, a page set collapsed back to its head page (after a delete) ends at
+ * the same index the head page already reported, so reaching the end again
+ * never requests the next page. Passing the rendered rows as `data` keys the
+ * trigger on the page set itself.
+ */
+export const autoLoadMoreProps = <T>({
+ hasMore,
+ items,
+ loadMoreError,
+ onLoadMore,
+}: {
+ hasMore?: boolean;
+ items: readonly T[];
+ loadMoreError?: unknown;
+ onLoadMore?: () => void;
+}): { data: readonly T[]; endReached?: () => void } => ({
+ data: items,
+ endReached: canAutoLoadMore({ hasMore, loadMoreError }) ? onLoadMore : undefined,
+});
diff --git a/src/routes/(main)/memory/identities/features/List/GridView/index.tsx b/src/routes/(main)/memory/identities/features/List/GridView/index.tsx
index 42a5382b3a0..97a33a4907f 100644
--- a/src/routes/(main)/memory/identities/features/List/GridView/index.tsx
+++ b/src/routes/(main)/memory/identities/features/List/GridView/index.tsx
@@ -1,7 +1,7 @@
import { type IdentityListItem } from '@lobechat/types';
import { memo } from 'react';
-import { useUserMemoryStore } from '@/store/userMemory';
+import { identitySelectors, useUserMemoryStore } from '@/store/userMemory';
import { GridView } from '../../../../features/GridView';
import IdentityCard from './IdentityCard';
@@ -14,13 +14,16 @@ interface GridViewProps {
const IdentityGridView = memo<GridViewProps>(({ identities, isLoading, onClick }) => {
const loadMoreIdentities = useUserMemoryStore((s) => s.loadMoreIdentities);
- const identitiesHasMore = useUserMemoryStore((s) => s.identitiesHasMore);
+ const identitiesHasMore = useUserMemoryStore(identitySelectors.identitiesHasMore);
+ const isLoadingMore = useUserMemoryStore(identitySelectors.identitiesIsLoadingMore);
+ const loadMoreError = useUserMemoryStore(identitySelectors.identitiesLoadMoreError);
return (
<GridView
hasMore={identitiesHasMore}
- isLoading={isLoading}
+ isLoading={isLoading || isLoadingMore}
items={identities}
+ loadMoreError={loadMoreError}
renderItem={(identity) => (
<IdentityCard identity={identity} onClick={() => onClick?.(identity)} />
)}
diff --git a/src/routes/(main)/memory/identities/features/List/TimelineView/index.tsx b/src/routes/(main)/memory/identities/features/List/TimelineView/index.tsx
index 6630457b93b..0003c34f0ae 100644
--- a/src/routes/(main)/memory/identities/features/List/TimelineView/index.tsx
+++ b/src/routes/(main)/memory/identities/features/List/TimelineView/index.tsx
@@ -1,7 +1,7 @@
import { type IdentityListItem } from '@lobechat/types';
import { memo } from 'react';
-import { useUserMemoryStore } from '@/store/userMemory';
+import { identitySelectors, useUserMemoryStore } from '@/store/userMemory';
import { TimelineView as GenericTimelineView } from '../../../../features/TimeLineView';
import { PeriodHeader, TimelineItemWrapper } from '../../../../features/TimeLineView/PeriodGroup';
@@ -15,14 +15,17 @@ interface TimelineViewProps {
const TimelineView = memo<TimelineViewProps>(({ identities, isLoading, onClick }) => {
const loadMoreIdentities = useUserMemoryStore((s) => s.loadMoreIdentities);
- const identitiesHasMore = useUserMemoryStore((s) => s.identitiesHasMore);
+ const identitiesHasMore = useUserMemoryStore(identitySelectors.identitiesHasMore);
+ const isLoadingMore = useUserMemoryStore(identitySelectors.identitiesIsLoadingMore);
+ const loadMoreError = useUserMemoryStore(identitySelectors.identitiesLoadMoreError);
return (
<GenericTimelineView
data={identities}
groupBy="month"
hasMore={identitiesHasMore}
- isLoading={isLoading}
+ isLoading={isLoading || isLoadingMore}
+ loadMoreError={loadMoreError}
renderHeader={(periodKey) => <PeriodHeader groupBy="month" periodKey={periodKey} />}
getDateForGrouping={(identity) =>
identity.episodicDate || identity.capturedAt || identity.createdAt
diff --git a/src/routes/(main)/memory/identities/identitiesListLoader.test.ts b/src/routes/(main)/memory/identities/identitiesListLoader.test.ts
new file mode 100644
index 00000000000..ff7fef786bd
--- /dev/null
+++ b/src/routes/(main)/memory/identities/identitiesListLoader.test.ts
@@ -0,0 +1,45 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const preHydrateIdentities = vi.hoisted(() => vi.fn(async () => true));
+
+vi.mock('@/store/userMemory', () => ({
+ getUserMemoryStoreState: () => ({ preHydrateIdentities }),
+}));
+
+const { identitiesListLoader } = await import('./identitiesListLoader');
+
+describe('identitiesListLoader', () => {
+ beforeEach(() => preHydrateIdentities.mockClear());
+
+ it('pre-hydrates the unfiltered head page for a plain visit', async () => {
+ await identitiesListLoader({ request: new Request('https://app.test/memory/identities') });
+
+ expect(preHydrateIdentities).toHaveBeenCalledWith({
+ pageSize: 12,
+ q: undefined,
+ types: undefined,
+ });
+ });
+
+ it('pre-hydrates the filtered query a cold load of a filtered URL asks for', async () => {
+ await identitiesListLoader({
+ request: new Request('https://app.test/memory/identities?q=mentor&type=professional'),
+ });
+
+ expect(preHydrateIdentities).toHaveBeenCalledWith({
+ pageSize: 12,
+ q: 'mentor',
+ types: ['professional'],
+ });
+ });
+
+ it('treats the `all` type tab as no type filter', async () => {
+ await identitiesListLoader({
+ request: new Request('https://app.test/memory/identities?type=all'),
+ });
+
+ expect(preHydrateIdentities).toHaveBeenCalledWith(
+ expect.objectContaining({ q: undefined, types: undefined }),
+ );
+ });
+});
diff --git a/src/routes/(main)/memory/identities/identitiesListLoader.ts b/src/routes/(main)/memory/identities/identitiesListLoader.ts
new file mode 100644
index 00000000000..7aa35f89318
--- /dev/null
+++ b/src/routes/(main)/memory/identities/identitiesListLoader.ts
@@ -0,0 +1,22 @@
+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';
+import { getUserMemoryStoreState } from '@/store/userMemory';
+
+import { identityListParamsOf } from './identityListParams';
+
+// Route loaders run before React commits the route: the only point where the
+// persisted identity list (an async read) can land before the page paints its
+// loading state. It hydrates the query the URL asks for β€” a different query's
+// row would fill the replica slot and block the page's own hydrate.
+export const identitiesListLoader = async ({
+ request,
+}: { request?: Request } = {}): Promise<null> => {
+ const search = request ? new URL(request.url).searchParams : undefined;
+ const params = identityListParamsOf(search?.get('q'), search?.get('type'));
+
+ await settleWithin(
+ getUserMemoryStoreState().preHydrateIdentities(params),
+ PRE_PAINT_HYDRATE_TIMEOUT,
+ );
+
+ return null;
+};
diff --git a/src/routes/(main)/memory/identities/identityListBoundary.test.ts b/src/routes/(main)/memory/identities/identityListBoundary.test.ts
new file mode 100644
index 00000000000..2bee4a29266
--- /dev/null
+++ b/src/routes/(main)/memory/identities/identityListBoundary.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { identityListBoundary } from './identityListBoundary';
+
+const failure = new Error('offline');
+
+describe('identityListBoundary', () => {
+ it('renders the rows of the query on screen', () => {
+ expect(identityListBoundary({ error: undefined, init: true, isStaleQuery: false })).toEqual({
+ error: undefined,
+ isResetting: false,
+ showRows: true,
+ });
+ });
+
+ it('hides the previous query’s rows while the new query resolves', () => {
+ expect(identityListBoundary({ error: undefined, init: true, isStaleQuery: true })).toEqual({
+ error: undefined,
+ isResetting: true,
+ showRows: false,
+ });
+ });
+
+ it('surfaces the failure instead of the previous query’s rows when the new query fails', () => {
+ const state = identityListBoundary({ error: failure, init: true, isStaleQuery: true });
+
+ expect(state.showRows).toBe(false);
+ expect(state.error).toBe(failure);
+ });
+
+ it('keeps the rows of the query on screen when only its revalidation fails', () => {
+ expect(identityListBoundary({ error: failure, init: true, isStaleQuery: false })).toEqual({
+ error: undefined,
+ isResetting: false,
+ showRows: true,
+ });
+ });
+
+ it('shows the failure of a first load', () => {
+ const state = identityListBoundary({ error: failure, init: false, isStaleQuery: true });
+
+ expect(state.error).toBe(failure);
+ expect(state.showRows).toBe(false);
+ });
+});
diff --git a/src/routes/(main)/memory/identities/identityListBoundary.ts b/src/routes/(main)/memory/identities/identityListBoundary.ts
new file mode 100644
index 00000000000..f9d66196aac
--- /dev/null
+++ b/src/routes/(main)/memory/identities/identityListBoundary.ts
@@ -0,0 +1,40 @@
+interface IdentityListBoundaryParams {
+ /** Error of the head request for the query now on screen. */
+ error: unknown;
+ /** `true` once any identity page has landed (survives a query change). */
+ init: boolean;
+ /** The painted rows were fetched for another search / type filter. */
+ isStaleQuery: boolean;
+}
+
+interface IdentityListBoundaryState {
+ /** Error to surface as the full-surface failure (with retry), if any. */
+ error: unknown;
+ /** Hide the rows behind the loading state while the new query resolves. */
+ isResetting: boolean;
+ /** The store rows answer the query on screen and may be rendered. */
+ showRows: boolean;
+}
+
+/**
+ * What the identities list boundary renders for the current query.
+ *
+ * The replica is the source of truth once it has painted *this* query, so a
+ * failed background revalidation keeps its rows. Rows painted for another
+ * query are never this query's answer: while the new head page is in flight
+ * they stay hidden behind the loading state, and when that request fails the
+ * failure (and its retry) is shown instead of the previous query's rows.
+ */
+export const identityListBoundary = ({
+ error,
+ init,
+ isStaleQuery,
+}: IdentityListBoundaryParams): IdentityListBoundaryState => {
+ const failed = Boolean(error);
+
+ return {
+ error: failed && (!init || isStaleQuery) ? error : undefined,
+ isResetting: isStaleQuery && !failed,
+ showRows: init && !isStaleQuery,
+ };
+};
diff --git a/src/routes/(main)/memory/identities/identityListParams.ts b/src/routes/(main)/memory/identities/identityListParams.ts
new file mode 100644
index 00000000000..2bd8a3e740f
--- /dev/null
+++ b/src/routes/(main)/memory/identities/identityListParams.ts
@@ -0,0 +1,18 @@
+import {
+ DEFAULT_IDENTITY_LIST_PAGE_SIZE,
+ type IdentityListParams,
+} from '@/store/userMemory/slices/identity/projection';
+
+/**
+ * Head-page params of the identities list for the page's `q` / `type` URL
+ * params. The route and its pre-paint loader both build them here, so the
+ * loader hydrates exactly the persisted query the page then syncs.
+ */
+export const identityListParamsOf = (
+ q: string | null | undefined,
+ type: string | null | undefined,
+): IdentityListParams => ({
+ pageSize: DEFAULT_IDENTITY_LIST_PAGE_SIZE,
+ q: q || undefined,
+ types: !type || type === 'all' ? undefined : [type],
+});
diff --git a/src/routes/(main)/memory/identities/index.tsx b/src/routes/(main)/memory/identities/index.tsx
index 97b10b40ef9..9c265c979f9 100644
--- a/src/routes/(main)/memory/identities/index.tsx
+++ b/src/routes/(main)/memory/identities/index.tsx
@@ -2,7 +2,7 @@ import { Flexbox, Icon } from '@lobehub/ui';
import { Tag } from '@lobehub/ui/base-ui';
import { BrainCircuitIcon } from 'lucide-react';
import { type FC } from 'react';
-import { memo, useCallback, useEffect, useState } from 'react';
+import { memo, useCallback, useState } from 'react';
import { MemoryListBoundary } from '@/features/Memory';
import NavHeader from '@/features/NavHeader';
@@ -11,8 +11,8 @@ import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
import { useQueryState } from '@/hooks/useQueryParam';
import ActionBar from '@/routes/(main)/memory/features/ActionBar';
import CommonFilterBar from '@/routes/(main)/memory/features/FilterBar';
-import { useUserMemoryStore } from '@/store/userMemory';
-import { type TypesEnum } from '@/types/userMemory';
+import { identitySelectors, useUserMemoryStore } from '@/store/userMemory';
+import { isIdentityQueryCurrent } from '@/store/userMemory/slices/identity/projection';
import EditableModal from '../features/EditableModal';
import Loading from '../features/Loading';
@@ -23,6 +23,8 @@ import IdentityRightPanel from './features/IdentityRightPanel';
import { type IdentityType } from './features/List';
import List from './features/List';
import SegmentedBar from './features/SegmentedBar';
+import { identityListBoundary } from './identityListBoundary';
+import { identityListParamsOf } from './identityListParams';
import { showIdentityControls } from './showIdentityControls';
const IdentitiesArea = memo(() => {
@@ -33,26 +35,26 @@ const IdentitiesArea = memo(() => {
const searchValue = searchValueRaw || '';
const typeFilter = (typeFilterRaw as IdentityType) || 'all';
- const identitiesPage = useUserMemoryStore((s) => s.identitiesPage);
- const identitiesInit = useUserMemoryStore((s) => s.identitiesInit);
- const identitiesTotal = useUserMemoryStore((s) => s.identitiesTotal);
- const identitiesSearchLoading = useUserMemoryStore((s) => s.identitiesSearchLoading);
+ const identities = useUserMemoryStore((s) => s.identities);
+ const identitiesMeta = useUserMemoryStore((s) => s.identitiesMeta);
+ const identitiesInit = useUserMemoryStore(identitySelectors.isIdentitiesInitialized);
+ const identitiesTotal = useUserMemoryStore(identitySelectors.identitiesTotal);
const useFetchIdentities = useUserMemoryStore((s) => s.useFetchIdentities);
- const resetIdentitiesList = useUserMemoryStore((s) => s.resetIdentitiesList);
- // Reset list when search or type filter changes
- useEffect(() => {
- const types = typeFilter === 'all' ? undefined : [typeFilter as TypesEnum];
- resetIdentitiesList({ q: searchValue || undefined, types });
- }, [searchValue, typeFilter]);
+ // Same params the route loader pre-hydrated, so its row is this query's.
+ const requestedQuery = identityListParamsOf(searchValue, typeFilter);
- // Call SWR hook to fetch data
- const { data, error, isLoading, mutate } = useFetchIdentities({
- page: identitiesPage,
- pageSize: 12,
- q: searchValue || undefined,
- types: typeFilter === 'all' ? undefined : [typeFilter as TypesEnum],
- });
+ // Hydrate the persisted head page, then revalidate. The rows land in
+ // `identities` β€” read them from the store, never from this hook.
+ const { error, isValidating, revalidate } = useFetchIdentities(requestedQuery);
+
+ // A page painted for another filter set is not the answer on screen yet: the
+ // replica keeps the previous query's rows until the new head page lands, so
+ // the boundary must not read them as this query's (empty) result.
+ const isStaleQuery = !isIdentityQueryCurrent(identitiesMeta, requestedQuery);
+ // A failed revalidation of the painted query keeps its rows; a failed new
+ // query surfaces the failure instead of the previous query's rows.
+ const boundary = identityListBoundary({ error, init: identitiesInit, isStaleQuery });
// Handle search and type changes
const handleSearch = useCallback(
@@ -74,7 +76,7 @@ const IdentitiesArea = memo(() => {
const showControls = showIdentityControls({
hasFilters: Boolean(searchValue) || typeFilter !== 'all',
init: identitiesInit,
- searchLoading: identitiesSearchLoading,
+ searchLoading: isStaleQuery,
total: identitiesTotal,
});
@@ -109,15 +111,15 @@ const IdentitiesArea = memo(() => {
</Flexbox>
)}
<MemoryListBoundary
- data={data}
- error={error}
+ data={boundary.showRows ? identities : undefined}
+ error={boundary.error}
isInitialized={identitiesInit}
- isLoading={isLoading}
- isResetting={identitiesSearchLoading}
+ isLoading={isValidating}
+ isResetting={boundary.isResetting}
loading={<Loading viewMode={viewMode} />}
- onRetry={() => void mutate()}
+ onRetry={() => void revalidate()}
>
- <List isLoading={isLoading} searchValue={searchValue} viewMode={viewMode} />
+ <List isLoading={isValidating} searchValue={searchValue} viewMode={viewMode} />
</MemoryListBoundary>
</WideScreenContainer>
</Flexbox>
diff --git a/src/routes/(main)/memory/preferences/features/List/GridView/index.tsx b/src/routes/(main)/memory/preferences/features/List/GridView/index.tsx
index 8c3fda34e0f..be126a59af7 100644
--- a/src/routes/(main)/memory/preferences/features/List/GridView/index.tsx
+++ b/src/routes/(main)/memory/preferences/features/List/GridView/index.tsx
@@ -15,12 +15,16 @@ interface GridViewProps {
const PreferenceGridView = memo<GridViewProps>(({ preferences, isLoading, onClick }) => {
const loadMorePreferences = useUserMemoryStore((s) => s.loadMorePreferences);
const preferencesHasMore = useUserMemoryStore((s) => s.preferencesHasMore);
+ // Load-more progress / failure of the query on screen (footer + retry).
+ const isLoadingMore = useUserMemoryStore((s) => Boolean(s.preferenceListData?.isLoadingMore));
+ const loadMoreError = useUserMemoryStore((s) => s.preferenceListData?.loadMoreError);
return (
<GridView
hasMore={preferencesHasMore}
- isLoading={isLoading}
+ isLoading={isLoading || isLoadingMore}
items={preferences}
+ loadMoreError={loadMoreError}
renderItem={(preference) => (
<PreferenceCard preference={preference} onClick={() => onClick(preference)} />
)}
diff --git a/src/routes/(main)/memory/preferences/features/List/TimelineView/index.tsx b/src/routes/(main)/memory/preferences/features/List/TimelineView/index.tsx
index a705c0e5c80..dac753f3e10 100644
--- a/src/routes/(main)/memory/preferences/features/List/TimelineView/index.tsx
+++ b/src/routes/(main)/memory/preferences/features/List/TimelineView/index.tsx
@@ -19,13 +19,17 @@ const PreferenceTimelineView = memo<PreferenceTimelineViewProps>(
({ preferences, isLoading, onClick }) => {
const loadMorePreferences = useUserMemoryStore((s) => s.loadMorePreferences);
const preferencesHasMore = useUserMemoryStore((s) => s.preferencesHasMore);
+ // Load-more progress / failure of the query on screen (footer + retry).
+ const isLoadingMore = useUserMemoryStore((s) => Boolean(s.preferenceListData?.isLoadingMore));
+ const loadMoreError = useUserMemoryStore((s) => s.preferenceListData?.loadMoreError);
return (
<GenericTimelineView
data={preferences}
groupBy="day"
hasMore={preferencesHasMore}
- isLoading={isLoading}
+ isLoading={isLoading || isLoadingMore}
+ loadMoreError={loadMoreError}
renderHeader={(periodKey) => <PeriodHeader groupBy="day" periodKey={periodKey} />}
renderItem={(preference) => (
<TimelineItemWrapper>
diff --git a/src/routes/(main)/memory/preferences/index.tsx b/src/routes/(main)/memory/preferences/index.tsx
index daa2b61ca46..15890ac3e36 100644
--- a/src/routes/(main)/memory/preferences/index.tsx
+++ b/src/routes/(main)/memory/preferences/index.tsx
@@ -5,7 +5,7 @@ import { type FC } from 'react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { MemoryListBoundary, useResetMemoryList } from '@/features/Memory';
+import { MemoryListBoundary } from '@/features/Memory';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
@@ -35,10 +35,7 @@ const PreferencesArea = memo(() => {
const preferencesPage = useUserMemoryStore((s) => s.preferencesPage);
const preferencesInit = useUserMemoryStore((s) => s.preferencesInit);
const preferencesTotal = useUserMemoryStore((s) => s.preferencesTotal);
- const preferencesSearchError = useUserMemoryStore((s) => s.preferencesSearchError);
- const preferencesSearchLoading = useUserMemoryStore((s) => s.preferencesSearchLoading);
const useFetchPreferences = useUserMemoryStore((s) => s.useFetchPreferences);
- const resetPreferencesList = useUserMemoryStore((s) => s.resetPreferencesList);
const sortOptions = [
{ label: t('filter.sort.createdAt'), value: 'capturedAt' },
@@ -48,15 +45,10 @@ const PreferencesArea = memo(() => {
// Convert sort: capturedAt becomes undefined (backend default)
const apiSort = sortValue === 'capturedAt' ? undefined : (sortValue as 'scorePriority');
- useResetMemoryList({
- query: searchValue,
- resetList: resetPreferencesList,
- sort: apiSort,
- viewMode,
- });
-
- // Call SWR hook to fetch data
- const { data, isLoading, mutate } = useFetchPreferences({
+ // Each search / sort is its own replica entry: the hook selects it before
+ // paint, so the previous query's rows never show under this one. `error` is
+ // this query's failure while it has nothing painted.
+ const { data, error, isLoading, mutate } = useFetchPreferences({
page: preferencesPage,
pageSize: 12,
q: searchValue || undefined,
@@ -109,10 +101,9 @@ const PreferencesArea = memo(() => {
/>
<MemoryListBoundary
data={data}
- error={preferencesSearchError}
+ error={error}
isInitialized={preferencesInit}
isLoading={isLoading}
- isResetting={preferencesSearchLoading}
loading={<Loading viewMode={viewMode} />}
onRetry={() => void mutate()}
>
diff --git a/src/routes/(main)/memory/preferences/preferencesLoader.test.ts b/src/routes/(main)/memory/preferences/preferencesLoader.test.ts
new file mode 100644
index 00000000000..c873031499d
--- /dev/null
+++ b/src/routes/(main)/memory/preferences/preferencesLoader.test.ts
@@ -0,0 +1,35 @@
+// @vitest-environment happy-dom
+import type { LoaderFunctionArgs } from 'react-router';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { preferenceListLoader } from './preferencesLoader';
+
+const argsOf = (url: string) => ({ request: new Request(url) }) as LoaderFunctionArgs;
+
+describe('preferenceListLoader', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it('pre-hydrates the query the route URL encodes', async () => {
+ const preHydrate = vi
+ .spyOn(useUserMemoryStore.getState(), 'preHydratePreferences')
+ .mockResolvedValue(true);
+
+ await expect(
+ preferenceListLoader(argsOf('https://app.lobehub.com/memory/preferences?q=foo')),
+ ).resolves.toBeNull();
+
+ expect(preHydrate).toHaveBeenCalledWith({ q: 'foo' });
+ });
+
+ it('pre-hydrates the unfiltered query for a bare URL', async () => {
+ const preHydrate = vi
+ .spyOn(useUserMemoryStore.getState(), 'preHydratePreferences')
+ .mockResolvedValue(true);
+
+ await preferenceListLoader(argsOf('https://app.lobehub.com/memory/preferences'));
+
+ expect(preHydrate).toHaveBeenCalledWith({ q: undefined });
+ });
+});
diff --git a/src/routes/(main)/memory/preferences/preferencesLoader.ts b/src/routes/(main)/memory/preferences/preferencesLoader.ts
new file mode 100644
index 00000000000..b1db3b7bf96
--- /dev/null
+++ b/src/routes/(main)/memory/preferences/preferencesLoader.ts
@@ -0,0 +1,28 @@
+import type { LoaderFunctionArgs } from 'react-router';
+
+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+/**
+ * Seed the persisted preference page set for the query the route URL encodes.
+ *
+ * Route loaders run before React commits the route: the only point where the
+ * persisted list (an async read) can land before the page paints its loading
+ * skeleton. Without the URL's `q`, a bookmarked `/memory/preferences?q=foo`
+ * would wait on the unfiltered entry and still mount into a skeleton.
+ *
+ * Only `q` is taken from the URL: the page's first paint is the timeline query,
+ * whose `sort` is undefined (the sort control only exists in grid mode, which is
+ * not part of the URL). Hydrating the URL's `sort` would key a different entry
+ * and miss the one the page requests first.
+ */
+export const preferenceListLoader = async ({ request }: LoaderFunctionArgs): Promise<null> => {
+ const q = new URL(request.url).searchParams.get('q') || undefined;
+
+ await settleWithin(
+ useUserMemoryStore.getState().preHydratePreferences({ q }),
+ PRE_PAINT_HYDRATE_TIMEOUT,
+ );
+
+ return null;
+};
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index b24f3ab4a1f..f2d28ef2805 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -77,7 +77,9 @@ import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShel
import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';
import { channelDataLoader } from '@/spa/router/channelDataLoader';
+import { identitiesListLoader } from '@/spa/router/identitiesListLoader';
import { pageListLoader } from '@/spa/router/pageListLoader';
+import { preferenceListLoader } from '@/spa/router/preferenceListLoader';
import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';
import { SettingsTabs } from '@/store/global/initialState';
import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
@@ -764,6 +766,9 @@ export const sharedMainAreaChildren: RouteObject[] = [
handle: {
meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),
},
+ // Seed the persisted identity list before the page paints, so a cold
+ // start shows the local copy instead of a loading state.
+ loader: identitiesListLoader,
path: 'identities',
},
{
@@ -784,6 +789,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
handle: {
meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),
},
+ loader: preferenceListLoader,
path: 'preferences',
},
{
diff --git a/src/spa/router/identitiesListLoader.ts b/src/spa/router/identitiesListLoader.ts
new file mode 100644
index 00000000000..7b94bfa649b
--- /dev/null
+++ b/src/spa/router/identitiesListLoader.ts
@@ -0,0 +1,7 @@
+// The route tables sit in the entry chunk's static graph; resolving the real
+// loader on first use keeps the userMemory store in the identities route's lazy
+// chunks.
+export const identitiesListLoader = (args?: { request?: Request }) =>
+ import('@/routes/(main)/memory/identities/identitiesListLoader').then((module) =>
+ module.identitiesListLoader(args),
+ );
diff --git a/src/spa/router/identitiesListLoader.wiring.test.ts b/src/spa/router/identitiesListLoader.wiring.test.ts
new file mode 100644
index 00000000000..8ae651d3f21
--- /dev/null
+++ b/src/spa/router/identitiesListLoader.wiring.test.ts
@@ -0,0 +1,40 @@
+// @vitest-environment happy-dom
+import type { RouteObject } from 'react-router';
+import { describe, expect, it, vi } from 'vitest';
+
+import { desktopRoutes } from './desktopRouter.config';
+import { identitiesListLoader } from './identitiesListLoader';
+
+const loaderModule = vi.hoisted(() => ({ evaluated: false }));
+
+// Evaluating the real loader means the userMemory store reached the entry
+// chunk's first-screen graph.
+vi.mock('@/routes/(main)/memory/identities/identitiesListLoader', () => {
+ loaderModule.evaluated = true;
+ return { identitiesListLoader: vi.fn(async () => null) };
+});
+
+const flatten = (routes: RouteObject[]): RouteObject[] =>
+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);
+
+describe('identities list loader wiring', () => {
+ it('does not load the store-backed loader while the route tables load', () => {
+ expect(loaderModule.evaluated).toBe(false);
+ });
+
+ it('pre-hydrates the identity list on the desktop identities route', () => {
+ const routes = flatten(desktopRoutes).filter((r) => r.path === 'identities');
+
+ expect(routes.length).toBeGreaterThan(0);
+
+ expect(routes.map((r) => r.loader)).toEqual(routes.map(() => identitiesListLoader));
+ });
+
+ it('delegates to the real loader on first use', async () => {
+ const { identitiesListLoader: realLoader } =
+ await import('@/routes/(main)/memory/identities/identitiesListLoader');
+
+ await expect(identitiesListLoader()).resolves.toBeNull();
+ expect(realLoader).toHaveBeenCalled();
+ });
+});
diff --git a/src/spa/router/preferenceListLoader.ts b/src/spa/router/preferenceListLoader.ts
new file mode 100644
index 00000000000..f36261e8ab5
--- /dev/null
+++ b/src/spa/router/preferenceListLoader.ts
@@ -0,0 +1,10 @@
+import type { LoaderFunctionArgs } from 'react-router';
+
+// The route tables sit in the entry chunk's static graph; resolving the real
+// loader on first use keeps the userMemory store in the preferences route's
+// lazy chunks. The loader arguments carry the request, so the pre-hydrate can
+// target the query the URL encodes.
+export const preferenceListLoader = (args: LoaderFunctionArgs) =>
+ import('@/routes/(main)/memory/preferences/preferencesLoader').then((module) =>
+ module.preferenceListLoader(args),
+ );
diff --git a/src/spa/router/preferenceListLoader.wiring.test.ts b/src/spa/router/preferenceListLoader.wiring.test.ts
new file mode 100644
index 00000000000..0c6ec74360e
--- /dev/null
+++ b/src/spa/router/preferenceListLoader.wiring.test.ts
@@ -0,0 +1,44 @@
+// @vitest-environment happy-dom
+import type { LoaderFunctionArgs, RouteObject } from 'react-router';
+import { describe, expect, it, vi } from 'vitest';
+
+import { desktopRoutes } from './desktopRouter.config';
+import { preferenceListLoader } from './preferenceListLoader';
+
+const loaderModule = vi.hoisted(() => ({ evaluated: false }));
+
+// Evaluating the real loader means the userMemory store reached the entry
+// chunk's first-screen graph.
+vi.mock('@/routes/(main)/memory/preferences/preferencesLoader', () => {
+ loaderModule.evaluated = true;
+ return { preferenceListLoader: vi.fn(async () => null) };
+});
+
+const flatten = (routes: RouteObject[]): RouteObject[] =>
+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);
+
+describe('preference list loader wiring', () => {
+ it('does not load the store-backed loader while the route tables load', () => {
+ expect(loaderModule.evaluated).toBe(false);
+ });
+
+ it('pre-hydrates the preference list on the desktop preferences route', () => {
+ const routes = flatten(desktopRoutes).filter((r) => r.path === 'preferences');
+
+ expect(routes.length).toBeGreaterThan(0);
+
+ expect(routes.map((r) => r.loader)).toEqual(routes.map(() => preferenceListLoader));
+ });
+
+ it('delegates to the real loader on first use', async () => {
+ const { preferenceListLoader: realLoader } =
+ await import('@/routes/(main)/memory/preferences/preferencesLoader');
+
+ const args = {
+ request: new Request('https://app.lobehub.com/memory/preferences?q=foo'),
+ } as LoaderFunctionArgs;
+
+ await expect(preferenceListLoader(args)).resolves.toBeNull();
+ expect(realLoader).toHaveBeenCalledWith(args);
+ });
+});
diff --git a/src/store/chat/slices/topic/topicListCache.integration.test.ts b/src/store/chat/slices/topic/topicListCache.integration.test.ts
index 2270608d7d4..77f88071d5f 100644
--- a/src/store/chat/slices/topic/topicListCache.integration.test.ts
+++ b/src/store/chat/slices/topic/topicListCache.integration.test.ts
@@ -206,7 +206,7 @@ describe('persisted topic list across a reload', () => {
await act(async () => {
await session1.result.current.revalidate();
});
- await waitFor(() => expect(persistSpy).toHaveBeenCalled());
+ // The pinned value equals the stored row, so the engine may skip the write.
await Promise.all(persistSpy.mock.results.map(({ value }) => value));
expect(await persistedTopicStatus(scope)).toBe('active');
session1.unmount();
diff --git a/src/store/userMemory/initialState.ts b/src/store/userMemory/initialState.ts
index a24febe4880..cbe2458fb0c 100644
--- a/src/store/userMemory/initialState.ts
+++ b/src/store/userMemory/initialState.ts
@@ -2,24 +2,22 @@ import { type RetrieveMemoryParams, type RetrieveMemoryResult } from '@lobechat/
import { createReplicaState, type ReplicaState } from '@/libs/replica';
-import { type ActivitySliceState } from './slices/activity';
-import { activityInitialState } from './slices/activity';
+import { type ActivitySliceState } from './slices/activity/initialState';
+import { activityInitialState } from './slices/activity/initialState';
import { type AgentMemorySliceState } from './slices/agent';
import { agentMemoryInitialState } from './slices/agent';
import { type MemoryDetailDisplay } from './slices/base/projection';
-import { type ContextSliceState } from './slices/context';
-import { contextInitialState } from './slices/context';
-import { type ExperienceSliceState } from './slices/experience';
-import { experienceInitialState } from './slices/experience';
+import { type ContextSliceState } from './slices/context/initialState';
+import { contextInitialState } from './slices/context/initialState';
+import { type ExperienceSliceState } from './slices/experience/initialState';
+import { experienceInitialState } from './slices/experience/initialState';
+import { homeInitialState, type HomeSliceState } from './slices/home/initialState';
import { type IdentitySliceState } from './slices/identity';
import { identityInitialState } from './slices/identity';
-import { type PreferenceSliceState } from './slices/preference';
-import { preferenceInitialState } from './slices/preference';
+import { type PreferenceSliceState } from './slices/preference/initialState';
+import { preferenceInitialState } from './slices/preference/initialState';
-export interface PersonaData {
- content: string;
- summary: string;
-}
+export type { PersonaData } from './slices/home/projection';
export interface UserMemoryStoreState
extends
@@ -27,6 +25,7 @@ export interface UserMemoryStoreState
AgentMemorySliceState,
ContextSliceState,
ExperienceSliceState,
+ HomeSliceState,
IdentitySliceState,
PreferenceSliceState {
activeParams?: RetrieveMemoryParams;
@@ -45,11 +44,6 @@ export interface UserMemoryStoreState
memoryMap: Record<string, RetrieveMemoryResult>;
/** Local-first bookkeeping for the retrieve result map (`memoryMap`). */
memoryRetrieveReplica: ReplicaState<RetrieveMemoryResult>;
- persona?: PersonaData;
- personaInit: boolean;
- roles: { count: number; tag: string }[];
- tags: { count: number; tag: string }[];
- tagsInit: boolean;
}
export const initialState: UserMemoryStoreState = {
@@ -57,6 +51,7 @@ export const initialState: UserMemoryStoreState = {
...agentMemoryInitialState,
...contextInitialState,
...experienceInitialState,
+ ...homeInitialState,
...identityInitialState,
...preferenceInitialState,
activeParams: undefined,
@@ -69,9 +64,4 @@ export const initialState: UserMemoryStoreState = {
memoryFetchedAtMap: {},
memoryMap: {},
memoryRetrieveReplica: createReplicaState<RetrieveMemoryResult>(),
- persona: undefined,
- personaInit: false,
- roles: [],
- tags: [],
- tagsInit: false,
};
diff --git a/src/store/userMemory/slices/activity/action.ts b/src/store/userMemory/slices/activity/action.ts
index 239ea4c8b5c..595fd1bc52a 100644
--- a/src/store/userMemory/slices/activity/action.ts
+++ b/src/store/userMemory/slices/activity/action.ts
@@ -1,186 +1,130 @@
-import { type ActivityListResult } from '@lobechat/types';
-import { uniqBy } from 'es-toolkit/compat';
-import { produce } from 'immer';
-import { useEffect } from 'react';
+import { type ActivityListItem } from '@lobechat/types';
import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
import { userMemoryKeys } from '@/libs/swr/keys';
import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
-import { type UserMemoryStore } from '../../store';
-import { isMemoryListRequestCurrent } from '../utils/isMemoryListRequestCurrent';
-import { shouldSurfaceMemoryListError } from '../utils/shouldSurfaceMemoryListError';
+import { type UserMemoryStore, useUserMemoryStore } from '../../store';
+import { type MemoryListPageResult, MemoryQueryList } from '../utils/memoryQueryList';
+import {
+ ACTIVITY_LIST_PAGE_SIZE,
+ type ActivityListData,
+ type ActivityListParams,
+ activityListResource,
+} from './projection';
const n = setNamespace('userMemory/activity');
-export interface ActivityQueryParams {
+export interface ActivityQueryParams extends Partial<ActivityListParams> {
page?: number;
- pageSize?: number;
- q?: string;
- sort?: 'capturedAt' | 'startsAt';
- status?: string[];
- types?: string[];
}
-type ActivityListRequest = ActivityQueryParams & { page: number };
+/** Flat mirrors of one page set (`undefined` = the active query has no view yet). */
+const mirrorsOf = (data: ActivityListData | undefined): Partial<UserMemoryStore> =>
+ data
+ ? {
+ activityListData: data,
+ activities: data.items,
+ activitiesHasMore: data.hasMore,
+ activitiesInit: true,
+ activitiesPage: data.currentPage + 1,
+ activitiesTotal: data.total ?? data.items.length,
+ }
+ : {
+ activityListData: undefined,
+ activities: [],
+ activitiesHasMore: true,
+ activitiesInit: false,
+ activitiesPage: 1,
+ activitiesTotal: 0,
+ };
type Setter = StoreSetter<UserMemoryStore>;
export const createActivitySlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
new ActivityActionImpl(set, get, _api);
+/**
+ * The user-memory activity list: one `MemoryQueryList` (shared with the other
+ * offset-paged memory lists) behind the slice's long-standing action names.
+ */
export class ActivityActionImpl {
- readonly #get: () => UserMemoryStore;
- readonly #set: Setter;
+ readonly #list: MemoryQueryList<ActivityListParams, ActivityListItem, ActivityListData>;
constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
void _api;
- this.#set = set;
- this.#get = get;
+ this.#list = new MemoryQueryList({
+ actionPrefix: n('activityList'),
+ activeKeyField: 'activityListKey',
+ entriesField: 'activityListEntries',
+ fetchPage: async (params, page) => {
+ const response = await userMemoryService.queryActivities({
+ page,
+ pageSize: params.pageSize,
+ q: params.q,
+ sort: params.sort,
+ status: params.status,
+ types: params.types,
+ });
+ return { items: response.items, total: response.total };
+ },
+ get,
+ mirror: mirrorsOf,
+ queryFields: ({ q, sort }) => ({ activitiesQuery: q || undefined, activitiesSort: sort }),
+ replicaField: 'activityListReplica',
+ resource: activityListResource,
+ rootKey: userMemoryKeys.activities.root,
+ set,
+ useStore: (selector) => useUserMemoryStore(selector),
+ });
}
- deleteActivity = async (id: string): Promise<void> => {
- await memoryCRUDService.deleteActivity(id);
- this.#get().resetActivitiesList({
- q: this.#get().activitiesQuery,
- sort: this.#get().activitiesSort,
- });
- };
+ /** Delete one activity: optimistic, then the offset repair (see `OffsetListPager`). */
+ deleteActivity = (id: string): Promise<void> =>
+ this.#list.delete(id, () => memoryCRUDService.deleteActivity(id));
- loadMoreActivities = (): void => {
- const { activitiesPage, activitiesTotal, activities } = this.#get();
- if (activities.length < (activitiesTotal || 0)) {
- this.#set(
- produce((draft) => {
- draft.activitiesPage = activitiesPage + 1;
- }),
- false,
- n('loadMoreActivities'),
- );
- }
- };
+ /** Purge for "delete all memories" (every query, memory + IndexedDB). */
+ internal_clearActivityList = (user?: string): Promise<boolean> => this.#list.clear(user);
- internal_acceptActivitiesList = (
- data: ActivityListResult,
- request: ActivityListRequest,
+ /** Confirmed edit of one activity in every loaded and persisted query. */
+ internal_updateActivityEntity = (
+ id: string,
+ fn: (item: ActivityListItem) => ActivityListItem,
): void => {
- const state = this.#get();
- if (
- !isMemoryListRequestCurrent(
- {
- page: state.activitiesPage,
- q: state.activitiesQuery,
- sort: state.activitiesSort,
- },
- { page: request.page, q: request.q, sort: request.sort },
- )
- )
- return;
-
- this.#set(
- produce((draft) => {
- draft.activitiesSearchError = undefined;
- draft.activitiesSearchLoading = false;
- draft.activitiesTotal = data.total;
-
- if (!draft.activitiesInit) {
- draft.activitiesInit = true;
- }
-
- if (request.page === 1) {
- draft.activities = uniqBy(data.items, 'id');
- } else {
- draft.activities = uniqBy([...draft.activities, ...data.items], 'id');
- }
-
- draft.activitiesHasMore = data.items.length >= (request.pageSize || 20);
- }),
- false,
- n('internal_acceptActivitiesList'),
- );
+ this.#list.updateEntity(id, fn);
};
- internal_failActivitiesList = (error: unknown, request: ActivityListRequest): void => {
- const state = this.#get();
- if (
- !isMemoryListRequestCurrent(
- {
- page: state.activitiesPage,
- q: state.activitiesQuery,
- sort: state.activitiesSort,
- },
- { page: request.page, q: request.q, sort: request.sort },
- )
- )
- return;
-
- const shouldSurfaceError = shouldSurfaceMemoryListError({
- initialized: state.activitiesInit,
- page: request.page,
- resetting: state.activitiesSearchLoading,
- });
-
- this.#set(
- produce((draft) => {
- if (shouldSurfaceError) draft.activitiesSearchError = error;
- draft.activitiesSearchLoading = false;
- }),
- false,
- n('internal_failActivitiesList'),
- );
+ /** Append the next page of the query on screen. */
+ loadMoreActivities = (): void => {
+ void this.#list.loadMore();
};
+ /** Seed the persisted head page of a query before its route paints. */
+ preHydrateActivities = (
+ query?: Omit<ActivityQueryParams, 'page' | 'pageSize'>,
+ ): Promise<boolean> =>
+ this.#list.preHydrate({
+ ...query,
+ pageSize: ACTIVITY_LIST_PAGE_SIZE,
+ q: query?.q || undefined,
+ });
+
+ /** Point the list at another search / sort (no page set is dropped). */
resetActivitiesList = (params?: Omit<ActivityQueryParams, 'page' | 'pageSize'>): void => {
- this.#set(
- produce((draft) => {
- draft.activities = [];
- draft.activitiesPage = 1;
- draft.activitiesQuery = params?.q;
- draft.activitiesSearchError = undefined;
- draft.activitiesSearchLoading = true;
- draft.activitiesSort = params?.sort;
- }),
- false,
- n('resetActivitiesList'),
- );
+ this.#list.select({ ...params, q: params?.q || undefined });
};
- /**
- * Hydrate the store from SWR's rendered state because deduped cache hits do not invoke SWR's
- * request lifecycle callbacks.
- */
- useFetchActivities = (params: ActivityQueryParams): SWRResponse<ActivityListResult> => {
- const page = params.page ?? 1;
- const response = useSWR(
- userMemoryKeys.activities(params),
- async () => {
- return userMemoryService.queryActivities({
- page: params.page,
- pageSize: params.pageSize,
- q: params.q,
- sort: params.sort,
- status: params.status,
- types: params.types,
- });
- },
- {
- revalidateOnFocus: false,
- },
- );
-
- useEffect(() => {
- if (response.data !== undefined)
- this.internal_acceptActivitiesList(response.data, { ...params, page });
- }, [page, params.pageSize, params.q, params.sort, response.data]);
-
- useEffect(() => {
- if (response.error !== undefined)
- this.internal_failActivitiesList(response.error, { ...params, page });
- }, [page, params.pageSize, params.q, params.sort, response.error]);
-
- return response;
+ /** Fetch orchestration for the activity list page (see `MemoryQueryList.useFetch`). */
+ useFetchActivities = (
+ params: ActivityQueryParams,
+ ): SWRResponse<MemoryListPageResult<ActivityListItem>> => {
+ const { page: _page, ...query } = params;
+ return this.#list.useFetch({
+ ...query,
+ pageSize: params.pageSize ?? ACTIVITY_LIST_PAGE_SIZE,
+ q: params.q || undefined,
+ });
};
}
diff --git a/src/store/userMemory/slices/activity/index.ts b/src/store/userMemory/slices/activity/index.ts
index 787b5379044..58620335bea 100644
--- a/src/store/userMemory/slices/activity/index.ts
+++ b/src/store/userMemory/slices/activity/index.ts
@@ -1,2 +1,3 @@
export { type ActivityAction, createActivitySlice } from './action';
export { activityInitialState, type ActivitySliceState } from './initialState';
+export type { ActivityListData, ActivityListParams, ActivityListSort } from './projection';
diff --git a/src/store/userMemory/slices/activity/initialState.ts b/src/store/userMemory/slices/activity/initialState.ts
index b3978289f2f..c308560a91e 100644
--- a/src/store/userMemory/slices/activity/initialState.ts
+++ b/src/store/userMemory/slices/activity/initialState.ts
@@ -1,15 +1,38 @@
import { type ActivityListItem } from '@lobechat/types';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import { memoryListKey } from '../../utils/replica';
+import { type ActivityListData, type ActivityListSort } from './projection';
+
+/**
+ * The activity list is a `@lobechat/replica` paged resource with one page set
+ * per search / sort (`activityListEntries`). The long-standing flat fields
+ * (`activityListData`, `activities`, `activitiesTotal`, `activitiesPage`,
+ * `activitiesHasMore`, `activitiesInit`) mirror the active query's entry so every
+ * existing consumer keeps reading the place it always has.
+ */
export interface ActivitySliceState {
+ /** Rows of the active page set. Mirror of `activityListData.items`. */
activities: ActivityListItem[];
+ /** Mirror of `activityListData.hasMore`. */
activitiesHasMore: boolean;
+ /** Whether the active query has a view (persisted row hydrated or a page landed). */
activitiesInit: boolean;
+ /** Mirror of `activityListData.currentPage + 1`. */
activitiesPage: number;
activitiesQuery?: string;
- activitiesSearchError?: unknown;
- activitiesSearchLoading?: boolean;
- activitiesSort?: 'capturedAt' | 'startsAt';
+ activitiesSort?: ActivityListSort;
+ /** Mirror of `activityListData.total`. */
activitiesTotal: number;
+ /** View of the active query's page set. Mirror of `activityListEntries[activityListKey]`. */
+ activityListData?: ActivityListData;
+ /** Canonical replica views, one page set per query. Engine-owned. */
+ activityListEntries: Record<string, ActivityListData>;
+ /** Entry key of the query on screen (see `memoryListKey`). */
+ activityListKey: string;
+ /** Local-first bookkeeping for `activityListEntries`. */
+ activityListReplica: ReplicaState<ActivityListData>;
}
export const activityInitialState: ActivitySliceState = {
@@ -18,8 +41,10 @@ export const activityInitialState: ActivitySliceState = {
activitiesInit: false,
activitiesPage: 1,
activitiesQuery: undefined,
- activitiesSearchError: undefined,
- activitiesSearchLoading: undefined,
activitiesSort: undefined,
activitiesTotal: 0,
+ activityListData: undefined,
+ activityListEntries: {},
+ activityListKey: memoryListKey({}),
+ activityListReplica: createReplicaState<ActivityListData>(),
};
diff --git a/src/store/userMemory/slices/activity/projection.ts b/src/store/userMemory/slices/activity/projection.ts
new file mode 100644
index 00000000000..598c2ebcc5e
--- /dev/null
+++ b/src/store/userMemory/slices/activity/projection.ts
@@ -0,0 +1,66 @@
+import { type ActivityListItem } from '@lobechat/types';
+
+import { type ReplicaPagedData } from '@/libs/replica';
+import { userMemoryKeys } from '@/libs/swr/keys';
+
+import {
+ defineUserMemoryPagedReplica,
+ MAX_RECENT_MEMORY_QUERIES,
+ memoryListKey,
+} from '../../utils/replica';
+
+/** Server-side ordering of the activity list (`ActivityListSort`). */
+export type ActivityListSort = 'capturedAt' | 'startsAt';
+
+/** Page size the memory activity list asks for when the caller does not name one. */
+export const ACTIVITY_LIST_PAGE_SIZE = 12;
+
+/**
+ * Query of one page set. `page` is NOT here β€” it is the paging cursor, owned by
+ * the replica. Everything but `pageSize` is the entry key (`memoryListKey`).
+ */
+export interface ActivityListParams {
+ pageSize: number;
+ q?: string;
+ sort?: ActivityListSort;
+ status?: string[];
+ types?: string[];
+}
+
+/** One page set of the activity list, tagged with the query it answers. */
+export interface ActivityListData extends ReplicaPagedData<ActivityListItem, number> {
+ q?: string;
+ sort?: ActivityListSort;
+}
+
+/**
+ * The user-memory activity list: a local-first, offset-paged replica with one
+ * entry per search / sort (see `MemoryQueryList`). Each query paints its
+ * persisted head page on the first frame and the network confirms it.
+ *
+ * It adopts the long-standing `userMemory:activities` SWR key as its sync key, so
+ * code that revalidates the list by its key root (`purgeAllMemories`,
+ * `updateMemory`) reaches it.
+ */
+export const activityListResource = defineUserMemoryPagedReplica<
+ ActivityListParams,
+ ActivityListItem,
+ number,
+ ActivityListData
+>({
+ key: memoryListKey,
+ name: 'activityList',
+ paging: {
+ direction: 'forward',
+ getId: (item) => item.id,
+ mode: 'offset',
+ // A reload repaints what the first network page would show, never a stale tail.
+ persist: { pages: 1 },
+ },
+ // Bounded: least recently used queries leave IndexedDB and memory together;
+ // the query on screen is pinned by its mounted `useSync`.
+ persist: { maxEntries: MAX_RECENT_MEMORY_QUERIES },
+ storage: 'indexedDB',
+ syncKey: (params) => userMemoryKeys.activities(params),
+ version: 1,
+});
diff --git a/src/store/userMemory/slices/agent/action.ts b/src/store/userMemory/slices/agent/action.ts
index d74f5efa262..f973472c1a7 100644
--- a/src/store/userMemory/slices/agent/action.ts
+++ b/src/store/userMemory/slices/agent/action.ts
@@ -1,69 +1,68 @@
-import { omit } from 'es-toolkit';
-import { type SWRResponse } from 'swr';
-
-import { useClientDataSWRWithSync } from '@/libs/swr';
-import { userMemoryKeys } from '@/libs/swr/keys';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
import { userMemoryService } from '@/services/userMemory';
import { type StoreSetter } from '@/store/types';
import { type RetrieveMemoryResult } from '@/types/userMemory';
-import { setNamespace } from '@/utils/storeDebug';
import { type UserMemoryStore } from '../../store';
-
-const n = setNamespace('userMemory/agent');
+import { clearUserReplicas } from '../../utils/replica';
+import { topicMemoriesResource } from './projection';
type Setter = StoreSetter<UserMemoryStore>;
export const createAgentMemorySlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
new AgentMemoryActionImpl(set, get, _api);
export class AgentMemoryActionImpl {
- readonly #get: () => UserMemoryStore;
- readonly #set: Setter;
+ /**
+ * Topic-based memory bundles, keyed by topic id β€” the replica view the chat
+ * send path reads synchronously (see `resolveTopicMemories`).
+ */
+ readonly #topicMemories;
constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
void _api;
- this.#set = set;
- this.#get = get;
+ this.#topicMemories = createReplicaSlice(topicMemoriesResource, {
+ actionPrefix: 'userMemory/topicMemories',
+ fetcher: (topicId) => userMemoryService.retrieveMemoryForTopic(topicId),
+ get,
+ set,
+ stateKey: 'topicMemoriesReplica',
+ view: recordLens<UserMemoryStore, RetrieveMemoryResult>('topicMemoriesMap'),
+ });
}
+ /** Drop one topic's cached bundle (and its replica bookkeeping entry). */
clearTopicMemories = (topicId: string): void => {
- this.#set(
- { topicMemoriesMap: omit(this.#get().topicMemoriesMap, [topicId]) },
- false,
- n('clearTopicMemories', { topicId }),
- );
+ this.#topicMemories.remove(topicId);
};
- useFetchMemoriesForTopic = (topicId?: string | null): SWRResponse<RetrieveMemoryResult> => {
- return useClientDataSWRWithSync<RetrieveMemoryResult>(
- topicId ? userMemoryKeys.topicMemories(topicId) : null,
- async () => {
- // Retrieve memories using topic's context
- // The backend will use topic info to build the query
- return await userMemoryService.retrieveMemoryForTopic(topicId!);
- },
- {
- onData: (data) => {
- if (!topicId || !data) return;
-
- this.#set(
- (state) => ({
- topicMemoriesMap: { ...state.topicMemoriesMap, [topicId]: data },
- }),
- false,
- n('useFetchMemoriesForTopic/success', {
- activitiesCount: data.activities?.length ?? 0,
- contextsCount: data.contexts?.length ?? 0,
- experiencesCount: data.experiences?.length ?? 0,
- preferencesCount: data.preferences?.length ?? 0,
- topicId,
- }),
- );
- },
- revalidateOnFocus: false,
- },
- );
+ /**
+ * Drop every topic bundle β€” memory and every persisted row of the identity,
+ * including bundles an earlier session wrote in any workspace (the resource
+ * is scoped per user, see `topicMemoriesResource`) β€” then refetch the mounted
+ * topics. Called by `purgeAllMemories`, so a reload or a workspace switch can
+ * never inject deleted memories into the next chat request.
+ *
+ * Memory is wiped synchronously. A storage failure (a blocked IndexedDB
+ * upgrade, a closed connection) leaves a row behind that the next session has
+ * no record of, so the purge is retried once and the outcome reported: the
+ * caller surfaces `false` instead of claiming a purge a reload would undo.
+ */
+ internal_clearTopicMemories = async (user?: string): Promise<boolean> => {
+ const active = user === undefined || user === topicMemoriesResource.scope.get();
+ const cleared = await clearUserReplicas(user, this.#topicMemories);
+ // The topic bundles sync under the replica's own keys, which the purge's
+ // legacy-key revalidation does not reach.
+ if (active) void this.#topicMemories.revalidate();
+ return cleared;
};
+
+ /**
+ * Fetch orchestration only; read the bundle through `agentMemorySelectors`.
+ * One replica entry per topic, so switching topics paints the persisted
+ * bundle and the network only confirms it.
+ */
+ useFetchMemoriesForTopic = (topicId?: string | null): ReplicaSyncResult =>
+ this.#topicMemories.useSync(topicId ?? null, { revalidateOnFocus: false });
}
export type AgentMemoryAction = Pick<AgentMemoryActionImpl, keyof AgentMemoryActionImpl>;
diff --git a/src/store/userMemory/slices/agent/index.ts b/src/store/userMemory/slices/agent/index.ts
index cec69d139dd..a686fe28160 100644
--- a/src/store/userMemory/slices/agent/index.ts
+++ b/src/store/userMemory/slices/agent/index.ts
@@ -1,3 +1,4 @@
export { type AgentMemoryAction, createAgentMemorySlice } from './action';
export { agentMemoryInitialState, type AgentMemorySliceState } from './initialState';
+export { topicMemoriesResource } from './projection';
export { agentMemorySelectors } from './selectors';
diff --git a/src/store/userMemory/slices/agent/initialState.ts b/src/store/userMemory/slices/agent/initialState.ts
index 82c6f7debe2..497d9947692 100644
--- a/src/store/userMemory/slices/agent/initialState.ts
+++ b/src/store/userMemory/slices/agent/initialState.ts
@@ -1,13 +1,18 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
import { type RetrieveMemoryResult } from '@/types/userMemory';
export interface AgentMemorySliceState {
/**
- * Topic-based memory cache for agent context injection
- * Key is topicId, value is the retrieved memories for that topic
+ * Topic-based memory cache for agent context injection.
+ * Key is topicId, value is the retrieved memories for that topic.
+ * This is the view of the `topicMemoriesResource` replica.
*/
topicMemoriesMap: Record<string, RetrieveMemoryResult>;
+ /** Replica bookkeeping of `topicMemoriesMap`. */
+ topicMemoriesReplica: ReplicaState<RetrieveMemoryResult>;
}
export const agentMemoryInitialState: AgentMemorySliceState = {
topicMemoriesMap: {},
+ topicMemoriesReplica: createReplicaState(),
};
diff --git a/src/store/userMemory/slices/agent/projection.ts b/src/store/userMemory/slices/agent/projection.ts
new file mode 100644
index 00000000000..93d90e2118a
--- /dev/null
+++ b/src/store/userMemory/slices/agent/projection.ts
@@ -0,0 +1,22 @@
+import { type RetrieveMemoryResult } from '@/types/userMemory';
+
+import { defineUserMemoryReplica, MAX_RECENT_TOPIC_MEMORIES } from '../../utils/replica';
+
+/**
+ * The memories retrieved for one topic (`topicMemoriesMap[topicId]`), injected
+ * into the chat context.
+ *
+ * Keyed by the topic: the backend builds the query from the topic itself, so
+ * the topic id is the whole entry identity. Read-only and persisted, so a
+ * reload / a revisit paints the last confirmed bundle before the network only
+ * confirms it β€” the chat send path reads it synchronously and must not wait on
+ * a fetch. Scoped per user (see `userMemoryIdentityScope`), and bounded to the
+ * most recently visited topics (`MAX_RECENT_TOPIC_MEMORIES`).
+ */
+export const topicMemoriesResource = defineUserMemoryReplica<string, RetrieveMemoryResult>({
+ key: (topicId) => topicId,
+ name: 'userMemoryTopicMemories',
+ persist: { maxEntries: MAX_RECENT_TOPIC_MEMORIES },
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/userMemory/slices/agent/replica.test.ts b/src/store/userMemory/slices/agent/replica.test.ts
new file mode 100644
index 00000000000..fa24eeb0954
--- /dev/null
+++ b/src/store/userMemory/slices/agent/replica.test.ts
@@ -0,0 +1,440 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The topic memory bundles are a replica: `topicMemoriesMap` is its view and the
+ * chat send path reads it synchronously (`resolveTopicMemories`), so a reload or
+ * a topic revisit must paint the persisted bundle before the network only
+ * confirms it. One entry per topic, partitioned by identity scope.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { REPLICA_INDEX_KEY } from '@lobechat/replica';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, createReplicaState } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
+import { type RetrieveMemoryResult } from '@/types/userMemory';
+
+import { initialState as userMemoryInitialState } from '../../initialState';
+import { useUserMemoryStore } from '../../store';
+import { identityScopeOf, MAX_RECENT_TOPIC_MEMORIES } from '../../utils/replica';
+import { topicMemoriesResource } from './projection';
+import { agentMemorySelectors } from './selectors';
+
+vi.mock('@/services/userMemory', () => ({
+ memoryCRUDService: { deleteAll: vi.fn() },
+ userMemoryService: { retrieveMemoryForTopic: vi.fn() },
+}));
+
+const TOPIC_A = 'topic-a';
+const TOPIC_B = 'topic-b';
+
+const bundle = (marker: string): RetrieveMemoryResult =>
+ ({
+ activities: [{ id: `${marker}-activity` }],
+ contexts: [{ id: `${marker}-context` }],
+ experiences: [{ id: `${marker}-experience` }],
+ preferences: [{ id: `${marker}-preference` }],
+ }) as unknown as RetrieveMemoryResult;
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const topicMemories = (topicId: string) =>
+ agentMemorySelectors.topicMemories(topicId)(useUserMemoryStore.getState());
+const entry = (topicId: string) =>
+ useUserMemoryStore.getState().topicMemoriesReplica.entries[topicId];
+
+describe('userMemory topic memories replica', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ /** The storage partition of the topic memories: the identity, not the workspace. */
+ let rowScope = '';
+ const useScope = (next: string) => {
+ scope = next;
+ rowScope = identityScopeOf(next);
+ scopes.add(rowScope);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`memory-user-${randomUUID()}:personal`);
+ act(() =>
+ useUserMemoryStore.setState({
+ ...userMemoryInitialState,
+ topicMemoriesMap: {},
+ topicMemoriesReplica: createReplicaState(),
+ }),
+ );
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ [TOPIC_A, TOPIC_B].map((topicId) =>
+ topicMemoriesResource.storage!.remove({
+ queryKey: topicMemoriesResource.storageKey(topicId),
+ scope: value,
+ }),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted bundle before the network answers', async () => {
+ const cached = bundle('cached');
+ await topicMemoriesResource.storage!.set(
+ { queryKey: topicMemoriesResource.storageKey(TOPIC_A), scope: rowScope },
+ { data: cached, updatedAt: 1 },
+ );
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockImplementation(pending);
+
+ const sync = renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_A), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(topicMemories(TOPIC_A)).toEqual(cached));
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(sync.result.current.isValidating).toBe(true);
+ });
+
+ it('replaces the persisted bundle with the network response and persists it', async () => {
+ const fresh = bundle('fresh');
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(fresh);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_A), { wrapper });
+
+ await waitFor(() => expect(topicMemories(TOPIC_A)).toEqual(fresh));
+ // The view is backed by the replica engine, keyed by the topic.
+ expect(entry(TOPIC_A)?.source).toBe('server');
+
+ await waitFor(async () =>
+ expect(
+ (
+ await topicMemoriesResource.storage!.get({
+ queryKey: topicMemoriesResource.storageKey(TOPIC_A),
+ scope: rowScope,
+ })
+ )?.data,
+ ).toEqual(fresh),
+ );
+ });
+
+ it('drops a topic’s bundle β€” view, bookkeeping and storage β€” on clear', async () => {
+ const fresh = bundle('fresh');
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(fresh);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_A), { wrapper });
+ await waitFor(() => expect(topicMemories(TOPIC_A)).toEqual(fresh));
+
+ act(() => useUserMemoryStore.getState().clearTopicMemories(TOPIC_A));
+
+ expect(topicMemories(TOPIC_A)).toBeUndefined();
+ expect(entry(TOPIC_A)).toBeUndefined();
+ expect(agentMemorySelectors.hasTopicMemories(TOPIC_A)(useUserMemoryStore.getState())).toBe(
+ false,
+ );
+
+ await waitFor(async () =>
+ expect(
+ await topicMemoriesResource.storage!.get({
+ queryKey: topicMemoriesResource.storageKey(TOPIC_A),
+ scope: rowScope,
+ }),
+ ).toBeUndefined(),
+ );
+ });
+
+ it('purges every persisted bundle on purgeAllMemories, so a reload cannot restore them', async () => {
+ const storageKeyOf = (topicId: string) => ({
+ queryKey: topicMemoriesResource.storageKey(topicId),
+ scope: rowScope,
+ });
+ const resetMemory = () =>
+ act(() =>
+ useUserMemoryStore.setState({
+ topicMemoriesMap: {},
+ topicMemoriesReplica: createReplicaState(),
+ }),
+ );
+
+ // An earlier session persisted TOPIC_B; after the reload it is not in memory.
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(
+ bundle('earlier-session'),
+ );
+ const earlier = renderHook(
+ () => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_B),
+ { wrapper },
+ );
+ await waitFor(async () =>
+ expect(await topicMemoriesResource.storage!.get(storageKeyOf(TOPIC_B))).toBeDefined(),
+ );
+ earlier.unmount();
+ resetMemory();
+
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(bundle('fresh'));
+ renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_A), { wrapper });
+ await waitFor(() => expect(topicMemories(TOPIC_A)).toEqual(bundle('fresh')));
+ await waitFor(async () =>
+ expect(await topicMemoriesResource.storage!.get(storageKeyOf(TOPIC_A))).toBeDefined(),
+ );
+
+ // After the purge the server only has an empty bundle to give back.
+ const empty = bundle('empty');
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(empty);
+ await act(() => useUserMemoryStore.getState().purgeAllMemories());
+
+ expect(memoryCRUDService.deleteAll).toHaveBeenCalledTimes(1);
+ expect(await topicMemoriesResource.storage!.get(storageKeyOf(TOPIC_B))).toBeUndefined();
+ // The mounted topic settles on the server's post-purge answer, which is all
+ // that is persisted for it β€” never the deleted bundle.
+ await waitFor(() => expect(topicMemories(TOPIC_A)).toEqual(empty));
+ await waitFor(async () =>
+ expect((await topicMemoriesResource.storage!.get(storageKeyOf(TOPIC_A)))?.data).toEqual(
+ empty,
+ ),
+ );
+
+ // Reload: a fresh view whose fetch never answers paints nothing deleted.
+ cleanup();
+ resetMemory();
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockImplementation(pending);
+ const reloaded = renderHook(
+ () => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_B),
+ { wrapper },
+ );
+ await waitFor(() => expect(reloaded.result.current.isHydrated).toBe(true));
+ expect(topicMemories(TOPIC_B)).toBeUndefined();
+ });
+
+ it('retries a purge whose local deletes failed, so no earlier bundle survives', async () => {
+ // `purgeAllMemories` revalidates through the app's scoped `mutate`.
+ renderHook(() => null, { wrapper });
+
+ const storage = topicMemoriesResource.storage!;
+ const remove = storage.remove.bind(storage);
+ const rowKey = { queryKey: topicMemoriesResource.storageKey(TOPIC_B), scope: rowScope };
+ const indexRowKey = { queryKey: REPLICA_INDEX_KEY, scope: rowScope };
+
+ // An earlier session's rows only β€” nothing is tracked in memory.
+ await storage.set(rowKey, { data: bundle('earlier-session'), updatedAt: 1 });
+ await storage.set(indexRowKey, { data: [rowKey.queryKey], updatedAt: 1 });
+
+ // The first try aborts (a blocked IndexedDB upgrade); the retry lands.
+ let removeCalls = 0;
+ vi.spyOn(storage, 'remove').mockImplementation(async (key) => {
+ if (++removeCalls === 1) throw new Error('IndexedDB transaction aborted');
+ return remove(key);
+ });
+
+ await act(() => useUserMemoryStore.getState().purgeAllMemories());
+
+ expect(removeCalls).toBeGreaterThan(1);
+ expect(await storage.get(rowKey)).toBeUndefined();
+ });
+
+ it('purges the bundles cached in the identity’s other workspaces', async () => {
+ const userId = scope.slice(0, scope.indexOf(':'));
+ const otherWorkspace = `${userId}:workspace-b`;
+ const personal = scope;
+
+ // A bundle fetched and persisted while the user was in another workspace.
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(
+ bundle('other-workspace'),
+ );
+ useScope(otherWorkspace);
+ const earlier = renderHook(
+ () => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_B),
+ { wrapper },
+ );
+ await waitFor(async () =>
+ expect(
+ await topicMemoriesResource.storage!.get({
+ queryKey: topicMemoriesResource.storageKey(TOPIC_B),
+ scope: rowScope,
+ }),
+ ).toBeDefined(),
+ );
+ earlier.unmount();
+
+ // Back in the personal workspace, the user purges everything (server-side
+ // the delete is user-wide).
+ useScope(personal);
+ renderHook(() => null, { wrapper });
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockImplementation(pending);
+ await act(() => useUserMemoryStore.getState().purgeAllMemories());
+
+ // Switching to the other workspace must not hydrate the purged bundle.
+ useScope(otherWorkspace);
+ const sync = renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_B), {
+ wrapper,
+ });
+ await waitFor(() => expect(sync.result.current.isHydrated).toBe(true));
+ expect(topicMemories(TOPIC_B)).toBeUndefined();
+ sync.unmount();
+ });
+
+ it('surfaces a purge whose rows survive local storage, after the in-memory reset', async () => {
+ renderHook(() => null, { wrapper });
+
+ const storage = topicMemoriesResource.storage!;
+ const remove = storage.remove.bind(storage);
+ const rowKey = { queryKey: topicMemoriesResource.storageKey(TOPIC_B), scope: rowScope };
+ const indexRowKey = { queryKey: REPLICA_INDEX_KEY, scope: rowScope };
+
+ await storage.set(rowKey, { data: bundle('earlier-session'), updatedAt: 1 });
+ await storage.set(indexRowKey, { data: [rowKey.queryKey], updatedAt: 1 });
+
+ let failDeletes = true;
+ vi.spyOn(storage, 'remove').mockImplementation(async (key) => {
+ if (failDeletes) throw new Error('IndexedDB transaction aborted');
+ return remove(key);
+ });
+
+ try {
+ // What the user is looking at when they hit purge.
+ act(() =>
+ useUserMemoryStore.setState({ topicMemoriesMap: { [TOPIC_A]: bundle('in-memory') } }),
+ );
+
+ // Storage is unreachable for both attempts, so the purge must not report success.
+ await act(async () => {
+ await expect(useUserMemoryStore.getState().purgeAllMemories()).rejects.toThrow(
+ /local storage/,
+ );
+ });
+
+ // The in-memory reset still stands β€” purged memories must not stay visible,
+ // and the row that could not be deleted is exactly what was surfaced.
+ expect(topicMemories(TOPIC_A)).toBeUndefined();
+ expect(agentMemorySelectors.hasTopicMemories(TOPIC_A)(useUserMemoryStore.getState())).toBe(
+ false,
+ );
+ expect(await storage.get(rowKey)).toBeDefined();
+ } finally {
+ // Let the suite's cleanup reach storage again.
+ failDeletes = false;
+ }
+ });
+
+ it('purges the deleted user’s bundles after an account switch, so they are never injected later', async () => {
+ const rowOf = (topicId: string, scopeValue: string) =>
+ topicMemoriesResource.storage!.get({
+ queryKey: topicMemoriesResource.storageKey(topicId),
+ scope: scopeValue,
+ });
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(bundle('deleted'));
+ const first = renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_A), {
+ wrapper,
+ });
+ await waitFor(async () => expect((await rowOf(TOPIC_A, rowScope))?.data).toBeDefined());
+ first.unmount();
+ const deletedUser = rowScope;
+
+ // Another account becomes active and caches its own bundle.
+ useScope(`memory-user-${randomUUID()}:personal`);
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(bundle('active'));
+ renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_B), { wrapper });
+ await waitFor(async () => expect((await rowOf(TOPIC_B, rowScope))?.data).toBeDefined());
+
+ let cleared = false;
+ await act(async () => {
+ cleared = await useUserMemoryStore.getState().internal_clearTopicMemories(deletedUser);
+ });
+
+ expect(cleared).toBe(true);
+ await expect(rowOf(TOPIC_A, deletedUser)).resolves.toBeUndefined();
+ // The active user's bundle (view and row) is untouched.
+ expect(topicMemories(TOPIC_B)).toEqual(bundle('active'));
+ expect((await rowOf(TOPIC_B, rowScope))?.data).toEqual(bundle('active'));
+ });
+
+ it('bounds the persisted topic bundles to the most recently visited topics', async () => {
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockImplementation(async (topicId) =>
+ bundle(topicId),
+ );
+ const topics = Array.from({ length: MAX_RECENT_TOPIC_MEMORIES + 2 }, (_, i) => `topic-${i}`);
+ const rowOf = (topicId: string) =>
+ topicMemoriesResource.storage!.get({
+ queryKey: topicMemoriesResource.storageKey(topicId),
+ scope: rowScope,
+ });
+
+ const hook = renderHook(
+ (props: { topicId: string }) =>
+ useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(props.topicId),
+ { initialProps: { topicId: topics[0] }, wrapper },
+ );
+ for (const topicId of topics) {
+ hook.rerender({ topicId });
+ await waitFor(() => expect(topicMemories(topicId)).toEqual(bundle(topicId)));
+ }
+
+ // The oldest topics left memory and IndexedDB together; the recent ones stay.
+ expect(Object.keys(useUserMemoryStore.getState().topicMemoriesMap)).toHaveLength(
+ MAX_RECENT_TOPIC_MEMORIES,
+ );
+ expect(topicMemories(topics[0])).toBeUndefined();
+ await waitFor(async () => expect(await rowOf(topics[0])).toBeUndefined());
+ expect((await rowOf(topics.at(-1)!))?.data).toEqual(bundle(topics.at(-1)!));
+ await Promise.all(
+ topics.map((topicId) =>
+ topicMemoriesResource.storage!.remove({
+ queryKey: topicMemoriesResource.storageKey(topicId),
+ scope: rowScope,
+ }),
+ ),
+ );
+ });
+
+ it('does not fetch when there is no topic', async () => {
+ renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(undefined), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(userMemoryService.retrieveMemoryForTopic).not.toHaveBeenCalled();
+ expect(topicMemories(TOPIC_A)).toBeUndefined();
+ });
+
+ it('drops the previous identity’s bundles before the next identity paints', async () => {
+ const fresh = bundle('fresh');
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(fresh);
+
+ const sync = renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_A), {
+ wrapper,
+ });
+ await waitFor(() => expect(topicMemories(TOPIC_A)).toEqual(fresh));
+
+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockImplementation(pending);
+ useScope(`memory-user-${randomUUID()}:personal`);
+ sync.rerender();
+
+ await waitFor(() => expect(topicMemories(TOPIC_A)).toBeUndefined());
+ expect(entry(TOPIC_A)).toBeUndefined();
+ });
+});
diff --git a/src/store/userMemory/slices/base/action.test.ts b/src/store/userMemory/slices/base/action.test.ts
index 9fb117b9342..e2397c5d829 100644
--- a/src/store/userMemory/slices/base/action.test.ts
+++ b/src/store/userMemory/slices/base/action.test.ts
@@ -2,6 +2,7 @@ import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { DisplayPreferenceMemory } from '@/database/repositories/userMemory';
+import { cacheScope } from '@/libs/replica';
import type * as SwrLib from '@/libs/swr';
import { mutate } from '@/libs/swr';
import { userMemoryKeys } from '@/libs/swr/keys';
@@ -39,13 +40,21 @@ const preferenceMemory = {
beforeEach(() => {
vi.clearAllMocks();
+ const page = {
+ currentPage: 0,
+ hasMore: false,
+ items: [preferenceMemory],
+ pageSize: 12,
+ total: 1,
+ };
useUserMemoryStore.setState(
{
...initialState,
+ preferenceListData: page,
+ preferenceListEntries: { [initialState.preferenceListKey]: page },
preferences: [preferenceMemory],
preferencesInit: true,
preferencesPage: 1,
- preferencesSearchLoading: false,
preferencesTotal: 1,
},
false,
@@ -58,6 +67,48 @@ afterEach(() => {
describe('userMemory base actions', () => {
describe('updateMemory', () => {
+ it.each([
+ [LayersEnum.Activity, 'updateActivity', 'internal_updateActivityEntity', 'narrative'],
+ [LayersEnum.Context, 'updateContext', 'internal_updateContextEntity', 'description'],
+ [LayersEnum.Experience, 'updateExperience', 'internal_updateExperienceEntity', 'keyLearning'],
+ [LayersEnum.Identity, 'updateIdentity', 'internal_updateIdentityEntity', 'description'],
+ [
+ LayersEnum.Preference,
+ 'updatePreference',
+ 'internal_updatePreferenceEntity',
+ 'conclusionDirectives',
+ ],
+ ] as const)(
+ 'routes a %s edit through its replica entity patch, then revalidates list and detail',
+ async (layer, serviceMethod, entityAction, field) => {
+ vi.spyOn(memoryCRUDService, serviceMethod).mockResolvedValue(true as never);
+ const patchEntity = vi.fn();
+ const refreshIdentities = vi.fn().mockResolvedValue(undefined);
+ useUserMemoryStore.setState({
+ [entityAction]: patchEntity,
+ editingMemoryId: 'memory-1',
+ refreshIdentities,
+ });
+
+ await useUserMemoryStore.getState().updateMemory('memory-1', 'edited', layer);
+
+ expect(memoryCRUDService[serviceMethod]).toHaveBeenCalledWith('memory-1', {
+ [field]: 'edited',
+ });
+ expect(patchEntity).toHaveBeenCalledTimes(1);
+ const [id, patch] = patchEntity.mock.calls[0];
+ expect(id).toBe('memory-1');
+ expect(patch({ id: 'memory-1', [field]: 'old' })).toEqual({
+ id: 'memory-1',
+ [field]: 'edited',
+ });
+ expect(useUserMemoryStore.getState().editingMemoryId).toBeUndefined();
+ expect(mutate).toHaveBeenCalledWith(userMemoryKeys.memoryDetail(layer, 'memory-1'));
+ if (layer === LayersEnum.Identity) expect(refreshIdentities).toHaveBeenCalledTimes(1);
+ else expect(mutate).toHaveBeenCalledWith(expect.any(Function));
+ },
+ );
+
it('updates a preference memory in place and revalidates related caches', async () => {
const updatePreferenceResult = {} as Awaited<
ReturnType<typeof memoryCRUDService.updatePreference>
@@ -74,13 +125,15 @@ describe('userMemory base actions', () => {
);
});
- expect(result.current.preferences).toEqual([
- {
- ...preferenceMemory,
- conclusionDirectives: 'Prefer concise answers with examples.',
- },
+ const edited = {
+ ...preferenceMemory,
+ conclusionDirectives: 'Prefer concise answers with examples.',
+ };
+ expect(result.current.preferences).toEqual([edited]);
+ // The canonical replica value carries the edit, not only the flat mirror.
+ expect(result.current.preferenceListEntries[result.current.preferenceListKey].items).toEqual([
+ edited,
]);
- expect(result.current.preferencesSearchLoading).toBe(false);
expect(memoryCRUDService.updatePreference).toHaveBeenCalledWith('preference-1', {
conclusionDirectives: 'Prefer concise answers with examples.',
});
@@ -89,6 +142,161 @@ describe('userMemory base actions', () => {
userMemoryKeys.memoryDetail(LayersEnum.Preference, 'preference-1'),
);
});
+
+ it('applies an identity edit through the replica and revalidates it', async () => {
+ vi.spyOn(memoryCRUDService, 'updateIdentity').mockResolvedValue(true);
+ const internal_updateIdentityEntity = vi.fn();
+ const internal_clearIdentityList = vi.fn().mockResolvedValue(true);
+ const refreshIdentities = vi.fn().mockResolvedValue(undefined);
+ useUserMemoryStore.setState({
+ internal_clearIdentityList,
+ internal_updateIdentityEntity,
+ refreshIdentities,
+ });
+
+ await act(async () => {
+ await useUserMemoryStore
+ .getState()
+ .updateMemory('identity-1', 'New description', LayersEnum.Identity);
+ });
+
+ expect(internal_updateIdentityEntity).toHaveBeenCalledWith(
+ 'identity-1',
+ expect.any(Function),
+ );
+ const patch = internal_updateIdentityEntity.mock.calls[0][1];
+ expect(patch({ description: 'old', id: 'identity-1' })).toEqual({
+ description: 'New description',
+ id: 'identity-1',
+ });
+ expect(refreshIdentities).toHaveBeenCalledTimes(1);
+ expect(internal_clearIdentityList).not.toHaveBeenCalled();
+ });
+ });
+});
+
+/** Every replica-backed slice's purge action (see `purgeAllMemories`). */
+const REPLICA_CLEARS = [
+ 'internal_clearMemoryReplicas',
+ 'internal_clearTopicMemories',
+ 'internal_clearHomeReplicas',
+ 'internal_clearActivityList',
+ 'internal_clearContextList',
+ 'internal_clearExperienceList',
+ 'internal_clearIdentityList',
+ 'internal_clearPreferenceList',
+] as const;
+
+/** Replace every slice purge with a spy that records its call and resolves `result`. */
+const stubReplicaClears = (order: string[], results: Partial<Record<string, boolean>> = {}) => {
+ const spies = Object.fromEntries(
+ REPLICA_CLEARS.map((name) => [
+ name,
+ vi.fn(async () => {
+ order.push(name);
+ return results[name] ?? true;
+ }),
+ ]),
+ );
+ useUserMemoryStore.setState(spies);
+ return spies;
+};
+
+describe('purgeAllMemories', () => {
+ const useCacheScope = (value: string) => {
+ vi.spyOn(cacheScope, 'get').mockReturnValue(value);
+ };
+
+ beforeEach(() => {
+ useCacheScope('user-1:personal');
+ });
+
+ it('clears every replica right after deleting, then revalidates', async () => {
+ const order: string[] = [];
+ vi.spyOn(memoryCRUDService, 'deleteAll').mockImplementation(async () => {
+ order.push('deleteAll');
+ return undefined as never;
+ });
+ stubReplicaClears(order);
+ vi.mocked(mutate).mockImplementation(async () => {
+ order.push('revalidate');
+ });
+
+ await useUserMemoryStore.getState().purgeAllMemories();
+
+ // Every slice purge runs right after the server delete, before any refetch.
+ expect(order.slice(0, REPLICA_CLEARS.length + 1)).toEqual(['deleteAll', ...REPLICA_CLEARS]);
+ expect(order.slice(REPLICA_CLEARS.length + 1).every((step) => step === 'revalidate')).toBe(
+ true,
+ );
+ // The replica-owned fields are not overwritten by `preferenceInitialState`.
+ expect(useUserMemoryStore.getState().preferences).toEqual([preferenceMemory]);
+ });
+
+ it('surfaces a local purge failure after the in-memory reset and the refetch', async () => {
+ const order: string[] = [];
+ vi.spyOn(memoryCRUDService, 'deleteAll').mockResolvedValue(undefined as never);
+ const spies = stubReplicaClears(order, { internal_clearContextList: false });
+ useUserMemoryStore.setState({ editingMemoryId: 'editing' });
+ vi.mocked(mutate).mockImplementation(async () => {
+ order.push('revalidate');
+ });
+
+ await expect(useUserMemoryStore.getState().purgeAllMemories()).rejects.toThrow(
+ 'Failed to purge persisted memories from local storage',
+ );
+
+ // A failed slice does not stop the others, and the reset + refetch still ran.
+ for (const name of REPLICA_CLEARS) expect(spies[name]).toHaveBeenCalledTimes(1);
+ expect(useUserMemoryStore.getState().editingMemoryId).toBeUndefined();
+ expect(order).toContain('revalidate');
+ });
+
+ it('purges the same user’s replicas when the workspace switches mid-purge', async () => {
+ const order: string[] = [];
+ vi.spyOn(memoryCRUDService, 'deleteAll').mockImplementation(async () => {
+ // Memories are per user: another workspace of the same user is the same partition.
+ useCacheScope('user-1:ws-2');
+ return undefined as never;
+ });
+ const spies = stubReplicaClears(order);
+
+ await useUserMemoryStore.getState().purgeAllMemories();
+
+ // Same user: the ordinary (active-partition) purge.
+ for (const name of REPLICA_CLEARS) expect(spies[name]).toHaveBeenCalledWith('user-1:*');
+ });
+
+ it('purges only the deleted user’s partition when the account switches mid-purge', async () => {
+ const order: string[] = [];
+ vi.spyOn(memoryCRUDService, 'deleteAll').mockImplementation(async () => {
+ useCacheScope('user-2:personal');
+ return undefined as never;
+ });
+ const spies = stubReplicaClears(order);
+ useUserMemoryStore.setState({ editingMemoryId: 'kept' });
+ vi.mocked(mutate).mockClear();
+
+ await expect(useUserMemoryStore.getState().purgeAllMemories()).resolves.toBeUndefined();
+
+ // Every slice purges the user the server deleted, not the active one.
+ for (const name of REPLICA_CLEARS) expect(spies[name]).toHaveBeenCalledWith('user-1:*');
+ // The active user's state and mounted queries are left alone.
+ expect(useUserMemoryStore.getState().editingMemoryId).toBe('kept');
+ expect(useUserMemoryStore.getState().preferences).toEqual([preferenceMemory]);
+ expect(mutate).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a failed purge of the deleted user’s partition after an account switch', async () => {
+ vi.spyOn(memoryCRUDService, 'deleteAll').mockImplementation(async () => {
+ useCacheScope('user-2:personal');
+ return undefined as never;
+ });
+ stubReplicaClears([], { internal_clearTopicMemories: false });
+
+ await expect(useUserMemoryStore.getState().purgeAllMemories()).rejects.toThrow(
+ 'Failed to purge persisted memories from local storage',
+ );
});
});
@@ -96,19 +304,33 @@ describe('deletePersona', () => {
const persona = { content: 'My persona', summary: 'Summary' };
beforeEach(() => {
- useUserMemoryStore.setState({ persona, personaInit: true });
- vi.mocked(mutate).mockImplementation(async (_key: any, update: any) => update());
+ useUserMemoryStore.setState({ persona, personaData: { persona }, personaInit: true });
+ vi.mocked(mutate).mockResolvedValue(undefined as never);
});
- it('clears the persona cache while retaining the memory lists', async () => {
+ it('clears the persona replica view while retaining the memory lists', async () => {
vi.spyOn(memoryCRUDService, 'deletePersona').mockResolvedValue({ success: true });
await useUserMemoryStore.getState().deletePersona();
expect(useUserMemoryStore.getState().persona).toBeUndefined();
+ // The canonical replica view carries the server-confirmed absence.
+ expect(useUserMemoryStore.getState().personaData).toEqual({ persona: null });
+ expect(useUserMemoryStore.getState().personaInit).toBe(true);
expect(useUserMemoryStore.getState().preferences).toEqual([preferenceMemory]);
expect(useUserMemoryStore.getState().preferencesTotal).toBe(1);
- expect(mutate).toHaveBeenCalledWith(userMemoryKeys.persona(), expect.any(Function), {
- revalidate: false,
- });
+ // The replica adopts the userMemory:persona key as its sync key.
+ expect(mutate).toHaveBeenCalledWith(userMemoryKeys.persona());
+ });
+
+ it('resolves when the persona is deleted but the follow-up read fails', async () => {
+ vi.spyOn(memoryCRUDService, 'deletePersona').mockResolvedValue({ success: true });
+ vi.mocked(mutate).mockRejectedValueOnce(new Error('read failed'));
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(useUserMemoryStore.getState().deletePersona()).resolves.toBeUndefined();
+
+ expect(useUserMemoryStore.getState().persona).toBeUndefined();
+ expect(useUserMemoryStore.getState().personaData).toEqual({ persona: null });
+ expect(consoleError).toHaveBeenCalled();
});
it('retains the persona and memories when deletion fails', async () => {
diff --git a/src/store/userMemory/slices/base/action.ts b/src/store/userMemory/slices/base/action.ts
index 6ab54d32b46..93c7b4df2ed 100644
--- a/src/store/userMemory/slices/base/action.ts
+++ b/src/store/userMemory/slices/base/action.ts
@@ -2,7 +2,7 @@ import { produce } from 'immer';
import { type SWRResponse } from 'swr';
import { createReplicaSlice, type ReplicaLens, type ReplicaSyncResult } from '@/libs/replica';
-import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
+import { mutate } from '@/libs/swr';
import { userMemoryKeys } from '@/libs/swr/keys';
import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
import { type StoreSetter } from '@/store/types';
@@ -11,14 +11,9 @@ import { LayersEnum } from '@/types/userMemory';
import { setNamespace } from '@/utils/storeDebug';
import { type UserMemoryStore, useUserMemoryStore } from '../../store';
-import { type IdentityForInjection } from '../../types';
import { userMemoryCacheKey } from '../../utils/cacheKey';
+import { clearUserReplicas, userMemoryIdentityScope } from '../../utils/replica';
import { createMemorySearchParams } from '../../utils/searchParams';
-import { activityInitialState } from '../activity/initialState';
-import { contextInitialState } from '../context/initialState';
-import { experienceInitialState } from '../experience/initialState';
-import { identityInitialState } from '../identity/initialState';
-import { preferenceInitialState } from '../preference/initialState';
import {
type MemoryDetailDisplay,
memoryDetailKey,
@@ -121,18 +116,13 @@ export class BaseActionImpl {
);
};
- /** PersonaHeader confirmation deletes the persona through memoryCRUDService, then clears its cache. */
+ /** PersonaHeader confirmation deletes the persona through memoryCRUDService, then refreshes its replica. */
deletePersona = async (): Promise<void> => {
const { memoryCRUDService } = await import('@/services/userMemory');
- await mutate(
- userMemoryKeys.persona(),
- async () => {
- await memoryCRUDService.deletePersona();
- this.#set({ persona: undefined, personaInit: true }, false, n('deletePersona'));
- return null;
- },
- { revalidate: false },
- );
+ await memoryCRUDService.deletePersona();
+ // The persona is a replica view now: drop it locally and re-read server
+ // truth (null) so the section disappears without waiting for the network.
+ await this.#get().refreshPersona();
};
/**
@@ -176,96 +166,87 @@ export class BaseActionImpl {
* no record of, so the purge is retried once; resolves `true` once storage
* is purged.
*/
- internal_clearMemoryReplicas = async (): Promise<boolean> => {
- let cleared = false;
- for (let attempt = 0; attempt < 2 && !cleared; attempt++) {
- const results = await Promise.all([this.#retrieve.clear(), this.#detail.clear()]);
- cleared = results.every(Boolean);
- }
- return cleared;
- };
+ internal_clearMemoryReplicas = (user?: string): Promise<boolean> =>
+ clearUserReplicas(user, this.#retrieve, this.#detail);
purgeAllMemories = async (): Promise<void> => {
const { memoryCRUDService } = await import('@/services/userMemory');
+ // Every userMemory replica is partitioned per user (see
+ // `userMemoryIdentityScope`), so a workspace switch while the request is in
+ // flight changes nothing below.
+ const user = userMemoryIdentityScope.get();
+
await memoryCRUDService.deleteAll();
// Replica-backed reads own their state and persisted projection: wipe them
// through the engine (memory + IndexedDB + reads in flight) before the
- // revalidation below, so a reload never resurrects purged rows. Each
- // `internal_clear*` resolves `false` when a persisted row survived a storage
- // failure (the next session would hydrate it back).
+ // plain-state reset and the revalidation below, so a reload never
+ // resurrects purged rows. Each `internal_clear*` retries once and resolves
+ // `false` when a persisted row survived a storage failure (the next session
+ // would hydrate it back). No slice resets its replica-owned fields here.
+ //
+ // `user` is the account whose memories the server deleted. If another
+ // account became active while the request ran, each slice purges only that
+ // user's persisted partition and leaves the active user's views and rows
+ // alone (`clearUserReplicas`).
const replicaPurges: boolean[] = [
// One line per replica-backed slice.
- await this.#get().internal_clearMemoryReplicas(),
+ await this.#get().internal_clearMemoryReplicas(user),
+ await this.#get().internal_clearTopicMemories(user),
+ await this.#get().internal_clearHomeReplicas(user),
+ await this.#get().internal_clearActivityList(user),
+ await this.#get().internal_clearContextList(user),
+ await this.#get().internal_clearExperienceList(user),
+ await this.#get().internal_clearIdentityList(user),
+ await this.#get().internal_clearPreferenceList(user),
];
+ const purgeFailed = !replicaPurges.every(Boolean);
+
+ // An account switch: the active views, plain state and mounted queries all
+ // belong to the other user, so there is nothing to reset or refetch.
+ if (userMemoryIdentityScope.get() !== user) {
+ if (purgeFailed) throw new Error('Failed to purge persisted memories from local storage');
+ return;
+ }
this.#set(
produce((draft) => {
- Object.assign(draft, activityInitialState);
- Object.assign(draft, contextInitialState);
- Object.assign(draft, experienceInitialState);
- Object.assign(draft, identityInitialState);
- Object.assign(draft, preferenceInitialState);
-
draft.activeParams = undefined;
draft.activeParamsKey = undefined;
draft.editingMemoryContent = undefined;
draft.editingMemoryId = undefined;
draft.editingMemoryLayer = undefined;
- draft.persona = undefined;
- draft.personaInit = true;
- draft.roles = [];
- draft.tags = [];
- draft.tagsInit = true;
}),
false,
n('purgeAllMemories'),
);
+ // `clear()` does not refetch: revalidate every mounted read so the views
+ // settle on the server's (now empty) answer. The lists, the retrieve map,
+ // the detail and the home reads adopt their legacy SWR keys as sync keys;
+ // identities (and the topic memories, see `internal_clearTopicMemories`)
+ // sync under the replica's own keys.
await Promise.all([
- mutate(
- (key) => Array.isArray(key) && key[0] === userMemoryKeys.memoryDetail.root,
- undefined,
- { revalidate: true },
- ),
- mutate((key) => Array.isArray(key) && key[0] === userMemoryKeys.activities.root, undefined, {
- revalidate: true,
- }),
- mutate((key) => Array.isArray(key) && key[0] === userMemoryKeys.contexts.root, undefined, {
- revalidate: true,
- }),
- mutate((key) => Array.isArray(key) && key[0] === userMemoryKeys.experiences.root, undefined, {
- revalidate: true,
- }),
- mutate(
- (key) => Array.isArray(key) && key[0] === userMemoryKeys.identityList.root,
- undefined,
- {
- revalidate: true,
- },
- ),
- mutate((key) => Array.isArray(key) && key[0] === userMemoryKeys.preferences.root, undefined, {
- revalidate: true,
- }),
- mutate((key) => Array.isArray(key) && key[0] === userMemoryKeys.retrieve.root, undefined, {
- revalidate: true,
- }),
- mutate(userMemoryKeys.persona(), null, { revalidate: false }),
- mutate(
- userMemoryKeys.tags(),
- {
- roles: [],
- tags: [],
- },
- { revalidate: false },
+ ...[
+ userMemoryKeys.activities.root,
+ userMemoryKeys.contexts.root,
+ userMemoryKeys.experiences.root,
+ userMemoryKeys.memoryDetail.root,
+ userMemoryKeys.preferences.root,
+ userMemoryKeys.retrieve.root,
+ ].map((root) =>
+ mutate((key) => Array.isArray(key) && key[0] === root, undefined, { revalidate: true }),
),
+ mutate(userMemoryKeys.persona(), undefined, { revalidate: true }),
+ mutate(userMemoryKeys.tags(), undefined, { revalidate: true }),
+ this.#get().refreshIdentities(),
]);
// The in-memory reset above already stands β€” the user must not keep seeing
// purged memories. Surface the rows that survived locally instead of
// reporting a purge the next session would silently undo.
- if (!replicaPurges.every(Boolean)) {
+ if (purgeFailed) {
throw new Error('Failed to purge persisted memories from local storage');
}
};
@@ -303,85 +284,68 @@ export class BaseActionImpl {
);
};
+ /**
+ * Save an inline edit. Every layer is replica-backed: its slice's
+ * `internal_update<X>Entity` patches the row in every loaded query and in
+ * the persisted rows of the ones not loaded, so a filter / sort switch or a
+ * reload shows the edit before any refetch. The list and the detail are
+ * then revalidated against the server.
+ */
updateMemory = async (id: string, content: string, layer: LayersEnum): Promise<void> => {
- let listKeyRoot: string | undefined;
+ const listRoot = (root: string) => () => mutate((key) => Array.isArray(key) && key[0] === root);
+ let revalidateList: () => Promise<unknown>;
switch (layer) {
case LayersEnum.Activity: {
await memoryCRUDService.updateActivity(id, { narrative: content });
- this.#set(
- produce((draft) => {
- const item = draft.activities.find((memory) => memory.id === id);
- if (item) item.narrative = content;
- }),
- false,
- n('updateMemory/activity'),
- );
- listKeyRoot = userMemoryKeys.activities.root;
+ this.#get().internal_updateActivityEntity(id, (item) => ({ ...item, narrative: content }));
+ revalidateList = listRoot(userMemoryKeys.activities.root);
break;
}
case LayersEnum.Context: {
await memoryCRUDService.updateContext(id, { description: content });
- this.#set(
- produce((draft) => {
- const item = draft.contexts.find((memory) => memory.id === id);
- if (item) item.description = content;
- }),
- false,
- n('updateMemory/context'),
- );
- listKeyRoot = userMemoryKeys.contexts.root;
+ this.#get().internal_updateContextEntity(id, (item) => ({ ...item, description: content }));
+ revalidateList = listRoot(userMemoryKeys.contexts.root);
break;
}
case LayersEnum.Experience: {
await memoryCRUDService.updateExperience(id, { keyLearning: content });
- this.#set(
- produce((draft) => {
- const item = draft.experiences.find((memory) => memory.id === id);
- if (item) item.keyLearning = content;
- }),
- false,
- n('updateMemory/experience'),
- );
- listKeyRoot = userMemoryKeys.experiences.root;
+ this.#get().internal_updateExperienceEntity(id, (item) => ({
+ ...item,
+ keyLearning: content,
+ }));
+ revalidateList = listRoot(userMemoryKeys.experiences.root);
break;
}
case LayersEnum.Identity: {
await memoryCRUDService.updateIdentity(id, { description: content });
- this.#set(
- produce((draft) => {
- const item = draft.identities.find((memory) => memory.id === id);
- if (item) item.description = content;
- }),
- false,
- n('updateMemory/identity'),
- );
- listKeyRoot = userMemoryKeys.identityList.root;
+ this.#get().internal_updateIdentityEntity(id, (item) => ({
+ ...item,
+ description: content,
+ }));
+ // The list and the self identities injected into chat sync under the
+ // replica's own keys.
+ revalidateList = this.#get().refreshIdentities;
break;
}
case LayersEnum.Preference: {
await memoryCRUDService.updatePreference(id, { conclusionDirectives: content });
- this.#set(
- produce((draft) => {
- const item = draft.preferences.find((memory) => memory.id === id);
- if (item) item.conclusionDirectives = content;
- }),
- false,
- n('updateMemory/preference'),
- );
- listKeyRoot = userMemoryKeys.preferences.root;
+ this.#get().internal_updatePreferenceEntity(id, (item) => ({
+ ...item,
+ conclusionDirectives: content,
+ }));
+ revalidateList = listRoot(userMemoryKeys.preferences.root);
break;
}
+ default: {
+ this.#get().clearEditingMemory();
+ return;
+ }
}
this.#get().clearEditingMemory();
- if (listKeyRoot) {
- await Promise.all([
- mutate((key) => Array.isArray(key) && key[0] === listKeyRoot),
- mutate(userMemoryKeys.memoryDetail(layer, id)),
- ]);
- }
+ await Promise.all([revalidateList(), mutate(userMemoryKeys.memoryDetail(layer, id))]);
};
/**
@@ -435,31 +399,6 @@ export class BaseActionImpl {
mutate: sync.revalidate,
} as unknown as SWRResponse<RetrieveMemoryResult>;
};
-
- useInitIdentities = (isLogin: boolean): SWRResponse<any> => {
- return useClientDataSWRWithSync<IdentityForInjection[]>(
- isLogin ? userMemoryKeys.identities() : null,
- // Use dedicated API that filters for self identities only
- () => userMemoryService.queryIdentitiesForInjection({ limit: 25 }),
- {
- onSuccess: (data) => {
- if (!data) return;
-
- const fetchedAt = Date.now();
-
- this.#set(
- {
- globalIdentities: data,
- globalIdentitiesFetchedAt: fetchedAt,
- globalIdentitiesInit: true,
- },
- false,
- n('useInitIdentities/success', { count: data.length }),
- );
- },
- },
- );
- };
}
export type BaseAction = Pick<BaseActionImpl, keyof BaseActionImpl>;
diff --git a/src/store/userMemory/slices/base/projection.ts b/src/store/userMemory/slices/base/projection.ts
index 5c8455ae6a7..97e72ea27ea 100644
--- a/src/store/userMemory/slices/base/projection.ts
+++ b/src/store/userMemory/slices/base/projection.ts
@@ -1,10 +1,10 @@
import { type RetrieveMemoryParams, type RetrieveMemoryResult } from '@lobechat/types';
-import { defineReplica } from '@/libs/replica';
import { userMemoryKeys } from '@/libs/swr/keys';
import { type LayersEnum } from '@/types/userMemory';
import { userMemoryCacheKey } from '../../utils/cacheKey';
+import { defineUserMemoryReplica } from '../../utils/replica';
/**
* One query of the memory retrieve endpoint (`userMemoryService.retrieveMemory`).
@@ -13,16 +13,17 @@ import { userMemoryCacheKey } from '../../utils/cacheKey';
* (`memoryMap`) and the SWR key stay keyed exactly as before: any caller that
* revalidates `userMemory:retrieve` by its root keeps working.
*/
-export const userMemoryRetrieveResource = defineReplica<RetrieveMemoryParams, RetrieveMemoryResult>(
- {
- key: (params) => userMemoryCacheKey(params),
- name: 'userMemoryRetrieve',
- storage: 'indexedDB',
- // Adopt the existing SWR key so the legacy root-key revalidation still matches.
- syncKey: (params) => userMemoryKeys.retrieve(userMemoryCacheKey(params)),
- version: 1,
- },
-);
+export const userMemoryRetrieveResource = defineUserMemoryReplica<
+ RetrieveMemoryParams,
+ RetrieveMemoryResult
+>({
+ key: (params) => userMemoryCacheKey(params),
+ name: 'userMemoryRetrieve',
+ storage: 'indexedDB',
+ // Adopt the existing SWR key so the legacy root-key revalidation still matches.
+ syncKey: (params) => userMemoryKeys.retrieve(userMemoryCacheKey(params)),
+ version: 1,
+});
export interface MemoryDetailParams {
id: string;
@@ -47,7 +48,7 @@ export const memoryDetailKey = ({ id, layer }: MemoryDetailParams): string => `$
* for a memory the server no longer has, which removes the cached detail
* (`isMissing`).
*/
-export const userMemoryDetailResource = defineReplica<
+export const userMemoryDetailResource = defineUserMemoryReplica<
MemoryDetailParams,
MemoryDetailDisplay,
MemoryDetailDisplay | null
diff --git a/src/store/userMemory/slices/base/replica.test.ts b/src/store/userMemory/slices/base/replica.test.ts
index 200bbfb724b..f3dceb1e6c8 100644
--- a/src/store/userMemory/slices/base/replica.test.ts
+++ b/src/store/userMemory/slices/base/replica.test.ts
@@ -23,6 +23,7 @@ import { LayersEnum } from '@/types/userMemory';
import { initialState } from '../../initialState';
import { useUserMemoryStore } from '../../store';
+import { identityScopeOf } from '../../utils/replica';
import {
memoryDetailKey,
userMemoryDetailResource,
@@ -63,12 +64,15 @@ const wrapper = ({ children }: PropsWithChildren) =>
describe('userMemory base replica', () => {
const scopes = new Set<string>();
let scope = '';
+ /** Storage partition of userMemory replicas: the user, not the workspace. */
+ let rowScope = '';
let retrieveSpy: ReturnType<typeof vi.spyOn>;
let detailSpy: ReturnType<typeof vi.spyOn>;
const useScope = (next: string) => {
scope = next;
- scopes.add(next);
+ rowScope = identityScopeOf(scope);
+ scopes.add(rowScope);
vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
@@ -102,7 +106,7 @@ describe('userMemory base replica', () => {
preferences: [{ id: 'cached-1' } as never],
};
await userMemoryRetrieveResource.storage!.set(
- { queryKey: RETRIEVE_KEY, scope },
+ { queryKey: RETRIEVE_KEY, scope: rowScope },
{ data: cached, updatedAt: 1 },
);
retrieveSpy.mockImplementation(pending);
@@ -130,7 +134,7 @@ describe('userMemory base replica', () => {
await waitFor(async () => {
const row = await userMemoryRetrieveResource.storage!.get({
queryKey: RETRIEVE_KEY,
- scope,
+ scope: rowScope,
});
expect(row?.data).toEqual(server);
});
@@ -242,8 +246,8 @@ describe('userMemory base replica', () => {
vi.spyOn(memoryCRUDService, 'deleteAll').mockResolvedValue({} as never);
renderHook(() => null, { wrapper });
const storage = userMemoryRetrieveResource.storage!;
- const rowKey = { queryKey: RETRIEVE_KEY, scope };
- const indexRowKey = { queryKey: REPLICA_INDEX_KEY, scope };
+ const rowKey = { queryKey: RETRIEVE_KEY, scope: rowScope };
+ const indexRowKey = { queryKey: REPLICA_INDEX_KEY, scope: rowScope };
await storage.set(rowKey, { data: emptyResult(), updatedAt: 1 });
await storage.set(indexRowKey, { data: [RETRIEVE_KEY], updatedAt: 1 });
@@ -311,7 +315,10 @@ describe('userMemory base replica', () => {
);
await waitFor(async () =>
expect(
- await userMemoryRetrieveResource.storage!.get({ queryKey: RETRIEVE_KEY, scope }),
+ await userMemoryRetrieveResource.storage!.get({
+ queryKey: RETRIEVE_KEY,
+ scope: rowScope,
+ }),
).toBeDefined(),
);
@@ -325,7 +332,10 @@ describe('userMemory base replica', () => {
expect(useUserMemoryStore.getState().memoryMap).toEqual({});
expect(useUserMemoryStore.getState().memoryDetailMap).toEqual({});
expect(useUserMemoryStore.getState().memoryFetchedAtMap).toEqual({});
- const row = await userMemoryRetrieveResource.storage!.get({ queryKey: RETRIEVE_KEY, scope });
+ const row = await userMemoryRetrieveResource.storage!.get({
+ queryKey: RETRIEVE_KEY,
+ scope: rowScope,
+ });
expect(row).toBeUndefined();
});
@@ -340,7 +350,10 @@ describe('userMemory base replica', () => {
);
await waitFor(async () =>
expect(
- await userMemoryRetrieveResource.storage!.get({ queryKey: OTHER_RETRIEVE_KEY, scope }),
+ await userMemoryRetrieveResource.storage!.get({
+ queryKey: OTHER_RETRIEVE_KEY,
+ scope: rowScope,
+ }),
).toBeDefined(),
);
earlier.unmount();
@@ -354,7 +367,10 @@ describe('userMemory base replica', () => {
});
expect(
- await userMemoryRetrieveResource.storage!.get({ queryKey: OTHER_RETRIEVE_KEY, scope }),
+ await userMemoryRetrieveResource.storage!.get({
+ queryKey: OTHER_RETRIEVE_KEY,
+ scope: rowScope,
+ }),
).toBeUndefined();
// Requesting that query again paints nothing deleted while the fetch is pending.
diff --git a/src/store/userMemory/slices/context/action.ts b/src/store/userMemory/slices/context/action.ts
index 0570534a7c4..842aa82acb7 100644
--- a/src/store/userMemory/slices/context/action.ts
+++ b/src/store/userMemory/slices/context/action.ts
@@ -1,8 +1,5 @@
-import { uniqBy } from 'es-toolkit/compat';
-import { produce } from 'immer';
-import { useEffect } from 'react';
+import { type ContextMemorySimple, type UserMemoryItemSimple } from '@lobechat/types';
import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
import { type DisplayContextMemory } from '@/database/repositories/userMemory';
import { userMemoryKeys } from '@/libs/swr/keys';
@@ -11,166 +8,128 @@ import { type StoreSetter } from '@/store/types';
import { LayersEnum } from '@/types/userMemory';
import { setNamespace } from '@/utils/storeDebug';
-import { type UserMemoryStore } from '../../store';
-import { isMemoryListRequestCurrent } from '../utils/isMemoryListRequestCurrent';
-import { shouldSurfaceMemoryListError } from '../utils/shouldSurfaceMemoryListError';
+import { type UserMemoryStore, useUserMemoryStore } from '../../store';
+import { type MemoryListPageResult, MemoryQueryList } from '../utils/memoryQueryList';
+import {
+ CONTEXT_LIST_PAGE_SIZE,
+ type ContextListData,
+ type ContextListParams,
+ contextListResource,
+} from './projection';
const n = setNamespace('userMemory/context');
-export interface ContextQueryParams {
+export interface ContextQueryParams extends Partial<ContextListParams> {
page?: number;
- pageSize?: number;
- q?: string;
- sort?: 'capturedAt' | 'scoreImpact' | 'scoreUrgency';
}
-type ContextListRequest = ContextQueryParams & { page: number };
+/** Flat mirrors of one page set (`undefined` = the active query has no view yet). */
+const mirrorsOf = (data: ContextListData | undefined): Partial<UserMemoryStore> =>
+ data
+ ? {
+ contextListData: data,
+ contexts: data.items,
+ contextsHasMore: data.hasMore,
+ contextsInit: true,
+ contextsPage: data.currentPage + 1,
+ contextsTotal: data.total ?? data.items.length,
+ }
+ : {
+ contextListData: undefined,
+ contexts: [],
+ contextsHasMore: true,
+ contextsInit: false,
+ contextsPage: 1,
+ contextsTotal: 0,
+ };
+
+/**
+ * Flatten a `queryMemories` row into the display shape the context list
+ * renders. The endpoint returns `{ memory, context }`; the row is merged in the
+ * same order the previous slice did, with `source` pinned to `null`.
+ */
+const toDisplayContext = (item: UserMemoryItemSimple): DisplayContextMemory => {
+ const { memory, context } = item as ContextMemorySimple;
+ return { ...memory, ...context, source: null } as unknown as DisplayContextMemory;
+};
type Setter = StoreSetter<UserMemoryStore>;
export const createContextSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
new ContextActionImpl(set, get, _api);
+/**
+ * The user-memory context list: one `MemoryQueryList` (shared with the other
+ * offset-paged memory lists) behind the slice's long-standing action names.
+ */
export class ContextActionImpl {
- readonly #get: () => UserMemoryStore;
- readonly #set: Setter;
+ readonly #list: MemoryQueryList<ContextListParams, DisplayContextMemory, ContextListData>;
constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
void _api;
- this.#set = set;
- this.#get = get;
+ this.#list = new MemoryQueryList({
+ actionPrefix: n('contextList'),
+ activeKeyField: 'contextListKey',
+ entriesField: 'contextListEntries',
+ fetchPage: async (params, page) => {
+ const response = await userMemoryService.queryMemories({
+ layer: LayersEnum.Context,
+ page,
+ pageSize: params.pageSize,
+ q: params.q,
+ sort: params.sort,
+ });
+ return { items: response.items.map(toDisplayContext), total: response.total };
+ },
+ get,
+ mirror: mirrorsOf,
+ queryFields: ({ q, sort }) => ({ contextsQuery: q || undefined, contextsSort: sort }),
+ replicaField: 'contextListReplica',
+ resource: contextListResource,
+ rootKey: userMemoryKeys.contexts.root,
+ set,
+ useStore: (selector) => useUserMemoryStore(selector),
+ });
}
- deleteContext = async (id: string): Promise<void> => {
- await memoryCRUDService.deleteContext(id);
- // Reset list to refresh
- this.#get().resetContextsList({ q: this.#get().contextsQuery, sort: this.#get().contextsSort });
- };
+ /** Delete one context: optimistic, then the offset repair (see `OffsetListPager`). */
+ deleteContext = (id: string): Promise<void> =>
+ this.#list.delete(id, () => memoryCRUDService.deleteContext(id));
- loadMoreContexts = (): void => {
- const { contextsPage, contextsTotal, contexts } = this.#get();
- if (contexts.length < (contextsTotal || 0)) {
- this.#set(
- produce((draft) => {
- draft.contextsPage = contextsPage + 1;
- }),
- false,
- n('loadMoreContexts'),
- );
- }
- };
+ /** Purge for "delete all memories" (every query, memory + IndexedDB). */
+ internal_clearContextList = (user?: string): Promise<boolean> => this.#list.clear(user);
- internal_acceptContextsList = (data: any, request: ContextListRequest): void => {
- const state = this.#get();
- if (
- !isMemoryListRequestCurrent(
- { page: state.contextsPage, q: state.contextsQuery, sort: state.contextsSort },
- { page: request.page, q: request.q, sort: request.sort },
- )
- )
- return;
-
- this.#set(
- produce((draft) => {
- draft.contextsSearchError = undefined;
- draft.contextsSearchLoading = false;
- draft.contextsInit = true;
- draft.contextsTotal = data.total;
-
- const transformedItems: DisplayContextMemory[] = data.items.map((item: any) => ({
- ...item.memory,
- ...item.context,
- source: null,
- }));
-
- if (request.page === 1) {
- draft.contexts = uniqBy(transformedItems, 'id');
- } else {
- draft.contexts = uniqBy([...draft.contexts, ...transformedItems], 'id');
- }
-
- draft.contextsHasMore = data.items.length >= (request.pageSize || 20);
- }),
- false,
- n('internal_acceptContextsList'),
- );
+ /** Confirmed edit of one context in every loaded and persisted query. */
+ internal_updateContextEntity = (
+ id: string,
+ fn: (item: DisplayContextMemory) => DisplayContextMemory,
+ ): void => {
+ this.#list.updateEntity(id, fn);
};
- internal_failContextsList = (error: unknown, request: ContextListRequest): void => {
- const state = this.#get();
- if (
- !isMemoryListRequestCurrent(
- { page: state.contextsPage, q: state.contextsQuery, sort: state.contextsSort },
- { page: request.page, q: request.q, sort: request.sort },
- )
- )
- return;
-
- const shouldSurfaceError = shouldSurfaceMemoryListError({
- initialized: state.contextsInit,
- page: request.page,
- resetting: state.contextsSearchLoading,
- });
-
- this.#set(
- produce((draft) => {
- if (shouldSurfaceError) draft.contextsSearchError = error;
- draft.contextsSearchLoading = false;
- }),
- false,
- n('internal_failContextsList'),
- );
+ /** Append the next page of the query on screen. */
+ loadMoreContexts = (): void => {
+ void this.#list.loadMore();
};
+ /** Seed the persisted head page of a query before its route paints. */
+ preHydrateContexts = (query?: Omit<ContextQueryParams, 'page' | 'pageSize'>): Promise<boolean> =>
+ this.#list.preHydrate({ ...query, pageSize: CONTEXT_LIST_PAGE_SIZE, q: query?.q || undefined });
+
+ /** Point the list at another search / sort (no page set is dropped). */
resetContextsList = (params?: Omit<ContextQueryParams, 'page' | 'pageSize'>): void => {
- this.#set(
- produce((draft) => {
- draft.contexts = [];
- draft.contextsPage = 1;
- draft.contextsQuery = params?.q;
- draft.contextsSearchError = undefined;
- draft.contextsSearchLoading = true;
- draft.contextsSort = params?.sort;
- }),
- false,
- n('resetContextsList'),
- );
+ this.#list.select({ ...params, q: params?.q || undefined });
};
- /**
- * Hydrate the store from SWR's rendered state because deduped cache hits do not invoke SWR's
- * request lifecycle callbacks.
- */
- useFetchContexts = (params: ContextQueryParams): SWRResponse<any> => {
- const page = params.page ?? 1;
- const response = useSWR(
- userMemoryKeys.contexts(params),
- async () => {
- const result = await userMemoryService.queryMemories({
- layer: LayersEnum.Context,
- page: params.page,
- pageSize: params.pageSize,
- q: params.q,
- sort: params.sort,
- });
-
- return result;
- },
- {
- revalidateOnFocus: false,
- },
- );
-
- useEffect(() => {
- if (response.data !== undefined)
- this.internal_acceptContextsList(response.data, { ...params, page });
- }, [page, params.pageSize, params.q, params.sort, response.data]);
-
- useEffect(() => {
- if (response.error !== undefined)
- this.internal_failContextsList(response.error, { ...params, page });
- }, [page, params.pageSize, params.q, params.sort, response.error]);
-
- return response;
+ /** Fetch orchestration for the context list page (see `MemoryQueryList.useFetch`). */
+ useFetchContexts = (
+ params: ContextQueryParams,
+ ): SWRResponse<MemoryListPageResult<DisplayContextMemory>> => {
+ const { page: _page, ...query } = params;
+ return this.#list.useFetch({
+ ...query,
+ pageSize: params.pageSize ?? CONTEXT_LIST_PAGE_SIZE,
+ q: params.q || undefined,
+ });
};
}
diff --git a/src/store/userMemory/slices/context/index.ts b/src/store/userMemory/slices/context/index.ts
index ba0739d5f2d..2206a6aaaa3 100644
--- a/src/store/userMemory/slices/context/index.ts
+++ b/src/store/userMemory/slices/context/index.ts
@@ -1,2 +1,3 @@
export { type ContextAction, createContextSlice } from './action';
export { contextInitialState, type ContextSliceState } from './initialState';
+export type { ContextListData, ContextListParams, ContextListSort } from './projection';
diff --git a/src/store/userMemory/slices/context/initialState.ts b/src/store/userMemory/slices/context/initialState.ts
index 3c9ccf2cf38..8009e0a261c 100644
--- a/src/store/userMemory/slices/context/initialState.ts
+++ b/src/store/userMemory/slices/context/initialState.ts
@@ -1,14 +1,36 @@
import { type DisplayContextMemory } from '@/database/repositories/userMemory';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import { memoryListKey } from '../../utils/replica';
+import { type ContextListData, type ContextListSort } from './projection';
+
+/**
+ * The context list is a `@lobechat/replica` paged resource with one page set
+ * per search / sort (`contextListEntries`). The long-standing flat fields
+ * (`contextListData`, `contexts`, `contextsTotal`, `contextsPage`,
+ * `contextsHasMore`, `contextsInit`) mirror the active query's entry so every
+ * existing consumer keeps reading the place it always has.
+ */
export interface ContextSliceState {
+ /** View of the active query's page set. Mirror of `contextListEntries[contextListKey]`. */
+ contextListData?: ContextListData;
+ /** Canonical replica views, one page set per query. Engine-owned. */
+ contextListEntries: Record<string, ContextListData>;
+ /** Entry key of the query on screen (see `memoryListKey`). */
+ contextListKey: string;
+ /** Local-first bookkeeping for `contextListEntries`. */
+ contextListReplica: ReplicaState<ContextListData>;
+ /** Rows of the active page set. Mirror of `contextListData.items`. */
contexts: DisplayContextMemory[];
+ /** Mirror of `contextListData.hasMore`. */
contextsHasMore: boolean;
+ /** Whether the active query has a view (persisted row hydrated or a page landed). */
contextsInit: boolean;
+ /** Mirror of `contextListData.currentPage + 1`. */
contextsPage: number;
contextsQuery?: string;
- contextsSearchError?: unknown;
- contextsSearchLoading?: boolean;
- contextsSort?: 'capturedAt' | 'scoreImpact' | 'scoreUrgency';
+ contextsSort?: ContextListSort;
+ /** Mirror of `contextListData.total`. */
contextsTotal: number;
}
@@ -18,8 +40,10 @@ export const contextInitialState: ContextSliceState = {
contextsInit: false,
contextsPage: 1,
contextsQuery: undefined,
- contextsSearchError: undefined,
- contextsSearchLoading: undefined,
contextsSort: undefined,
contextsTotal: 0,
+ contextListData: undefined,
+ contextListEntries: {},
+ contextListKey: memoryListKey({}),
+ contextListReplica: createReplicaState<ContextListData>(),
};
diff --git a/src/store/userMemory/slices/context/projection.ts b/src/store/userMemory/slices/context/projection.ts
new file mode 100644
index 00000000000..26860cfd281
--- /dev/null
+++ b/src/store/userMemory/slices/context/projection.ts
@@ -0,0 +1,63 @@
+import { type DisplayContextMemory } from '@/database/repositories/userMemory';
+import { type ReplicaPagedData } from '@/libs/replica';
+import { userMemoryKeys } from '@/libs/swr/keys';
+
+import {
+ defineUserMemoryPagedReplica,
+ MAX_RECENT_MEMORY_QUERIES,
+ memoryListKey,
+} from '../../utils/replica';
+
+/** Server-side ordering of the context list. */
+export type ContextListSort = 'capturedAt' | 'scoreImpact' | 'scoreUrgency';
+
+/** Page size the memory context list asks for when the caller does not name one. */
+export const CONTEXT_LIST_PAGE_SIZE = 12;
+
+/**
+ * Query of one page set. `page` is NOT here β€” it is the paging cursor, owned by
+ * the replica. Everything but `pageSize` is the entry key (`memoryListKey`).
+ */
+export interface ContextListParams {
+ pageSize: number;
+ q?: string;
+ sort?: ContextListSort;
+}
+
+/** One page set of the context list, tagged with the query it answers. */
+export interface ContextListData extends ReplicaPagedData<DisplayContextMemory, number> {
+ q?: string;
+ sort?: ContextListSort;
+}
+
+/**
+ * The user-memory context list: a local-first, offset-paged replica with one
+ * entry per search / sort (see `MemoryQueryList`). Each query paints its
+ * persisted head page on the first frame and the network confirms it.
+ *
+ * It adopts the long-standing `userMemory:contexts` SWR key as its sync key, so
+ * code that revalidates the list by its key root (`purgeAllMemories`,
+ * `updateMemory`) reaches it.
+ */
+export const contextListResource = defineUserMemoryPagedReplica<
+ ContextListParams,
+ DisplayContextMemory,
+ number,
+ ContextListData
+>({
+ key: memoryListKey,
+ name: 'contextList',
+ paging: {
+ direction: 'forward',
+ getId: (item) => item.id,
+ mode: 'offset',
+ // A reload repaints what the first network page would show, never a stale tail.
+ persist: { pages: 1 },
+ },
+ // Bounded: least recently used queries leave IndexedDB and memory together;
+ // the query on screen is pinned by its mounted `useSync`.
+ persist: { maxEntries: MAX_RECENT_MEMORY_QUERIES },
+ storage: 'indexedDB',
+ syncKey: (params) => userMemoryKeys.contexts(params),
+ version: 1,
+});
diff --git a/src/store/userMemory/slices/experience/action.ts b/src/store/userMemory/slices/experience/action.ts
index eb89bff8327..b2a03e0a688 100644
--- a/src/store/userMemory/slices/experience/action.ts
+++ b/src/store/userMemory/slices/experience/action.ts
@@ -1,184 +1,128 @@
-import { type ExperienceListResult } from '@lobechat/types';
-import { uniqBy } from 'es-toolkit/compat';
-import { produce } from 'immer';
-import { useEffect } from 'react';
+import { type ExperienceListItem } from '@lobechat/types';
import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
import { userMemoryKeys } from '@/libs/swr/keys';
import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
-import { type UserMemoryStore } from '../../store';
-import { isMemoryListRequestCurrent } from '../utils/isMemoryListRequestCurrent';
-import { shouldSurfaceMemoryListError } from '../utils/shouldSurfaceMemoryListError';
+import { type UserMemoryStore, useUserMemoryStore } from '../../store';
+import { type MemoryListPageResult, MemoryQueryList } from '../utils/memoryQueryList';
+import {
+ EXPERIENCE_LIST_PAGE_SIZE,
+ type ExperienceListData,
+ type ExperienceListParams,
+ experienceListResource,
+} from './projection';
const n = setNamespace('userMemory/experience');
-export interface ExperienceQueryParams {
+export interface ExperienceQueryParams extends Partial<ExperienceListParams> {
page?: number;
- pageSize?: number;
- q?: string;
- sort?: 'capturedAt' | 'scoreConfidence';
}
-type ExperienceListRequest = ExperienceQueryParams & { page: number };
+/** Flat mirrors of one page set (`undefined` = the active query has no view yet). */
+const mirrorsOf = (data: ExperienceListData | undefined): Partial<UserMemoryStore> =>
+ data
+ ? {
+ experienceListData: data,
+ experiences: data.items,
+ experiencesHasMore: data.hasMore,
+ experiencesInit: true,
+ experiencesPage: data.currentPage + 1,
+ experiencesTotal: data.total ?? data.items.length,
+ }
+ : {
+ experienceListData: undefined,
+ experiences: [],
+ experiencesHasMore: true,
+ experiencesInit: false,
+ experiencesPage: 1,
+ experiencesTotal: 0,
+ };
type Setter = StoreSetter<UserMemoryStore>;
export const createExperienceSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
new ExperienceActionImpl(set, get, _api);
+/**
+ * The user-memory experience list: one `MemoryQueryList` (shared with the other
+ * offset-paged memory lists) behind the slice's long-standing action names.
+ */
export class ExperienceActionImpl {
- readonly #get: () => UserMemoryStore;
- readonly #set: Setter;
+ readonly #list: MemoryQueryList<ExperienceListParams, ExperienceListItem, ExperienceListData>;
constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
void _api;
- this.#set = set;
- this.#get = get;
+ this.#list = new MemoryQueryList({
+ actionPrefix: n('experienceList'),
+ activeKeyField: 'experienceListKey',
+ entriesField: 'experienceListEntries',
+ fetchPage: async (params, page) => {
+ const response = await userMemoryService.queryExperiences({
+ page,
+ pageSize: params.pageSize,
+ q: params.q,
+ sort: params.sort,
+ });
+ return { items: response.items, total: response.total };
+ },
+ get,
+ mirror: mirrorsOf,
+ queryFields: ({ q, sort }) => ({ experiencesQuery: q || undefined, experiencesSort: sort }),
+ replicaField: 'experienceListReplica',
+ resource: experienceListResource,
+ rootKey: userMemoryKeys.experiences.root,
+ set,
+ useStore: (selector) => useUserMemoryStore(selector),
+ });
}
- deleteExperience = async (id: string): Promise<void> => {
- await memoryCRUDService.deleteExperience(id);
- // Reset list to refresh
- this.#get().resetExperiencesList({
- q: this.#get().experiencesQuery,
- sort: this.#get().experiencesSort,
- });
- };
+ /** Delete one experience: optimistic, then the offset repair (see `OffsetListPager`). */
+ deleteExperience = (id: string): Promise<void> =>
+ this.#list.delete(id, () => memoryCRUDService.deleteExperience(id));
- loadMoreExperiences = (): void => {
- const { experiencesPage, experiencesTotal, experiences } = this.#get();
- if (experiences.length < (experiencesTotal || 0)) {
- this.#set(
- produce((draft) => {
- draft.experiencesPage = experiencesPage + 1;
- }),
- false,
- n('loadMoreExperiences'),
- );
- }
- };
+ /** Purge for "delete all memories" (every query, memory + IndexedDB). */
+ internal_clearExperienceList = (user?: string): Promise<boolean> => this.#list.clear(user);
- internal_acceptExperiencesList = (
- data: ExperienceListResult,
- request: ExperienceListRequest,
+ /** Confirmed edit of one experience in every loaded and persisted query. */
+ internal_updateExperienceEntity = (
+ id: string,
+ fn: (item: ExperienceListItem) => ExperienceListItem,
): void => {
- const state = this.#get();
- if (
- !isMemoryListRequestCurrent(
- {
- page: state.experiencesPage,
- q: state.experiencesQuery,
- sort: state.experiencesSort,
- },
- { page: request.page, q: request.q, sort: request.sort },
- )
- )
- return;
-
- this.#set(
- produce((draft) => {
- draft.experiencesSearchError = undefined;
- draft.experiencesSearchLoading = false;
- draft.experiencesTotal = data.total;
-
- if (!draft.experiencesInit) {
- draft.experiencesInit = true;
- }
-
- if (request.page === 1) {
- draft.experiences = uniqBy(data.items, 'id');
- } else {
- draft.experiences = uniqBy([...draft.experiences, ...data.items], 'id');
- }
-
- draft.experiencesHasMore = data.items.length >= (request.pageSize || 20);
- }),
- false,
- n('internal_acceptExperiencesList'),
- );
+ this.#list.updateEntity(id, fn);
};
- internal_failExperiencesList = (error: unknown, request: ExperienceListRequest): void => {
- const state = this.#get();
- if (
- !isMemoryListRequestCurrent(
- {
- page: state.experiencesPage,
- q: state.experiencesQuery,
- sort: state.experiencesSort,
- },
- { page: request.page, q: request.q, sort: request.sort },
- )
- )
- return;
-
- const shouldSurfaceError = shouldSurfaceMemoryListError({
- initialized: state.experiencesInit,
- page: request.page,
- resetting: state.experiencesSearchLoading,
- });
-
- this.#set(
- produce((draft) => {
- if (shouldSurfaceError) draft.experiencesSearchError = error;
- draft.experiencesSearchLoading = false;
- }),
- false,
- n('internal_failExperiencesList'),
- );
+ /** Append the next page of the query on screen. */
+ loadMoreExperiences = (): void => {
+ void this.#list.loadMore();
};
+ /** Seed the persisted head page of a query before its route paints. */
+ preHydrateExperiences = (
+ query?: Omit<ExperienceQueryParams, 'page' | 'pageSize'>,
+ ): Promise<boolean> =>
+ this.#list.preHydrate({
+ ...query,
+ pageSize: EXPERIENCE_LIST_PAGE_SIZE,
+ q: query?.q || undefined,
+ });
+
+ /** Point the list at another search / sort (no page set is dropped). */
resetExperiencesList = (params?: Omit<ExperienceQueryParams, 'page' | 'pageSize'>): void => {
- this.#set(
- produce((draft) => {
- draft.experiences = [];
- draft.experiencesPage = 1;
- draft.experiencesQuery = params?.q;
- draft.experiencesSearchError = undefined;
- draft.experiencesSearchLoading = true;
- draft.experiencesSort = params?.sort;
- }),
- false,
- n('resetExperiencesList'),
- );
+ this.#list.select({ ...params, q: params?.q || undefined });
};
- /**
- * Hydrate the store from SWR's rendered state because deduped cache hits do not invoke SWR's
- * request lifecycle callbacks.
- */
- useFetchExperiences = (params: ExperienceQueryParams): SWRResponse<ExperienceListResult> => {
- const page = params.page ?? 1;
- const response = useSWR(
- userMemoryKeys.experiences(params),
- async () => {
- // Use the new dedicated queryExperiences API
- return userMemoryService.queryExperiences({
- page: params.page,
- pageSize: params.pageSize,
- q: params.q,
- sort: params.sort,
- });
- },
- {
- revalidateOnFocus: false,
- },
- );
-
- useEffect(() => {
- if (response.data !== undefined)
- this.internal_acceptExperiencesList(response.data, { ...params, page });
- }, [page, params.pageSize, params.q, params.sort, response.data]);
-
- useEffect(() => {
- if (response.error !== undefined)
- this.internal_failExperiencesList(response.error, { ...params, page });
- }, [page, params.pageSize, params.q, params.sort, response.error]);
-
- return response;
+ /** Fetch orchestration for the experience list page (see `MemoryQueryList.useFetch`). */
+ useFetchExperiences = (
+ params: ExperienceQueryParams,
+ ): SWRResponse<MemoryListPageResult<ExperienceListItem>> => {
+ const { page: _page, ...query } = params;
+ return this.#list.useFetch({
+ ...query,
+ pageSize: params.pageSize ?? EXPERIENCE_LIST_PAGE_SIZE,
+ q: params.q || undefined,
+ });
};
}
diff --git a/src/store/userMemory/slices/experience/index.ts b/src/store/userMemory/slices/experience/index.ts
index cddb823cae1..dd9263c7101 100644
--- a/src/store/userMemory/slices/experience/index.ts
+++ b/src/store/userMemory/slices/experience/index.ts
@@ -1,2 +1,3 @@
export { createExperienceSlice, type ExperienceAction } from './action';
export { experienceInitialState, type ExperienceSliceState } from './initialState';
+export type { ExperienceListData, ExperienceListParams, ExperienceListSort } from './projection';
diff --git a/src/store/userMemory/slices/experience/initialState.ts b/src/store/userMemory/slices/experience/initialState.ts
index 2b3f463e056..b22dde334fc 100644
--- a/src/store/userMemory/slices/experience/initialState.ts
+++ b/src/store/userMemory/slices/experience/initialState.ts
@@ -1,14 +1,37 @@
import { type ExperienceListItem } from '@lobechat/types';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import { memoryListKey } from '../../utils/replica';
+import { type ExperienceListData, type ExperienceListSort } from './projection';
+
+/**
+ * The experience list is a `@lobechat/replica` paged resource with one page set
+ * per search / sort (`experienceListEntries`). The long-standing flat fields
+ * (`experienceListData`, `experiences`, `experiencesTotal`, `experiencesPage`,
+ * `experiencesHasMore`, `experiencesInit`) mirror the active query's entry so every
+ * existing consumer keeps reading the place it always has.
+ */
export interface ExperienceSliceState {
+ /** View of the active query's page set. Mirror of `experienceListEntries[experienceListKey]`. */
+ experienceListData?: ExperienceListData;
+ /** Canonical replica views, one page set per query. Engine-owned. */
+ experienceListEntries: Record<string, ExperienceListData>;
+ /** Entry key of the query on screen (see `memoryListKey`). */
+ experienceListKey: string;
+ /** Local-first bookkeeping for `experienceListEntries`. */
+ experienceListReplica: ReplicaState<ExperienceListData>;
+ /** Rows of the active page set. Mirror of `experienceListData.items`. */
experiences: ExperienceListItem[];
+ /** Mirror of `experienceListData.hasMore`. */
experiencesHasMore: boolean;
+ /** Whether the active query has a view (persisted row hydrated or a page landed). */
experiencesInit: boolean;
+ /** Mirror of `experienceListData.currentPage + 1`. */
experiencesPage: number;
experiencesQuery?: string;
- experiencesSearchError?: unknown;
- experiencesSearchLoading?: boolean;
- experiencesSort?: 'capturedAt' | 'scoreConfidence';
+ experiencesSort?: ExperienceListSort;
+ /** Mirror of `experienceListData.total`. */
experiencesTotal: number;
}
@@ -18,8 +41,10 @@ export const experienceInitialState: ExperienceSliceState = {
experiencesInit: false,
experiencesPage: 1,
experiencesQuery: undefined,
- experiencesSearchError: undefined,
- experiencesSearchLoading: undefined,
experiencesSort: undefined,
experiencesTotal: 0,
+ experienceListData: undefined,
+ experienceListEntries: {},
+ experienceListKey: memoryListKey({}),
+ experienceListReplica: createReplicaState<ExperienceListData>(),
};
diff --git a/src/store/userMemory/slices/experience/projection.ts b/src/store/userMemory/slices/experience/projection.ts
new file mode 100644
index 00000000000..574b1f186b9
--- /dev/null
+++ b/src/store/userMemory/slices/experience/projection.ts
@@ -0,0 +1,63 @@
+import { type ExperienceListItem, type ExperienceListSort } from '@lobechat/types';
+
+import { type ReplicaPagedData } from '@/libs/replica';
+import { userMemoryKeys } from '@/libs/swr/keys';
+
+import {
+ defineUserMemoryPagedReplica,
+ MAX_RECENT_MEMORY_QUERIES,
+ memoryListKey,
+} from '../../utils/replica';
+
+export type { ExperienceListSort };
+
+/** Page size the memory experience list asks for when the caller does not name one. */
+export const EXPERIENCE_LIST_PAGE_SIZE = 12;
+
+/**
+ * Query of one page set. `page` is NOT here β€” it is the paging cursor, owned by
+ * the replica. Everything but `pageSize` is the entry key (`memoryListKey`).
+ */
+export interface ExperienceListParams {
+ pageSize: number;
+ q?: string;
+ sort?: ExperienceListSort;
+}
+
+/** One page set of the experience list, tagged with the query it answers. */
+export interface ExperienceListData extends ReplicaPagedData<ExperienceListItem, number> {
+ q?: string;
+ sort?: ExperienceListSort;
+}
+
+/**
+ * The user-memory experience list: a local-first, offset-paged replica with one
+ * entry per search / sort (see `MemoryQueryList`). Each query paints its
+ * persisted head page on the first frame and the network confirms it.
+ *
+ * It adopts the long-standing `userMemory:experiences` SWR key as its sync key, so
+ * code that revalidates the list by its key root (`purgeAllMemories`,
+ * `updateMemory`) reaches it.
+ */
+export const experienceListResource = defineUserMemoryPagedReplica<
+ ExperienceListParams,
+ ExperienceListItem,
+ number,
+ ExperienceListData
+>({
+ key: memoryListKey,
+ name: 'experienceList',
+ paging: {
+ direction: 'forward',
+ getId: (item) => item.id,
+ mode: 'offset',
+ // A reload repaints what the first network page would show, never a stale tail.
+ persist: { pages: 1 },
+ },
+ // Bounded: least recently used queries leave IndexedDB and memory together;
+ // the query on screen is pinned by its mounted `useSync`.
+ persist: { maxEntries: MAX_RECENT_MEMORY_QUERIES },
+ storage: 'indexedDB',
+ syncKey: (params) => userMemoryKeys.experiences(params),
+ version: 1,
+});
diff --git a/src/store/userMemory/slices/home/action.ts b/src/store/userMemory/slices/home/action.ts
index b3b65fbdedc..98e6f047c14 100644
--- a/src/store/userMemory/slices/home/action.ts
+++ b/src/store/userMemory/slices/home/action.ts
@@ -1,70 +1,201 @@
+import isEqual from 'fast-deep-equal';
+import { useMemo } from 'react';
import { type SWRResponse } from 'swr';
+import { type StoreApi, useStore } from 'zustand';
import { type QueryIdentityRolesResult } from '@/database/models/userMemory';
-import { useClientDataSWR } from '@/libs/swr';
+import { createReplicaSlice, type ReplicaLens } from '@/libs/replica';
+import { mutate } from '@/libs/swr';
import { userMemoryKeys } from '@/libs/swr/keys';
import { userMemoryService } from '@/services/userMemory';
import { type StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
-import { type PersonaData } from '../../initialState';
+// Type-only: the runtime store is reached through the `StoreApi` the store
+// passes to the slice, so this module never imports the store at runtime β€” the
+// store imports the slice, and a runtime import back would be a cycle.
import { type UserMemoryStore } from '../../store';
+import { clearUserReplicas } from '../../utils/replica';
+import {
+ type HomeReplicaParams,
+ IDENTITY_ROLES_KEY,
+ IDENTITY_ROLES_QUERY,
+ type IdentityRolesData,
+ identityRolesResource,
+ PERSONA_KEY,
+ type PersonaData,
+ type PersonaReplicaData,
+ personaResource,
+} from './projection';
-const n = (namespace: string) => namespace;
+const n = setNamespace('userMemory/home');
+
+/** Both home resources are one fixed entry per scope. */
+const HOME_PARAMS: HomeReplicaParams = {};
+
+/**
+ * The persona keeps its long-standing flat fields (`persona`, `personaInit`) as
+ * derived mirrors of the `personaData` replica view, so no consumer changes.
+ * The canonical value lives in `personaData` and is persisted to IndexedDB by
+ * the replica engine.
+ */
+const personaLens: ReplicaLens<UserMemoryStore, PersonaReplicaData> = {
+ clear: () => ({ persona: undefined, personaData: undefined, personaInit: false }),
+ get: (state) => state.personaData,
+ keys: (state) => (state.personaData ? [PERSONA_KEY] : []),
+ set: (_state, _key, data) =>
+ data
+ ? { persona: data.persona ?? undefined, personaData: data, personaInit: true }
+ : { persona: undefined, personaData: undefined, personaInit: false },
+};
+
+/**
+ * The identity roles + tags aggregate keeps its long-standing flat fields
+ * (`roles`, `tags`, `tagsInit`) as derived mirrors of the `identityRolesData`
+ * replica view, so no consumer changes. The server field `role` is renamed to
+ * `tag` for `roles`, exactly as the previous slice did.
+ */
+const identityRolesLens: ReplicaLens<UserMemoryStore, IdentityRolesData> = {
+ clear: () => ({ identityRolesData: undefined, roles: [], tags: [], tagsInit: false }),
+ get: (state) => state.identityRolesData,
+ keys: (state) => (state.identityRolesData ? [IDENTITY_ROLES_KEY] : []),
+ set: (_state, _key, data) =>
+ data
+ ? {
+ identityRolesData: data,
+ roles: data.roles.map((item) => ({ count: item.count, tag: item.role })),
+ tags: data.tags,
+ tagsInit: true,
+ }
+ : { identityRolesData: undefined, roles: [], tags: [], tagsInit: false },
+};
+
+/** An unchanged response must not repaint its readers. */
+const mergeUnchanged = <T>(incoming: T, confirmed: T | undefined) =>
+ isEqual(incoming, confirmed) ? undefined : incoming;
type Setter = StoreSetter<UserMemoryStore>;
-export const createHomeSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
- new HomeActionImpl(set, get, _api);
+export const createHomeSlice = (
+ set: Setter,
+ get: () => UserMemoryStore,
+ api: StoreApi<UserMemoryStore>,
+) => new HomeActionImpl(set, get, api);
+/**
+ * The memory home reads: the persona and the identity roles + tags aggregate.
+ *
+ * Server state is two `@lobechat/replica` single-value resources (`personaData`
+ * and `identityRolesData`): the persisted copy paints on the first frame and
+ * the network confirms it in the background. The domain store exposes the same
+ * flat fields and the same action surface it always has, backed by the replica
+ * views, so the memory home page and its components are untouched.
+ */
export class HomeActionImpl {
- readonly #set: Setter;
+ readonly #api: StoreApi<UserMemoryStore>;
+ readonly #identityRoles;
+ readonly #persona;
- constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
- void _api;
- this.#set = set;
- void get;
+ constructor(set: Setter, get: () => UserMemoryStore, api: StoreApi<UserMemoryStore>) {
+ this.#api = api;
+ this.#persona = createReplicaSlice(personaResource, {
+ actionPrefix: n('persona'),
+ fetcher: () => this.#fetchPersona(),
+ get,
+ merge: (incoming, confirmed) => mergeUnchanged(incoming, confirmed),
+ set,
+ stateKey: 'personaReplica',
+ view: personaLens,
+ });
+ this.#identityRoles = createReplicaSlice(identityRolesResource, {
+ actionPrefix: n('identityRoles'),
+ fetcher: () => this.#fetchIdentityRoles(),
+ get,
+ merge: (incoming, confirmed) => mergeUnchanged(incoming, confirmed),
+ set,
+ stateKey: 'identityRolesReplica',
+ view: identityRolesLens,
+ });
}
+ #fetchIdentityRoles = async (): Promise<IdentityRolesData> =>
+ userMemoryService.queryIdentityRoles({ ...IDENTITY_ROLES_QUERY });
+
+ /** The persona read returns `null` when the user has none; wrap it so the value is never missing. */
+ #fetchPersona = async (): Promise<PersonaReplicaData> => ({
+ persona: await userMemoryService.getPersona(),
+ });
+
+ /**
+ * Wipe both home replicas after "delete all memories": memory, every
+ * persisted row and reads already in flight (`clear()`), then seed the
+ * server-confirmed empty values (no persona, no roles/tags) so the home shows
+ * its empty state right away β€” mounted or not β€” and a reload paints the same
+ * instead of the purged data.
+ */
+ internal_clearHomeReplicas = async (user?: string): Promise<boolean> => {
+ const active = user === undefined || user === personaResource.scope.get();
+ const cleared = await clearUserReplicas(user, this.#persona, this.#identityRoles);
+ if (active) {
+ this.#persona.update(PERSONA_KEY, () => ({ persona: null }));
+ this.#identityRoles.update(IDENTITY_ROLES_KEY, () => ({ roles: [], tags: [] }));
+ }
+ return cleared;
+ };
+
+ /**
+ * Drop the persona locally (persisted), then re-read server truth (now
+ * `null`). The persona delete flow calls this after the DELETE succeeded, so
+ * the section disappears immediately instead of waiting for a network round
+ * trip. The re-read is best-effort: the deletion already happened, so a
+ * failed GET must not surface as a failed delete β€” the next sync confirms it.
+ */
+ refreshPersona = async (): Promise<void> => {
+ this.#persona.update(PERSONA_KEY, () => ({ persona: null }), { persist: true });
+ // The replica adopts `userMemory:persona` as its sync key, so revalidating
+ // that key is what drives the network sync.
+ try {
+ await mutate(userMemoryKeys.persona());
+ } catch (error) {
+ console.error('[userMemory] failed to re-read the persona after deleting it', error);
+ }
+ };
+
+ /**
+ * Fetch orchestration for the memory persona. Returns an `SWRResponse`-shaped
+ * result β€” `data` reads the replica view β€” so the existing consumers are
+ * untouched; the value lands in the store mirror, never in this return value.
+ */
useFetchPersona = (isLogin = true): SWRResponse<PersonaData | null> => {
- return useClientDataSWR(
- isLogin ? userMemoryKeys.persona() : null,
- () => userMemoryService.getPersona(),
- {
- onSuccess: (data: PersonaData | null | undefined) => {
- this.#set(
- {
- persona: data ?? undefined,
- personaInit: true,
- },
- false,
- n('useFetchPersona/onSuccess'),
- );
- },
- },
- );
+ const sync = this.#persona.useSync(HOME_PARAMS, { enabled: isLogin });
+ const view = useStore(this.#api, (state) => state.personaData);
+ const data = useMemo<PersonaData | null | undefined>(() => view?.persona, [view]);
+
+ return {
+ data,
+ error: sync.error,
+ isLoading: isLogin && !view && (sync.isValidating || !sync.isHydrated),
+ isValidating: sync.isValidating,
+ mutate: sync.revalidate,
+ } as unknown as SWRResponse<PersonaData | null>;
};
+ /**
+ * Fetch orchestration for the identity roles + tags aggregate. Returns an
+ * `SWRResponse`-shaped result so the existing consumers are untouched; the
+ * value lands in the store mirrors, never in this return value.
+ */
useFetchTags = (): SWRResponse<QueryIdentityRolesResult> => {
- return useClientDataSWR(
- userMemoryKeys.tags(),
- () =>
- userMemoryService.queryIdentityRoles({
- page: 1,
- size: 64,
- }),
- {
- onSuccess: (data: QueryIdentityRolesResult | undefined) => {
- this.#set(
- {
- roles: data?.roles.map((item) => ({ count: item.count, tag: item.role })) || [],
- tags: data?.tags || [],
- tagsInit: true,
- },
- false,
- n('useFetchTags/onSuccess'),
- );
- },
- },
- );
+ const sync = this.#identityRoles.useSync(HOME_PARAMS);
+ const view = useStore(this.#api, (state) => state.identityRolesData);
+ const data = useMemo<IdentityRolesData | undefined>(() => view, [view]);
+
+ return {
+ data,
+ error: sync.error,
+ isLoading: !view && (sync.isValidating || !sync.isHydrated),
+ isValidating: sync.isValidating,
+ mutate: sync.revalidate,
+ } as unknown as SWRResponse<QueryIdentityRolesResult>;
};
}
diff --git a/src/store/userMemory/slices/home/index.ts b/src/store/userMemory/slices/home/index.ts
index 2c0622fbb9c..813e1188eaa 100644
--- a/src/store/userMemory/slices/home/index.ts
+++ b/src/store/userMemory/slices/home/index.ts
@@ -1 +1,2 @@
export * from './action';
+export * from './projection';
diff --git a/src/store/userMemory/slices/home/initialState.ts b/src/store/userMemory/slices/home/initialState.ts
new file mode 100644
index 00000000000..72268fed896
--- /dev/null
+++ b/src/store/userMemory/slices/home/initialState.ts
@@ -0,0 +1,51 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import { type IdentityRolesData, type PersonaData, type PersonaReplicaData } from './projection';
+
+/**
+ * The memory home reads (persona + identity roles/tags) are two
+ * `@lobechat/replica` single-value resources. Their canonical values live in
+ * `personaData` / `identityRolesData`; the long-standing flat fields
+ * (`persona`, `personaInit`, `roles`, `tags`, `tagsInit`) are derived mirrors
+ * of those views so every existing consumer keeps reading the place it always
+ * has.
+ */
+export interface HomeSliceState {
+ /**
+ * Canonical replica view of the identity roles + tags aggregate β€” the single
+ * source of truth behind `roles`, `tags` and `tagsInit`. Engine-owned;
+ * readers use the flat mirrors.
+ */
+ identityRolesData?: IdentityRolesData;
+ /** Local-first bookkeeping for `identityRolesData`. */
+ identityRolesReplica: ReplicaState<IdentityRolesData>;
+ /** Mirror of `personaData.persona ?? undefined`. */
+ persona?: PersonaData;
+ /**
+ * Canonical replica view of the persona β€” the single source of truth behind
+ * `persona` and `personaInit`. Engine-owned; readers use the flat mirrors.
+ */
+ personaData?: PersonaReplicaData;
+ /** Whether the persona replica has a value (persisted row hydrated or a response landed). */
+ personaInit: boolean;
+ /** Local-first bookkeeping for `personaData`. */
+ personaReplica: ReplicaState<PersonaReplicaData>;
+ /** Mirror of `identityRolesData.roles` (server field `role` renamed to `tag`). */
+ roles: { count: number; tag: string }[];
+ /** Mirror of `identityRolesData.tags`. */
+ tags: { count: number; tag: string }[];
+ /** Whether the roles/tags replica has a value (persisted row hydrated or a response landed). */
+ tagsInit: boolean;
+}
+
+export const homeInitialState: HomeSliceState = {
+ identityRolesData: undefined,
+ identityRolesReplica: createReplicaState<IdentityRolesData>(),
+ persona: undefined,
+ personaData: undefined,
+ personaInit: false,
+ personaReplica: createReplicaState<PersonaReplicaData>(),
+ roles: [],
+ tags: [],
+ tagsInit: false,
+};
diff --git a/src/store/userMemory/slices/home/projection.ts b/src/store/userMemory/slices/home/projection.ts
new file mode 100644
index 00000000000..25494c8d2e1
--- /dev/null
+++ b/src/store/userMemory/slices/home/projection.ts
@@ -0,0 +1,83 @@
+import { type QueryIdentityRolesResult } from '@/database/models/userMemory';
+import { userMemoryKeys } from '@/libs/swr/keys';
+
+import { defineUserMemoryReplica } from '../../utils/replica';
+
+/**
+ * The persona is a single row per scope; the key never varies, so one entry
+ * backs every reader of the memory home page.
+ */
+export const PERSONA_KEY = 'persona';
+
+/**
+ * The identity roles + tags aggregate is a single row per scope; the key never
+ * varies, so one entry backs the home role/tag cloud.
+ */
+export const IDENTITY_ROLES_KEY = 'identityRoles';
+
+/**
+ * The window the home role/tag cloud asks for β€” mirrors the pre-migration
+ * `queryIdentityRoles({ page: 1, size: 64 })` call.
+ */
+export const IDENTITY_ROLES_QUERY = { page: 1, size: 64 } as const;
+
+/**
+ * Both home reads take no query params: one fixed value per scope. The paging
+ * window is baked into the fetcher, so it is not part of the query identity.
+ */
+export type HomeReplicaParams = Record<string, never>;
+
+/**
+ * The persona sub-model returned by `userMemory.getPersona` (`null` = the user
+ * has no persona yet).
+ */
+export interface PersonaData {
+ content: string;
+ summary: string;
+}
+
+/**
+ * Persona replica value. The persona is wrapped in an object so a
+ * server-confirmed absence (`persona: null`) is a real, persisted value rather
+ * than "no value" β€” a bare `null` would be indistinguishable from a missing
+ * entry once folded by the engine.
+ */
+export interface PersonaReplicaData {
+ persona: PersonaData | null;
+}
+
+/** Identity roles + tags aggregate (the `userMemory:tags` read). */
+export type IdentityRolesData = QueryIdentityRolesResult;
+
+/**
+ * The memory persona (`userMemory.getPersona`): one local-first replica per
+ * scope, so a revisit paints the persisted persona before the network answers.
+ *
+ * It adopts the long-standing `userMemory:persona` SWR key as its sync key, so
+ * existing revalidation by that key (the persona delete flow) still lands in
+ * the replica.
+ */
+export const personaResource = defineUserMemoryReplica<HomeReplicaParams, PersonaReplicaData>({
+ key: () => PERSONA_KEY,
+ name: 'userMemoryPersona',
+ storage: 'indexedDB',
+ syncKey: () => userMemoryKeys.persona(),
+ version: 1,
+});
+
+/**
+ * The memory identity roles + tags aggregate (`userMemoryMemories.queryIdentityRoles`):
+ * one local-first replica per scope, so the home role/tag cloud paints the
+ * persisted copy before the network answers.
+ *
+ * It adopts the long-standing `userMemory:tags` SWR key as its sync key, so
+ * existing revalidation by that key (a memory purge) still lands in the
+ * replica.
+ */
+export const identityRolesResource = defineUserMemoryReplica<HomeReplicaParams, IdentityRolesData>({
+ key: () => IDENTITY_ROLES_KEY,
+ name: 'userMemoryIdentityRoles',
+ storage: 'indexedDB',
+ syncKey: () => userMemoryKeys.tags(),
+ version: 1,
+});
diff --git a/src/store/userMemory/slices/home/replica.test.ts b/src/store/userMemory/slices/home/replica.test.ts
new file mode 100644
index 00000000000..e9fda126512
--- /dev/null
+++ b/src/store/userMemory/slices/home/replica.test.ts
@@ -0,0 +1,310 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The memory home reads (persona + identity roles/tags) are two
+ * `@lobechat/replica` single-value resources: the persisted copy paints before
+ * the network answers, the response confirms and persists it, a server
+ * `null` persona is a real (persisted) absence, an unchanged revalidation does
+ * not repaint, and the persona delete drops the value from the view and the
+ * persisted projection.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
+
+import { initialState } from '../../initialState';
+import { useUserMemoryStore } from '../../store';
+import { identityScopeOf } from '../../utils/replica';
+import {
+ type HomeReplicaParams,
+ IDENTITY_ROLES_KEY,
+ identityRolesResource,
+ PERSONA_KEY,
+ personaResource,
+} from './projection';
+
+const PARAMS = {} as HomeReplicaParams;
+const PERSONA_STORAGE_KEY = personaResource.storageKey(PARAMS);
+const ROLES_STORAGE_KEY = identityRolesResource.storageKey(PARAMS);
+
+const persona = { content: 'My persona', summary: 'Summary' };
+const roles = { roles: [{ count: 3, role: 'engineer' }], tags: [{ count: 2, tag: 'typescript' }] };
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+describe('userMemory home replicas', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ /** Storage partition of userMemory replicas: the user, not the workspace. */
+ let rowScope = '';
+ let personaSpy: ReturnType<typeof vi.spyOn>;
+ let rolesSpy: ReturnType<typeof vi.spyOn>;
+
+ const useScope = (next: string) => {
+ scope = next;
+ rowScope = identityScopeOf(scope);
+ scopes.add(rowScope);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`home-user-${randomUUID()}:personal`);
+ personaSpy = vi.spyOn(userMemoryService, 'getPersona');
+ rolesSpy = vi.spyOn(userMemoryService, 'queryIdentityRoles');
+ act(() => useUserMemoryStore.setState(initialState, false));
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ [PERSONA_STORAGE_KEY, ROLES_STORAGE_KEY].map((queryKey) =>
+ Promise.all([
+ personaResource.storage!.remove({ queryKey, scope: value }),
+ identityRolesResource.storage!.remove({ queryKey, scope: value }),
+ ]),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('backs each home read with one fixed scope entry', () => {
+ expect(PERSONA_KEY).toBe('persona');
+ expect(IDENTITY_ROLES_KEY).toBe('identityRoles');
+ });
+
+ describe('persona', () => {
+ it('paints the persisted persona before the network answers', async () => {
+ await personaResource.storage!.set(
+ { queryKey: PERSONA_STORAGE_KEY, scope: rowScope },
+ { data: { persona }, updatedAt: 1 },
+ );
+ personaSpy.mockImplementation(pending);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchPersona)(), { wrapper });
+
+ await waitFor(() => expect(useUserMemoryStore.getState().persona).toEqual(persona));
+ expect(useUserMemoryStore.getState().personaInit).toBe(true);
+ // The value can only have come from the persisted replica.
+ expect(personaSpy).toHaveBeenCalled();
+ });
+
+ it('confirms the server persona and persists it', async () => {
+ personaSpy.mockResolvedValue(persona);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchPersona)(), { wrapper });
+
+ await waitFor(() => expect(useUserMemoryStore.getState().persona).toEqual(persona));
+ expect(useUserMemoryStore.getState().personaData).toEqual({ persona });
+ expect(useUserMemoryStore.getState().personaInit).toBe(true);
+
+ await waitFor(async () => {
+ const row = await personaResource.storage!.get({
+ queryKey: PERSONA_STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect(row?.data).toEqual({ persona });
+ });
+ });
+
+ it('treats a server null persona as a persisted absence, not a missing entry', async () => {
+ personaSpy.mockResolvedValue(null);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchPersona)(), { wrapper });
+
+ await waitFor(() =>
+ expect(useUserMemoryStore.getState().personaData).toEqual({ persona: null }),
+ );
+ expect(useUserMemoryStore.getState().persona).toBeUndefined();
+ // Loaded-but-empty stays distinguishable from never-fetched.
+ expect(useUserMemoryStore.getState().personaInit).toBe(true);
+
+ await waitFor(async () => {
+ const row = await personaResource.storage!.get({
+ queryKey: PERSONA_STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect(row?.data).toEqual({ persona: null });
+ });
+ });
+
+ it('drops the persona from the view and the persisted row on refresh', async () => {
+ personaSpy.mockResolvedValue(null);
+ // Mount the SWR provider the scoped `mutate` inside refreshPersona needs.
+ renderHook(() => useUserMemoryStore((s) => s.useFetchPersona)(), { wrapper });
+ useUserMemoryStore.setState({ persona, personaData: { persona }, personaInit: true });
+
+ await act(async () => {
+ await useUserMemoryStore.getState().refreshPersona();
+ });
+
+ expect(useUserMemoryStore.getState().persona).toBeUndefined();
+ expect(useUserMemoryStore.getState().personaData).toEqual({ persona: null });
+
+ await waitFor(async () => {
+ const row = await personaResource.storage!.get({
+ queryKey: PERSONA_STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect(row?.data).toEqual({ persona: null });
+ });
+ });
+
+ it('does not report loading until a replica value exists', async () => {
+ let resolvePersona: (value: typeof persona | null) => void = () => {};
+ personaSpy.mockImplementation(() => new Promise((resolve) => (resolvePersona = resolve)));
+
+ const hook = renderHook(() => useUserMemoryStore((s) => s.useFetchPersona)(), { wrapper });
+
+ // No persisted row and no response yet: loading.
+ expect(hook.result.current.isLoading).toBe(true);
+
+ await act(async () => {
+ resolvePersona(null);
+ });
+
+ await waitFor(() => expect(hook.result.current.isLoading).toBe(false));
+ });
+
+ it('does not fetch while disabled', async () => {
+ personaSpy.mockResolvedValue(persona);
+
+ const hook = renderHook(() => useUserMemoryStore((s) => s.useFetchPersona)(false), {
+ wrapper,
+ });
+
+ expect(hook.result.current.isLoading).toBe(false);
+ expect(personaSpy).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('identity roles + tags', () => {
+ it('paints the persisted roles/tags before the network answers', async () => {
+ await identityRolesResource.storage!.set(
+ { queryKey: ROLES_STORAGE_KEY, scope: rowScope },
+ { data: roles, updatedAt: 1 },
+ );
+ rolesSpy.mockImplementation(pending);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchTags)(), { wrapper });
+
+ await waitFor(() =>
+ expect(useUserMemoryStore.getState().roles).toEqual([{ count: 3, tag: 'engineer' }]),
+ );
+ expect(useUserMemoryStore.getState().tags).toEqual([{ count: 2, tag: 'typescript' }]);
+ expect(useUserMemoryStore.getState().tagsInit).toBe(true);
+ });
+
+ it('maps role -> tag, persists, and does not repaint an unchanged response', async () => {
+ rolesSpy.mockResolvedValue(roles);
+
+ const hook = renderHook(() => useUserMemoryStore((s) => s.useFetchTags)(), { wrapper });
+
+ await waitFor(() =>
+ expect(useUserMemoryStore.getState().roles).toEqual([{ count: 3, tag: 'engineer' }]),
+ );
+ expect(useUserMemoryStore.getState().tags).toEqual([{ count: 2, tag: 'typescript' }]);
+
+ await waitFor(async () => {
+ const row = await identityRolesResource.storage!.get({
+ queryKey: ROLES_STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect(row?.data).toEqual(roles);
+ });
+
+ const first = useUserMemoryStore.getState().identityRolesData;
+ await act(async () => {
+ await hook.result.current.mutate();
+ });
+
+ // Same server value -> the replica keeps the same view object.
+ expect(useUserMemoryStore.getState().identityRolesData).toBe(first);
+ expect(rolesSpy).toHaveBeenCalledTimes(2);
+ });
+ });
+ describe('purge all memories', () => {
+ it('replaces the persisted home rows with empty values even when home is not mounted', async () => {
+ personaSpy.mockResolvedValue(persona);
+ rolesSpy.mockResolvedValue(roles);
+ vi.spyOn(memoryCRUDService, 'deleteAll').mockResolvedValue(undefined as never);
+
+ const hook = renderHook(
+ () => {
+ useUserMemoryStore((s) => s.useFetchPersona)();
+ useUserMemoryStore((s) => s.useFetchTags)();
+ },
+ { wrapper },
+ );
+ await waitFor(async () => {
+ const personaRow = await personaResource.storage!.get({
+ queryKey: PERSONA_STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect(personaRow?.data).toEqual({ persona });
+ const rolesRow = await identityRolesResource.storage!.get({
+ queryKey: ROLES_STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect(rolesRow?.data).toEqual(roles);
+ });
+
+ // Purge from another memory route: no home fetcher is mounted to refresh.
+ hook.unmount();
+ renderHook(() => null, { wrapper });
+
+ await act(async () => {
+ await useUserMemoryStore.getState().purgeAllMemories();
+ });
+
+ const state = useUserMemoryStore.getState();
+ expect(state.persona).toBeUndefined();
+ expect(state.personaData).toEqual({ persona: null });
+ expect(state.personaInit).toBe(true);
+ expect(state.roles).toEqual([]);
+ expect(state.tags).toEqual([]);
+ expect(state.tagsInit).toBe(true);
+
+ await waitFor(async () => {
+ const personaRow = await personaResource.storage!.get({
+ queryKey: PERSONA_STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect(personaRow?.data).toEqual({ persona: null });
+ const rolesRow = await identityRolesResource.storage!.get({
+ queryKey: ROLES_STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect(rolesRow?.data).toEqual({ roles: [], tags: [] });
+ });
+ });
+ });
+});
diff --git a/src/store/userMemory/slices/identity/action.test.ts b/src/store/userMemory/slices/identity/action.test.ts
new file mode 100644
index 00000000000..7aec4c1220f
--- /dev/null
+++ b/src/store/userMemory/slices/identity/action.test.ts
@@ -0,0 +1,239 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * Action-level behaviour of the identity slice: the CRUD paths revalidate the
+ * replica list instead of hand-resetting it, the injection identities sync
+ * through their own replica, and a purge clears both views through the engine.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { IdentityForInjection, IdentityListItem } from '@lobechat/types';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
+import { identitySelectors, useUserMemoryStore } from '@/store/userMemory';
+
+import { identityScopeOf } from '../../utils/replica';
+import { identityInitialState } from './initialState';
+import { globalIdentitiesResource, identityListResource } from './projection';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const identity = (id: string): IdentityListItem => ({
+ capturedAt: new Date('2026-01-01T00:00:00.000Z'),
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ description: null,
+ episodicDate: null,
+ id,
+ relationship: 'self',
+ role: null,
+ tags: null,
+ title: id,
+ type: 'personal',
+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),
+});
+
+const injection = (id: string): IdentityForInjection => ({
+ capturedAt: new Date('2026-01-01T00:00:00.000Z'),
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ description: null,
+ id,
+ role: null,
+ type: 'personal',
+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),
+});
+
+/** One `queryIdentities` response (the service envelope, not the replica view). */
+const pageOf = (items: IdentityListItem[]) => ({
+ items,
+ page: 1,
+ pageSize: 12,
+ total: items.length,
+});
+
+const PARAMS = { pageSize: 12 };
+const LIST_KEY = identityListResource.storageKey(PARAMS);
+const INJECTION_KEY = globalIdentitiesResource.storageKey({});
+
+const state = () => useUserMemoryStore.getState();
+
+describe('identity slice actions', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ /** Storage partition of userMemory replicas: the user, not the workspace. */
+ let rowScope = '';
+
+ beforeEach(() => {
+ scope = `identity-action-${randomUUID()}:personal`;
+ rowScope = identityScopeOf(scope);
+ scopes.add(rowScope);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ useUserMemoryStore.setState({ ...identityInitialState });
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all([
+ ...[...scopes].map((value) =>
+ identityListResource.storage!.remove({ queryKey: LIST_KEY, scope: value }),
+ ),
+ ...[...scopes].map((value) =>
+ globalIdentitiesResource.storage!.remove({ queryKey: INJECTION_KEY, scope: value }),
+ ),
+ ]);
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('revalidates the list after creating an identity', async () => {
+ const fetchSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValue(pageOf([identity('i1')]));
+ vi.spyOn(memoryCRUDService, 'createIdentity').mockResolvedValue({
+ identity: { id: 'i1' },
+ } as never);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), { wrapper });
+ await waitFor(() => expect(state().identities).toHaveLength(1));
+ const callsAfterHead = fetchSpy.mock.calls.length;
+
+ await act(async () => {
+ await state().createIdentity({ description: 'new' });
+ });
+
+ expect(fetchSpy.mock.calls.length).toBeGreaterThan(callsAfterHead);
+ expect(fetchSpy).toHaveBeenLastCalledWith(expect.objectContaining({ page: 1, pageSize: 12 }));
+ });
+
+ it('revalidates the list after updating an identity', async () => {
+ const fetchSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValue(pageOf([identity('i1')]));
+ const updateSpy = vi.spyOn(memoryCRUDService, 'updateIdentity').mockResolvedValue(true);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), { wrapper });
+ await waitFor(() => expect(state().identities).toHaveLength(1));
+ const callsAfterHead = fetchSpy.mock.calls.length;
+
+ await act(async () => {
+ await state().updateIdentity('i1', { description: 'edited' });
+ });
+
+ expect(updateSpy).toHaveBeenCalledWith('i1', { description: 'edited' });
+ expect(fetchSpy.mock.calls.length).toBeGreaterThan(callsAfterHead);
+ });
+
+ it('syncs the self identities injected into the chat context', async () => {
+ const injectionSpy = vi
+ .spyOn(userMemoryService, 'queryIdentitiesForInjection')
+ .mockResolvedValue([injection('i1')]);
+
+ renderHook(() => useUserMemoryStore((s) => s.useInitIdentities)(true), { wrapper });
+
+ await waitFor(() => expect(state().globalIdentitiesInit).toBe(true));
+ expect(state().globalIdentities.map((item) => item.id)).toEqual(['i1']);
+ expect(identitySelectors.hasGlobalIdentities(state())).toBe(true);
+ expect(injectionSpy).toHaveBeenCalledWith({ limit: 25 });
+ });
+
+ it('does not request injection identities when signed out', () => {
+ const injectionSpy = vi
+ .spyOn(userMemoryService, 'queryIdentitiesForInjection')
+ .mockResolvedValue([injection('i1')]);
+
+ renderHook(() => useUserMemoryStore((s) => s.useInitIdentities)(false), { wrapper });
+
+ expect(injectionSpy).not.toHaveBeenCalled();
+ expect(state().globalIdentitiesInit).toBe(false);
+ });
+
+ it('clears both identity views (and their persisted rows) on reset', async () => {
+ vi.spyOn(userMemoryService, 'queryIdentities').mockResolvedValue(pageOf([identity('i1')]));
+ vi.spyOn(userMemoryService, 'queryIdentitiesForInjection').mockResolvedValue([injection('i1')]);
+
+ renderHook(
+ () => ({
+ list: useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS),
+ injection: useUserMemoryStore((s) => s.useInitIdentities)(true),
+ }),
+ { wrapper },
+ );
+ await waitFor(() => expect(state().identities).toHaveLength(1));
+ await waitFor(() => expect(state().globalIdentities).toHaveLength(1));
+
+ // The purge emptied the server; the clear itself is synchronous.
+ vi.spyOn(userMemoryService, 'queryIdentities').mockResolvedValue(pageOf([]));
+ vi.spyOn(userMemoryService, 'queryIdentitiesForInjection').mockResolvedValue([]);
+ let reset!: Promise<boolean>;
+ act(() => {
+ reset = state().internal_clearIdentityList();
+ });
+
+ expect(state().identities).toEqual([]);
+ expect(state().globalIdentities).toEqual([]);
+ expect(identitySelectors.identitiesTotal(state())).toBe(0);
+ await act(async () => {
+ await expect(reset).resolves.toBe(true);
+ });
+ // The deleted rows are gone from the persisted copies.
+ const list = await identityListResource.storage!.get({ queryKey: LIST_KEY, scope: rowScope });
+ expect((list?.data as { items: unknown[] } | undefined)?.items ?? []).toEqual([]);
+ const injected = await globalIdentitiesResource.storage!.get({
+ queryKey: INJECTION_KEY,
+ scope: rowScope,
+ });
+ expect(injected?.data ?? []).toEqual([]);
+ });
+
+ it('revalidates both identity views on refresh (clear() does not refetch)', async () => {
+ const listSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValue(pageOf([identity('i1')]));
+ const injectionSpy = vi
+ .spyOn(userMemoryService, 'queryIdentitiesForInjection')
+ .mockResolvedValue([injection('i1')]);
+
+ renderHook(
+ () => ({
+ list: useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS),
+ injection: useUserMemoryStore((s) => s.useInitIdentities)(true),
+ }),
+ { wrapper },
+ );
+ await waitFor(() => expect(state().identities).toHaveLength(1));
+ await waitFor(() => expect(state().globalIdentities).toHaveLength(1));
+
+ // The purge emptied the server.
+ listSpy.mockResolvedValue(pageOf([]));
+ injectionSpy.mockResolvedValue([]);
+ await act(async () => {
+ await state().internal_clearIdentityList();
+ await state().refreshIdentities();
+ });
+
+ await waitFor(() => expect(state().identitiesInit).toBe(true));
+ await waitFor(() => expect(state().globalIdentitiesInit).toBe(true));
+ expect(state().identities).toEqual([]);
+ expect(state().globalIdentities).toEqual([]);
+ });
+});
diff --git a/src/store/userMemory/slices/identity/action.ts b/src/store/userMemory/slices/identity/action.ts
index f7a496f2bf0..6fdb9d930d7 100644
--- a/src/store/userMemory/slices/identity/action.ts
+++ b/src/store/userMemory/slices/identity/action.ts
@@ -1,153 +1,255 @@
import {
- type IdentityListResult,
+ type IdentityListItem,
type NewUserMemoryIdentity,
type UpdateUserMemoryIdentity,
} from '@lobechat/types';
-import { uniqBy } from 'es-toolkit/compat';
-import { produce } from 'immer';
-import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
+import isEqual from 'fast-deep-equal';
+import { useLayoutEffect } from 'react';
import { type AddIdentityEntryResult } from '@/database/models/userMemory';
-import { userMemoryKeys } from '@/libs/swr/keys';
-import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
+import {
+ createReplicaSlice,
+ recordLens,
+ type ReplicaLens,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
+import { memoryCRUDService } from '@/services/userMemory';
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type UserMemoryStore } from '../../store';
+import { type IdentityForInjection } from '../../types';
+import { clearReplicas, clearUserReplicas, memoryListKey } from '../../utils/replica';
+import { OffsetListPager } from '../utils/offsetListPager';
+import {
+ DEFAULT_IDENTITY_LIST_PAGE_SIZE,
+ GLOBAL_IDENTITIES_KEY,
+ globalIdentitiesResource,
+ type IdentityListParams,
+ identityListResource,
+ type IdentityListView,
+} from './projection';
const n = setNamespace('userMemory/identity');
-export interface IdentityQueryParams {
- page?: number;
- pageSize?: number;
- q?: string;
- relationships?: string[];
- sort?: 'capturedAt' | 'type';
- types?: string[];
-}
+const GLOBAL_IDENTITIES_PARAMS = {} as Record<string, never>;
+
+const identityEntries = recordLens<UserMemoryStore, IdentityListView>('identityListEntries');
+
+/**
+ * Flat mirrors of one identity page set (`undefined` = the active query has no
+ * view yet). `identitiesInit` is only ever set here: it survives a query
+ * change, so the page controls are not torn down while a search resolves.
+ */
+const identityMirrorsOf = (data: IdentityListView | undefined): Partial<UserMemoryStore> => {
+ if (!data) return { identities: [], identitiesMeta: undefined };
+ const { items, ...meta } = data;
+ return { identities: items, identitiesInit: true, identitiesMeta: meta };
+};
+
+/**
+ * The canonical value is one page set per search / filter / sort
+ * (`identityListEntries`). The long-standing flat array (`identities`) and its
+ * paging bookkeeping (`identitiesMeta`) mirror the active query's entry in the
+ * same commit, so every existing reader (grid, timeline, card dropdown, route
+ * boundary) keeps reading the same place.
+ */
+const identityListLens: ReplicaLens<UserMemoryStore, IdentityListView> = {
+ clear: (state) => ({
+ ...identityEntries.clear(state),
+ identities: [],
+ identitiesInit: false,
+ identitiesMeta: undefined,
+ }),
+ get: identityEntries.get,
+ keys: identityEntries.keys,
+ set: (state, key, data) => ({
+ ...identityEntries.set(state, key, data),
+ ...(key === state.identityListKey ? identityMirrorsOf(data) : undefined),
+ }),
+};
+
+/** Single-slot view of the injection-identities replica. */
+const globalIdentitiesLens: ReplicaLens<UserMemoryStore, IdentityForInjection[]> = {
+ clear: () => ({ globalIdentities: [], globalIdentitiesInit: false }),
+ get: (state) => (state.globalIdentitiesInit ? state.globalIdentities : undefined),
+ keys: (state) => (state.globalIdentitiesInit ? [GLOBAL_IDENTITIES_KEY] : []),
+ set: (_state, _key, data) =>
+ data
+ ? { globalIdentities: data, globalIdentitiesInit: true }
+ : { globalIdentities: [], globalIdentitiesInit: false },
+};
type Setter = StoreSetter<UserMemoryStore>;
export const createIdentitySlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
new IdentityActionImpl(set, get, _api);
+/**
+ * The identities domain.
+ *
+ * Server state is two replicas: the paginated `identities` list (its flat array
+ * is `identities`, its paging bookkeeping `identitiesMeta`) and the
+ * `globalIdentities` injection list. Each paints its persisted copy on the
+ * first frame and is confirmed by the network in the background; the engine
+ * owns hydration, paging, optimistic overlays with rollback and scope
+ * isolation.
+ */
export class IdentityActionImpl {
+ readonly #globalIdentities;
+ /** The identity list is a paged replica; the engine owns its paging. */
+ readonly #identities;
readonly #get: () => UserMemoryStore;
+ /** Delete / load more / purge with the offset repair shared by every memory list. */
+ readonly #pager: OffsetListPager;
readonly #set: Setter;
constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
void _api;
- this.#set = set;
this.#get = get;
+ this.#set = set;
+ this.#identities = createReplicaSlice(identityListResource, {
+ actionPrefix: n('identities'),
+ get,
+ set,
+ stateKey: 'identitiesReplica',
+ view: identityListLens,
+ viewFields: ({ order, q, relationships, sort, types }) => ({
+ order,
+ q: q || undefined,
+ relationships,
+ sort,
+ types,
+ }),
+ });
+ this.#globalIdentities = createReplicaSlice(globalIdentitiesResource, {
+ actionPrefix: n('globalIdentities'),
+ get,
+ // An unchanged list must not re-render the injection consumers.
+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),
+ set,
+ stateKey: 'globalIdentitiesReplica',
+ view: globalIdentitiesLens,
+ });
+ this.#pager = new OffsetListPager({
+ keys: () => Object.keys(get().identityListEntries),
+ read: (key) => get().identityListEntries[key],
+ refreshHead: () => this.refreshIdentities(),
+ slice: this.#identities,
+ });
}
createIdentity = async (data: NewUserMemoryIdentity): Promise<AddIdentityEntryResult> => {
const result = await memoryCRUDService.createIdentity(data);
- // Reset list to refresh
- this.#get().resetIdentitiesList({
- q: this.#get().identitiesQuery,
- relationships: this.#get().identitiesRelationships,
- sort: this.#get().identitiesSort,
- types: this.#get().identitiesTypes,
- });
+ await this.refreshIdentities();
return result;
};
- deleteIdentity = async (id: string): Promise<void> => {
- await memoryCRUDService.deleteIdentity(id);
- // Reset list to refresh
- this.#get().resetIdentitiesList({
- q: this.#get().identitiesQuery,
- relationships: this.#get().identitiesRelationships,
- sort: this.#get().identitiesSort,
- types: this.#get().identitiesTypes,
- });
- };
+ /**
+ * Delete one identity: optimistic (rolled back if the server rejects), then
+ * the offset repair shared by every memory list β€” the row leaves every
+ * persisted search/filter variant, the list collapses to a refreshed head,
+ * and "load more" waits for that head (see `OffsetListPager`).
+ */
+ deleteIdentity = (id: string): Promise<void> =>
+ this.#pager.delete(id, () => memoryCRUDService.deleteIdentity(id));
- loadMoreIdentities = (): void => {
- const { identitiesPage, identitiesTotal, identities } = this.#get();
- if (identities.length < (identitiesTotal || 0)) {
- this.#set(
- produce((draft) => {
- draft.identitiesPage = identitiesPage + 1;
- }),
- false,
- n('loadMoreIdentities'),
- );
- }
- };
+ /** Append the next page of the identities list, once its head is trustworthy. */
+ loadMoreIdentities = (): Promise<void> => this.#pager.loadMore(this.#get().identityListKey);
- resetIdentitiesList = (params?: Omit<IdentityQueryParams, 'page' | 'pageSize'>): void => {
+ /**
+ * Point the flat mirrors at another search / filter. Each query keeps its own
+ * entry, so this drops no page set: a query loaded before repaints from
+ * memory, one persisted before hydrates from storage, and a new one shows the
+ * loading state until its head lands. A no-op when the query is unchanged.
+ */
+ #selectQuery = (key: string): void => {
+ const state = this.#get();
+ if (state.identityListKey === key) return;
this.#set(
- produce((draft) => {
- draft.identities = [];
- draft.identitiesPage = 1;
- draft.identitiesQuery = params?.q;
- draft.identitiesRelationships = params?.relationships;
- draft.identitiesSearchLoading = true;
- draft.identitiesSort = params?.sort;
- draft.identitiesTypes = params?.types;
- }),
+ { identityListKey: key, ...identityMirrorsOf(state.identityListEntries[key]) },
false,
- n('resetIdentitiesList'),
+ n('identities/select'),
);
};
+ /**
+ * Apply a confirmed edit to one identity (an inline edit elsewhere in the
+ * store) in every loaded list entry and its persisted rows, so the replica
+ * value β€” not only the view β€” carries it across a reload.
+ */
+ internal_updateIdentityEntity = (
+ id: string,
+ fn: (item: IdentityListItem) => IdentityListItem | undefined,
+ ): void => {
+ this.#identities.updateEntity(id, fn);
+ };
+
+ /**
+ * Revalidate the identity replicas of the active scope: the list and the
+ * self identities injected into the chat context, which any identity write
+ * can change. The replica scope carries the user + workspace, so this always
+ * refreshes the lists the caller is in.
+ */
+ refreshIdentities = async (): Promise<void> => {
+ await Promise.all([this.#identities.revalidate(), this.#globalIdentities.revalidate()]);
+ };
+
+ /**
+ * Wipe every identity replica (list + injection) through the engine: memory,
+ * every persisted search/filter variant (not only the query on screen) and
+ * reads in flight. Used by the memory purge; `clear()` does not refetch, so
+ * the caller revalidates afterwards (`refreshIdentities`). Resolves `true`
+ * once the persisted rows are gone.
+ */
+ internal_clearIdentityList = (user?: string): Promise<boolean> =>
+ user === undefined || user === identityListResource.scope.get()
+ ? this.#pager.clear(() => clearReplicas(this.#identities.clear, this.#globalIdentities.clear))
+ : clearUserReplicas(user, this.#identities, this.#globalIdentities);
+
updateIdentity = async (id: string, data: UpdateUserMemoryIdentity): Promise<boolean> => {
const result = await memoryCRUDService.updateIdentity(id, data);
- // Reset list to refresh
- this.#get().resetIdentitiesList({
- q: this.#get().identitiesQuery,
- relationships: this.#get().identitiesRelationships,
- sort: this.#get().identitiesSort,
- types: this.#get().identitiesTypes,
- });
+ await this.refreshIdentities();
return result;
};
- useFetchIdentities = (params: IdentityQueryParams): SWRResponse<IdentityListResult> => {
- const page = params.page ?? 1;
-
- return useSWR(
- userMemoryKeys.identityList(params),
- async () => {
- // Use the new dedicated queryIdentities API
- return userMemoryService.queryIdentities({
- page: params.page,
- pageSize: params.pageSize,
- q: params.q,
- relationships: params.relationships,
- sort: params.sort,
- types: params.types,
- });
- },
- {
- onSuccess: (data: IdentityListResult) => {
- this.#set(
- produce((draft) => {
- draft.identitiesSearchLoading = false;
- draft.identitiesTotal = data.total;
-
- if (!draft.identitiesInit) {
- draft.identitiesInit = true;
- }
-
- // Backend now returns flat structure directly, no transformation needed
- if (page === 1) {
- draft.identities = uniqBy(data.items, 'id');
- } else {
- draft.identities = uniqBy([...draft.identities, ...data.items], 'id');
- }
-
- draft.identitiesHasMore = data.items.length >= (params.pageSize || 20);
- }),
- false,
- n('useFetchIdentities/onSuccess'),
- );
- },
- revalidateOnFocus: false,
- },
- );
+ /**
+ * Fetch orchestration for the identities list. Hydrates the persisted head
+ * page, then revalidates; the rows land in `identities` β€” read them from the
+ * store, never from this hook.
+ */
+ useFetchIdentities = (params: IdentityListParams): ReplicaSyncResult => {
+ const key = memoryListKey(params);
+
+ // Select the query before paint, so a frame never shows another query's rows.
+ useLayoutEffect(() => {
+ this.#selectQuery(key);
+ }, [key]);
+
+ return this.#identities.useSync(params, {
+ ...this.#pager.syncCallbacks(key),
+ revalidateOnFocus: false,
+ });
+ };
+
+ /**
+ * Fetch orchestration for the self identities injected into the chat context.
+ * Signed-out callers disable the sync, matching the previous `null` key.
+ */
+ useInitIdentities = (isLogin: boolean): ReplicaSyncResult =>
+ this.#globalIdentities.useSync(GLOBAL_IDENTITIES_PARAMS, { enabled: isLogin === true });
+
+ /**
+ * Seed the persisted head page of the identities list before the route
+ * commits, so a cold start paints the local copy instead of a skeleton. A
+ * later `useSync` hydrate is a no-op once the slot is filled.
+ */
+ preHydrateIdentities = (
+ params: IdentityListParams = { pageSize: DEFAULT_IDENTITY_LIST_PAGE_SIZE },
+ ): Promise<boolean> => {
+ const scope = identityListResource.scope.get();
+ this.#identities.ensureScope(scope);
+
+ return this.#identities.hydrate(params, scope);
};
}
diff --git a/src/store/userMemory/slices/identity/initialState.ts b/src/store/userMemory/slices/identity/initialState.ts
index 0e207d39fb8..41920e3b95f 100644
--- a/src/store/userMemory/slices/identity/initialState.ts
+++ b/src/store/userMemory/slices/identity/initialState.ts
@@ -1,37 +1,60 @@
-import { type IdentityListItem, type IdentityListSort } from '@lobechat/types';
+import { type IdentityListItem } from '@lobechat/types';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
import { type IdentityForInjection } from '../../types';
+import { memoryListKey } from '../../utils/replica';
+import {
+ DEFAULT_IDENTITY_LIST_PAGE_SIZE,
+ type IdentityListMeta,
+ type IdentityListView,
+} from './projection';
export interface IdentitySliceState {
- /** Global identities fetched at app initialization for injection into chat context */
+ /**
+ * The caller's own identities injected into the chat context β€” the view of
+ * the `globalIdentities` replica. Consumers read it through
+ * `identitySelectors.globalIdentities`.
+ */
globalIdentities: IdentityForInjection[];
- /** When global identities were fetched */
- globalIdentitiesFetchedAt?: number;
/** Whether global identities have been initialized */
globalIdentitiesInit: boolean;
+ /** Replica bookkeeping for `globalIdentities`. */
+ globalIdentitiesReplica: ReplicaState<IdentityForInjection[]>;
+
+ /**
+ * Rows of the identities list β€” the view of the `identityList` replica, kept
+ * as a flat array where every existing reader expects it. The paging
+ * bookkeeping lives beside it in `identitiesMeta`.
+ */
identities: IdentityListItem[];
- identitiesHasMore: boolean;
+ /**
+ * `true` once the first identity page has landed. Stays `true` across a query
+ * change (only a scope switch clears it), so the page controls are not torn
+ * down while a new search resolves.
+ */
identitiesInit: boolean;
- identitiesPage: number;
- identitiesQuery?: string;
- identitiesRelationships?: string[];
- identitiesSearchLoading?: boolean;
- identitiesSort?: IdentityListSort;
- identitiesTotal: number;
- identitiesTypes?: string[];
+ /** Paging bookkeeping of the active query's page set (mirror). */
+ identitiesMeta?: IdentityListMeta;
+ /** Replica bookkeeping for `identityListEntries`. */
+ identitiesReplica: ReplicaState<IdentityListView>;
+ /**
+ * Canonical replica views of the identity list, one page set per search /
+ * filter / sort. `identities` / `identitiesMeta` mirror the active one.
+ */
+ identityListEntries: Record<string, IdentityListView>;
+ /** Entry key of the query on screen (see `memoryListKey`). */
+ identityListKey: string;
}
export const identityInitialState: IdentitySliceState = {
globalIdentities: [],
- globalIdentitiesFetchedAt: undefined,
globalIdentitiesInit: false,
+ globalIdentitiesReplica: createReplicaState(),
identities: [],
- identitiesHasMore: true,
identitiesInit: false,
- identitiesPage: 1,
- identitiesQuery: undefined,
- identitiesRelationships: undefined,
- identitiesSort: undefined,
- identitiesTotal: 0,
- identitiesTypes: undefined,
+ identitiesMeta: undefined,
+ identitiesReplica: createReplicaState(),
+ identityListEntries: {},
+ identityListKey: memoryListKey({ pageSize: DEFAULT_IDENTITY_LIST_PAGE_SIZE }),
};
diff --git a/src/store/userMemory/slices/identity/projection.ts b/src/store/userMemory/slices/identity/projection.ts
new file mode 100644
index 00000000000..ed5aa280e8e
--- /dev/null
+++ b/src/store/userMemory/slices/identity/projection.ts
@@ -0,0 +1,128 @@
+import { type IdentityListItem, type IdentityListSort } from '@lobechat/types';
+
+import { type ReplicaPagedData } from '@/libs/replica';
+import { userMemoryService } from '@/services/userMemory';
+
+import { type IdentityForInjection } from '../../types';
+import {
+ defineUserMemoryPagedReplica,
+ defineUserMemoryReplica,
+ MAX_RECENT_MEMORY_QUERIES,
+ memoryListKey,
+} from '../../utils/replica';
+
+/** Rows per page when the caller does not name one. */
+export const DEFAULT_IDENTITY_LIST_PAGE_SIZE = 12;
+
+/**
+ * Query identity of one identities page: the server-side filters, the sort and
+ * the page size. The window start is NOT here β€” it is the replica's paging
+ * cursor (offset mode: the page index), which the engine owns and advances.
+ */
+export interface IdentityListParams {
+ order?: 'asc' | 'desc';
+ pageSize: number;
+ q?: string;
+ relationships?: string[];
+ sort?: IdentityListSort;
+ types?: string[];
+}
+
+/**
+ * `identities` view: the generic local-first paged data plus the query
+ * descriptors the page was fetched with, so the surface can tell whether the
+ * painted rows still answer the request on screen. Paging bookkeeping
+ * (`currentPage` / `hasMore` / `isLoadingMore`) comes from `ReplicaPagedData`.
+ */
+export interface IdentityListView extends ReplicaPagedData<IdentityListItem, number> {
+ order?: 'asc' | 'desc';
+ q?: string;
+ relationships?: string[];
+ sort?: IdentityListSort;
+ types?: string[];
+}
+
+/** Bookkeeping half of {@link IdentityListView} (the rows live in `identities`). */
+export type IdentityListMeta = Omit<IdentityListView, 'items'>;
+
+/**
+ * Whether a painted identity page still answers `params`. The view stores the
+ * query it was fetched with, so a response for another query can never be read
+ * as this one's answer.
+ */
+export const isIdentityQueryCurrent = (
+ meta: IdentityListMeta | undefined,
+ params: Pick<IdentityListParams, 'q' | 'types'>,
+): boolean => {
+ if (!meta) return false;
+ const sameTypes =
+ (meta.types?.length ?? 0) === (params.types?.length ?? 0) &&
+ (meta.types ?? []).every((type) => (params.types ?? []).includes(type));
+
+ return (meta.q || undefined) === (params.q || undefined) && sameTypes;
+};
+
+/**
+ * The identities list (`userMemories.queryIdentities`): a local-first paged
+ * replica. A reload paints the persisted head page on the first frame, the
+ * network confirms it, and "load more" appends further pages through the
+ * engine.
+ *
+ * Filters + sort are the entry key: a projection taken under another query
+ * never paints, and an un-loaded list never reads as an empty one.
+ *
+ * Offset paging, cursor = page index (0 = head): the endpoint pages 1-based and
+ * reports the real `total`, so "is there more" stays the server's answer.
+ */
+export const identityListResource = defineUserMemoryPagedReplica<
+ IdentityListParams,
+ IdentityListItem,
+ number,
+ IdentityListView
+>({
+ fetchPage: async (params, cursor) => {
+ const { pageSize, ...filters } = params;
+ const result = await userMemoryService.queryIdentities({
+ ...filters,
+ page: (cursor ?? 0) + 1,
+ pageSize,
+ });
+
+ return { items: result.items, total: result.total };
+ },
+ // One entry per search / filter / sort (see `memoryListKey`): each query
+ // hydrates its own persisted head page, and the recent-query window bounds
+ // how many survive (`persist.maxEntries`; the query on screen is pinned).
+ key: memoryListKey,
+ name: 'identityList',
+ paging: {
+ direction: 'forward',
+ getId: (item) => item.id,
+ mode: 'offset',
+ // A reload repaints what the first network page would show, never a stale tail.
+ persist: { pages: 1 },
+ },
+ persist: { maxEntries: MAX_RECENT_MEMORY_QUERIES },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** The single entry of the injection-identities resource. */
+export const GLOBAL_IDENTITIES_KEY = 'all';
+
+/**
+ * The caller's own identities, loaded at app init to inject into the chat
+ * context (`userMemories.queryIdentitiesForInjection`). Read through
+ * `identitySelectors.globalIdentities`; persisted so the injection survives a
+ * reload from the local copy while the network confirms it.
+ */
+export const globalIdentitiesResource = defineUserMemoryReplica<
+ Record<string, never>,
+ IdentityForInjection[]
+>({
+ fetcher: () => userMemoryService.queryIdentitiesForInjection({ limit: 25 }),
+ key: () => GLOBAL_IDENTITIES_KEY,
+ name: 'globalIdentities',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/userMemory/slices/identity/replica.test.ts b/src/store/userMemory/slices/identity/replica.test.ts
new file mode 100644
index 00000000000..86f93bff4ce
--- /dev/null
+++ b/src/store/userMemory/slices/identity/replica.test.ts
@@ -0,0 +1,531 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The identities list is a `@lobechat/replica` paged resource whose view is the
+ * userMemory store's flat `identities` array (with `identitiesMeta` beside it):
+ * the persisted head page paints while the network confirms it, "load more"
+ * appends through the engine, an optimistic delete rolls back on failure, and a
+ * cache-scope switch drops the previous identity's rows before paint.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { IdentityListItem } from '@lobechat/types';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
+import { identitySelectors, useUserMemoryStore } from '@/store/userMemory';
+
+import { identityScopeOf, MAX_RECENT_MEMORY_QUERIES } from '../../utils/replica';
+import { identityInitialState } from './initialState';
+import { identityListResource, type IdentityListView } from './projection';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const identity = (id: string, overrides: Partial<IdentityListItem> = {}): IdentityListItem => ({
+ capturedAt: new Date('2026-01-01T00:00:00.000Z'),
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ description: null,
+ episodicDate: null,
+ id,
+ relationship: 'self',
+ role: null,
+ tags: null,
+ title: id,
+ type: 'personal',
+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),
+ ...overrides,
+});
+
+/** One `queryIdentities` response (the service envelope, not the replica view). */
+const responseOf = (
+ items: IdentityListItem[],
+ overrides: { page?: number; total?: number } = {},
+) => ({
+ items,
+ page: overrides.page ?? 1,
+ pageSize: 12,
+ total: overrides.total ?? items.length,
+});
+
+const pageOf = (
+ items: IdentityListItem[],
+ overrides: Partial<IdentityListView> = {},
+): IdentityListView => ({
+ currentPage: 0,
+ hasMore: false,
+ items,
+ pageSize: 12,
+ total: items.length,
+ ...overrides,
+});
+
+/** Never-resolving fetch: what the store holds can only have come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const PARAMS = { pageSize: 12 };
+const STORAGE_KEY = identityListResource.storageKey(PARAMS);
+
+const listState = () => useUserMemoryStore.getState();
+
+describe('identity list replica', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ /** Storage partition of userMemory replicas: the user, not the workspace. */
+ let rowScope = '';
+
+ const useScope = (next: string) => {
+ scope = next;
+ rowScope = identityScopeOf(scope);
+ scopes.add(rowScope);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`identity-user-${randomUUID()}:personal`);
+ useUserMemoryStore.setState({ ...identityInitialState });
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].map((value) =>
+ identityListResource.storage!.remove({ queryKey: STORAGE_KEY, scope: value }),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted head page before the network answers', async () => {
+ await identityListResource.storage!.set(
+ { queryKey: STORAGE_KEY, scope: rowScope },
+ { data: pageOf([identity('i1', { title: 'Cached' })]), updatedAt: 1 },
+ );
+ vi.spyOn(userMemoryService, 'queryIdentities').mockImplementation(pending);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), { wrapper });
+
+ await waitFor(() => expect(listState().identitiesInit).toBe(true));
+ expect(listState().identities).toHaveLength(1);
+ expect(listState().identities[0].title).toBe('Cached');
+ // The slot is filled from storage, so the local read is what settled it.
+ expect(identitySelectors.identitiesTotal(listState())).toBe(1);
+ });
+
+ it('seeds the persisted head page before the route commits', async () => {
+ await identityListResource.storage!.set(
+ { queryKey: STORAGE_KEY, scope: rowScope },
+ { data: pageOf([identity('i1', { title: 'Seeded' })]), updatedAt: 1 },
+ );
+ vi.spyOn(userMemoryService, 'queryIdentities').mockImplementation(pending);
+
+ await act(async () => {
+ await listState().preHydrateIdentities(PARAMS);
+ });
+
+ expect(listState().identities.map((item) => item.title)).toEqual(['Seeded']);
+ expect(listState().identitiesInit).toBe(true);
+ });
+
+ it('appends the next page through the engine and keeps `hasMore` honest', async () => {
+ const head = Array.from({ length: 12 }, (_, i) => identity(`i${i}`));
+ const next = Array.from({ length: 12 }, (_, i) => identity(`i${i + 12}`));
+ const fetchSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValue(responseOf(head, { total: 24 }));
+
+ const { result } = renderHook(
+ () => ({
+ loadMore: useUserMemoryStore((s) => s.loadMoreIdentities),
+ sync: useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(listState().identities).toHaveLength(12));
+ expect(identitySelectors.identitiesHasMore(listState())).toBe(true);
+
+ fetchSpy.mockResolvedValue(responseOf(next, { page: 2, total: 24 }));
+ await act(async () => {
+ await result.current.loadMore();
+ });
+
+ expect(listState().identities).toHaveLength(24);
+ expect(listState().identities[12].id).toBe('i12');
+ expect(identitySelectors.identitiesHasMore(listState())).toBe(false);
+ // Offset mode: the cursor is the page index; the server is asked for page 2.
+ expect(fetchSpy).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2, pageSize: 12 }));
+ });
+
+ it('exposes load-more progress and failure so the list can show them and retry', async () => {
+ const head = Array.from({ length: 12 }, (_, i) => identity(`i${i}`));
+ const fetchSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValue(responseOf(head, { total: 24 }));
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), { wrapper });
+ await waitFor(() => expect(listState().identities).toHaveLength(12));
+
+ let fail!: (error: Error) => void;
+ fetchSpy.mockImplementation(
+ () =>
+ new Promise((_, reject) => {
+ fail = reject;
+ }),
+ );
+ let loading!: Promise<void>;
+ act(() => {
+ loading = listState().loadMoreIdentities();
+ });
+ await waitFor(() => expect(identitySelectors.identitiesIsLoadingMore(listState())).toBe(true));
+ expect(identitySelectors.identitiesLoadMoreError(listState())).toBeUndefined();
+
+ const failure = new Error('offline');
+ await act(async () => {
+ fail(failure);
+ await loading.catch(() => {});
+ });
+
+ expect(identitySelectors.identitiesIsLoadingMore(listState())).toBe(false);
+ expect(identitySelectors.identitiesLoadMoreError(listState())).toBe(failure);
+ // The rows already on screen stay; only the next page is missing.
+ expect(listState().identities).toHaveLength(12);
+ });
+
+ it('removes a row optimistically and rolls it back when the server rejects', async () => {
+ vi.spyOn(userMemoryService, 'queryIdentities').mockResolvedValue(
+ responseOf([identity('i1'), identity('i2')]),
+ );
+ const deleteSpy = vi
+ .spyOn(memoryCRUDService, 'deleteIdentity')
+ .mockRejectedValue(new Error('offline'));
+
+ const { result } = renderHook(() => useUserMemoryStore((s) => s.deleteIdentity), { wrapper });
+ renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), { wrapper });
+ await waitFor(() => expect(listState().identities).toHaveLength(2));
+
+ await act(async () => {
+ await expect(result.current('i1')).rejects.toThrow('offline');
+ });
+
+ expect(deleteSpy).toHaveBeenCalledWith('i1');
+ // Rolled back to the confirmed page, nothing lost.
+ expect(listState().identities.map((item) => item.id)).toEqual(['i1', 'i2']);
+ });
+
+ it('keeps offset paging contiguous after a delete (collapse + fresh head first)', async () => {
+ let server = Array.from({ length: 30 }, (_, i) => identity(`r${i}`));
+ vi.spyOn(userMemoryService, 'queryIdentities').mockImplementation(
+ async ({ page = 1, pageSize = 12 }: { page?: number; pageSize?: number } = {}) =>
+ responseOf(server.slice((page - 1) * pageSize, page * pageSize), {
+ page,
+ total: server.length,
+ }),
+ );
+ vi.spyOn(memoryCRUDService, 'deleteIdentity').mockResolvedValue(undefined);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), { wrapper });
+ await waitFor(() => expect(listState().identities).toHaveLength(12));
+ await act(async () => {
+ await listState().loadMoreIdentities();
+ });
+ await waitFor(() => expect(listState().identities).toHaveLength(24));
+
+ server = server.filter((item) => item.id !== 'r5');
+ await act(async () => {
+ await listState().deleteIdentity('r5');
+ });
+ await act(async () => {
+ await listState().loadMoreIdentities();
+ });
+
+ // Without the collapse, the stale page-2 offset would skip r12.
+ await waitFor(() =>
+ expect(listState().identities.map((item) => item.id)).toEqual(
+ server.slice(0, 24).map((item) => item.id),
+ ),
+ );
+ });
+
+ it('paints a previously persisted search from storage when switching to it offline', async () => {
+ const SEARCH = { pageSize: 12, q: 'alice' };
+ await identityListResource.storage!.set(
+ { queryKey: identityListResource.storageKey(SEARCH), scope: rowScope },
+ {
+ data: {
+ currentPage: 0,
+ hasMore: false,
+ items: [identity('cached-alice')],
+ pageSize: 12,
+ q: 'alice',
+ total: 1,
+ } satisfies IdentityListView,
+ updatedAt: 1,
+ },
+ );
+ scopes.add(rowScope);
+ const fetchSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValueOnce(responseOf([identity('i1')]));
+
+ const hook = renderHook(
+ (params: typeof PARAMS & { q?: string }) =>
+ useUserMemoryStore((s) => s.useFetchIdentities)(params),
+ { initialProps: PARAMS as typeof PARAMS & { q?: string }, wrapper },
+ );
+ await waitFor(() => expect(listState().identities.map((item) => item.id)).toEqual(['i1']));
+
+ // Offline: the search never answers, only its persisted row can paint it.
+ fetchSpy.mockRejectedValue(new Error('offline'));
+ hook.rerender(SEARCH);
+
+ await waitFor(() =>
+ expect(listState().identities.map((item) => item.id)).toEqual(['cached-alice']),
+ );
+ expect(listState().identitiesMeta).toMatchObject({ q: 'alice' });
+ await identityListResource.storage!.remove({
+ queryKey: identityListResource.storageKey(SEARCH),
+ scope: rowScope,
+ });
+ });
+
+ it('bounds how many identity search variants are kept', async () => {
+ vi.spyOn(userMemoryService, 'queryIdentities').mockImplementation(async ({ q } = {}) =>
+ responseOf([identity(`${q}-hit`)]),
+ );
+ const queries = Array.from({ length: MAX_RECENT_MEMORY_QUERIES + 2 }, (_, i) => `q-${i}`);
+ const keyOf = (q: string) => identityListResource.storageKey({ ...PARAMS, q });
+
+ const hook = renderHook(
+ (props: { q: string }) =>
+ useUserMemoryStore((s) => s.useFetchIdentities)({ ...PARAMS, q: props.q }),
+ { initialProps: { q: queries[0] }, wrapper },
+ );
+ for (const q of queries) {
+ hook.rerender({ q });
+ await waitFor(() => expect(listState().identityListEntries[keyOf(q)]).toBeDefined());
+ }
+
+ expect(Object.keys(listState().identityListEntries)).toHaveLength(MAX_RECENT_MEMORY_QUERIES);
+ // The oldest searches left memory and IndexedDB together.
+ await waitFor(async () =>
+ expect(
+ await identityListResource.storage!.get({ queryKey: keyOf(queries[0]), scope: rowScope }),
+ ).toBeUndefined(),
+ );
+ for (const q of queries) {
+ await identityListResource.storage!.remove({ queryKey: keyOf(q), scope: rowScope });
+ }
+ });
+
+ it('removes a deleted row from the view and the persisted copy', async () => {
+ const fetchSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValue(responseOf([identity('i1'), identity('i2')]));
+ vi.spyOn(memoryCRUDService, 'deleteIdentity').mockResolvedValue(undefined);
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), { wrapper });
+ await waitFor(() => expect(listState().identities).toHaveLength(2));
+
+ fetchSpy.mockResolvedValue(responseOf([identity('i2')]));
+ await act(async () => {
+ await listState().deleteIdentity('i1');
+ });
+
+ await waitFor(() => expect(listState().identities.map((item) => item.id)).toEqual(['i2']));
+ const stored = await identityListResource.storage!.get({
+ queryKey: STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect((stored?.data as IdentityListView).items.map((item) => item.id)).toEqual(['i2']);
+ });
+
+ it('removes a deleted identity from every persisted query, not only the one on screen', async () => {
+ const FILTERED = { ...PARAMS, q: 'mentor' };
+ const fetchSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValue(responseOf([identity('i1'), identity('i2')]));
+ vi.spyOn(memoryCRUDService, 'deleteIdentity').mockResolvedValue(undefined);
+
+ // Visit the unfiltered list (persisted), then search: the user deletes from
+ // the search, so the unfiltered variant is no longer the loaded one.
+ const { rerender } = renderHook(
+ ({ params }) => useUserMemoryStore((s) => s.useFetchIdentities)(params),
+ { initialProps: { params: PARAMS as typeof FILTERED | typeof PARAMS }, wrapper },
+ );
+ await waitFor(async () => {
+ const stored = await identityListResource.storage!.get({
+ queryKey: STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect((stored?.data as IdentityListView | undefined)?.items).toHaveLength(2);
+ });
+ fetchSpy.mockResolvedValue(responseOf([identity('i1')]));
+ rerender({ params: FILTERED });
+ await waitFor(() => expect(listState().identities.map((item) => item.id)).toEqual(['i1']));
+
+ fetchSpy.mockResolvedValue(responseOf([]));
+ await act(async () => {
+ await listState().deleteIdentity('i1');
+ });
+
+ expect(listState().identities).toEqual([]);
+ await waitFor(async () => {
+ const stored = await identityListResource.storage!.get({
+ queryKey: STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect((stored?.data as IdentityListView).items.map((item) => item.id)).toEqual(['i2']);
+ });
+ });
+
+ it('patches one row in the list view and persists it', async () => {
+ vi.spyOn(userMemoryService, 'queryIdentities').mockResolvedValue(
+ responseOf([identity('i1', { description: 'old' })]),
+ );
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), { wrapper });
+ await waitFor(() => expect(listState().identities).toHaveLength(1));
+
+ act(() => {
+ listState().internal_updateIdentityEntity('i1', (item) => ({ ...item, description: 'new' }));
+ });
+
+ expect(listState().identities[0].description).toBe('new');
+ await waitFor(async () => {
+ const stored = await identityListResource.storage!.get({
+ queryKey: STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect((stored?.data as IdentityListView).items[0].description).toBe('new');
+ });
+ });
+
+ it('drops the previous user’s list on an account switch', async () => {
+ vi.spyOn(userMemoryService, 'queryIdentities').mockResolvedValue(
+ responseOf([identity('i1', { title: 'Personal' })]),
+ );
+
+ const { rerender } = renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), {
+ wrapper,
+ });
+ await waitFor(() => expect(listState().identities).toHaveLength(1));
+
+ // Switch account: the new user's list is still in flight.
+ useScope(`identity-user-${randomUUID()}:personal`);
+ vi.spyOn(userMemoryService, 'queryIdentities').mockImplementation(pending);
+ rerender();
+
+ expect(listState().identities).toEqual([]);
+ expect(listState().identitiesInit).toBe(false);
+ });
+
+ it('keeps the user’s list across a workspace switch (memories are per user)', async () => {
+ vi.spyOn(userMemoryService, 'queryIdentities').mockResolvedValue(
+ responseOf([identity('i1', { title: 'Personal' })]),
+ );
+
+ const { rerender } = renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), {
+ wrapper,
+ });
+ await waitFor(() => expect(listState().identities).toHaveLength(1));
+
+ useScope(`${scope.split(':')[0]}:ws-1`);
+ vi.spyOn(userMemoryService, 'queryIdentities').mockImplementation(pending);
+ rerender();
+
+ expect(listState().identities.map((item) => item.id)).toEqual(['i1']);
+ expect(listState().identitiesInit).toBe(true);
+ });
+
+ it('clears the view (and the persisted row) when told to reset', async () => {
+ const fetchSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValue(responseOf([identity('i1')]));
+
+ renderHook(() => useUserMemoryStore((s) => s.useFetchIdentities)(PARAMS), { wrapper });
+ await waitFor(() => expect(listState().identities).toHaveLength(1));
+
+ // The purge emptied the server; the clear itself is synchronous.
+ fetchSpy.mockResolvedValue(responseOf([]));
+ let reset!: Promise<boolean>;
+ act(() => {
+ reset = listState().internal_clearIdentityList();
+ });
+
+ expect(listState().identities).toEqual([]);
+ expect(identitySelectors.identitiesTotal(listState())).toBe(0);
+ await act(async () => {
+ await expect(reset).resolves.toBe(true);
+ });
+ // The deleted row is gone from the persisted copy (at most the refetched empty page remains).
+ const stored = await identityListResource.storage!.get({
+ queryKey: STORAGE_KEY,
+ scope: rowScope,
+ });
+ expect((stored?.data as IdentityListView | undefined)?.items ?? []).toEqual([]);
+ });
+
+ it('clears every persisted query of the list on reset, not only the one on screen', async () => {
+ const FILTERED = { ...PARAMS, q: 'mentor' };
+ const FILTERED_KEY = identityListResource.storageKey(FILTERED);
+ const fetchSpy = vi
+ .spyOn(userMemoryService, 'queryIdentities')
+ .mockResolvedValue(responseOf([identity('i1')]));
+
+ // Visit the unfiltered list, then switch to a search: two persisted rows.
+ const { rerender } = renderHook(
+ ({ params }) => useUserMemoryStore((s) => s.useFetchIdentities)(params),
+ { initialProps: { params: PARAMS as typeof FILTERED | typeof PARAMS }, wrapper },
+ );
+ await waitFor(async () => {
+ await expect(
+ identityListResource.storage!.get({ queryKey: STORAGE_KEY, scope: rowScope }),
+ ).resolves.toBeDefined();
+ });
+ fetchSpy.mockResolvedValue(responseOf([identity('i2')]));
+ rerender({ params: FILTERED });
+ await waitFor(async () => {
+ await expect(
+ identityListResource.storage!.get({ queryKey: FILTERED_KEY, scope: rowScope }),
+ ).resolves.toBeDefined();
+ });
+
+ // The purge deleted everything server-side; the mounted query refetches.
+ fetchSpy.mockResolvedValue(responseOf([]));
+ await act(async () => {
+ await listState().internal_clearIdentityList();
+ });
+
+ // The unfiltered projection must not survive to pre-hydrate after a reload.
+ await expect(
+ identityListResource.storage!.get({ queryKey: STORAGE_KEY, scope: rowScope }),
+ ).resolves.toBeUndefined();
+ // The query on screen holds at most the server's (empty) answer.
+ const filtered = await identityListResource.storage!.get({
+ queryKey: FILTERED_KEY,
+ scope: rowScope,
+ });
+ expect((filtered?.data as IdentityListView | undefined)?.items ?? []).toEqual([]);
+ });
+});
diff --git a/src/store/userMemory/slices/identity/selectors.ts b/src/store/userMemory/slices/identity/selectors.ts
index 77113e0c33e..38234ebfb37 100644
--- a/src/store/userMemory/slices/identity/selectors.ts
+++ b/src/store/userMemory/slices/identity/selectors.ts
@@ -16,4 +16,25 @@ export const identitySelectors = {
* Check if there are any global identities
*/
hasGlobalIdentities: (state: UserMemoryStoreState): boolean => state.globalIdentities.length > 0,
+
+ /**
+ * Whether the identity list has loaded its first page. The page controls stay
+ * mounted across a query change, so this survives a search reset.
+ */
+ isIdentitiesInitialized: (state: UserMemoryStoreState): boolean => state.identitiesInit,
+
+ /** Whether another identity page can be appended after the loaded ones. */
+ identitiesHasMore: (state: UserMemoryStoreState): boolean =>
+ state.identitiesMeta?.hasMore ?? false,
+
+ /** Whether a "load more" request for the next identity page is in flight. */
+ identitiesIsLoadingMore: (state: UserMemoryStoreState): boolean =>
+ state.identitiesMeta?.isLoadingMore ?? false,
+
+ /** Failure of the last "load more" request, cleared by the next attempt. */
+ identitiesLoadMoreError: (state: UserMemoryStoreState): unknown =>
+ state.identitiesMeta?.loadMoreError,
+
+ /** Row count of the *current* query, not the whole collection. */
+ identitiesTotal: (state: UserMemoryStoreState): number => state.identitiesMeta?.total ?? 0,
};
diff --git a/src/store/userMemory/slices/listRequestGuard.test.ts b/src/store/userMemory/slices/listRequestGuard.test.ts
deleted file mode 100644
index 5bdafd2790f..00000000000
--- a/src/store/userMemory/slices/listRequestGuard.test.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-import { beforeEach, describe, expect, it } from 'vitest';
-
-import { useUserMemoryStore } from '@/store/userMemory';
-import { initialState } from '@/store/userMemory/initialState';
-
-interface GuardCase {
- accept: (request: { page: number; pageSize: number; q?: string }) => void;
- fail: (error: Error, request: { page: number; pageSize: number; q?: string }) => void;
- name: string;
- readList: () => unknown[];
- readSearchError: () => unknown;
- readSearchLoading: () => boolean | undefined;
- resetWithSearch: () => void;
- seedPageTwo: () => void;
- seedSettledSearch: () => void;
-}
-
-const cases: GuardCase[] = [
- {
- accept: (request) =>
- useUserMemoryStore
- .getState()
- .internal_acceptActivitiesList(
- { items: [], page: request.page, pageSize: request.pageSize, total: 22 },
- request,
- ),
- fail: (error, request) =>
- useUserMemoryStore.getState().internal_failActivitiesList(error, request),
- name: 'activities',
- readList: () => useUserMemoryStore.getState().activities,
- readSearchError: () => useUserMemoryStore.getState().activitiesSearchError,
- readSearchLoading: () => useUserMemoryStore.getState().activitiesSearchLoading,
- resetWithSearch: () => useUserMemoryStore.getState().resetActivitiesList({ q: 'late night' }),
- seedSettledSearch: () =>
- useUserMemoryStore.setState({
- activities: [{ id: 'existing' } as never],
- activitiesInit: true,
- activitiesQuery: 'late night',
- }),
- seedPageTwo: () =>
- useUserMemoryStore.setState({ activities: [{ id: 'existing' } as never], activitiesPage: 2 }),
- },
- {
- accept: (request) =>
- useUserMemoryStore.getState().internal_acceptContextsList({ items: [], total: 22 }, request),
- fail: (error, request) =>
- useUserMemoryStore.getState().internal_failContextsList(error, request),
- name: 'contexts',
- readList: () => useUserMemoryStore.getState().contexts,
- readSearchError: () => useUserMemoryStore.getState().contextsSearchError,
- readSearchLoading: () => useUserMemoryStore.getState().contextsSearchLoading,
- resetWithSearch: () => useUserMemoryStore.getState().resetContextsList({ q: 'late night' }),
- seedSettledSearch: () =>
- useUserMemoryStore.setState({
- contexts: [{ id: 'existing' } as never],
- contextsInit: true,
- contextsQuery: 'late night',
- }),
- seedPageTwo: () =>
- useUserMemoryStore.setState({ contexts: [{ id: 'existing' } as never], contextsPage: 2 }),
- },
- {
- accept: (request) =>
- useUserMemoryStore
- .getState()
- .internal_acceptExperiencesList(
- { items: [], page: request.page, pageSize: request.pageSize, total: 22 },
- request,
- ),
- fail: (error, request) =>
- useUserMemoryStore.getState().internal_failExperiencesList(error, request),
- name: 'experiences',
- readList: () => useUserMemoryStore.getState().experiences,
- readSearchError: () => useUserMemoryStore.getState().experiencesSearchError,
- readSearchLoading: () => useUserMemoryStore.getState().experiencesSearchLoading,
- resetWithSearch: () => useUserMemoryStore.getState().resetExperiencesList({ q: 'late night' }),
- seedSettledSearch: () =>
- useUserMemoryStore.setState({
- experiences: [{ id: 'existing' } as never],
- experiencesInit: true,
- experiencesQuery: 'late night',
- }),
- seedPageTwo: () =>
- useUserMemoryStore.setState({
- experiences: [{ id: 'existing' } as never],
- experiencesPage: 2,
- }),
- },
- {
- accept: (request) =>
- useUserMemoryStore
- .getState()
- .internal_acceptPreferencesList({ items: [], total: 22 }, request),
- fail: (error, request) =>
- useUserMemoryStore.getState().internal_failPreferencesList(error, request),
- name: 'preferences',
- readList: () => useUserMemoryStore.getState().preferences,
- readSearchError: () => useUserMemoryStore.getState().preferencesSearchError,
- readSearchLoading: () => useUserMemoryStore.getState().preferencesSearchLoading,
- resetWithSearch: () => useUserMemoryStore.getState().resetPreferencesList({ q: 'late night' }),
- seedSettledSearch: () =>
- useUserMemoryStore.setState({
- preferences: [{ id: 'existing' } as never],
- preferencesInit: true,
- preferencesQuery: 'late night',
- }),
- seedPageTwo: () =>
- useUserMemoryStore.setState({
- preferences: [{ id: 'existing' } as never],
- preferencesPage: 2,
- }),
- },
-];
-
-beforeEach(() => {
- useUserMemoryStore.setState(initialState, false);
-});
-
-describe('memory list request guards', () => {
- it.each(cases)('ignores a late $name response after a search reset', (testCase) => {
- testCase.seedPageTwo();
- testCase.resetWithSearch();
- testCase.accept({ page: 2, pageSize: 12 });
-
- expect(testCase.readList()).toEqual([]);
- expect(testCase.readSearchLoading()).toBe(true);
- });
-
- it.each(cases)('keeps $name loading when an obsolete request fails', (testCase) => {
- testCase.seedPageTwo();
- testCase.resetWithSearch();
- testCase.fail(new Error('request failed'), { page: 2, pageSize: 12 });
-
- expect(testCase.readSearchError()).toBeUndefined();
- expect(testCase.readSearchLoading()).toBe(true);
- });
-
- it.each(cases)('preserves the current $name search error after loading settles', (testCase) => {
- testCase.resetWithSearch();
- const error = new Error('request failed');
- testCase.fail(error, { page: 1, pageSize: 12, q: 'late night' });
-
- expect(testCase.readSearchError()).toBe(error);
- expect(testCase.readSearchLoading()).toBe(false);
- });
-
- it.each(cases)('preserves settled $name content when a background refresh fails', (testCase) => {
- testCase.seedSettledSearch();
- testCase.fail(new Error('request failed'), { page: 1, pageSize: 12, q: 'late night' });
-
- expect(testCase.readList()).toHaveLength(1);
- expect(testCase.readSearchError()).toBeUndefined();
- });
-});
diff --git a/src/store/userMemory/slices/memoryLists.replica.test.ts b/src/store/userMemory/slices/memoryLists.replica.test.ts
new file mode 100644
index 00000000000..a1305500a7e
--- /dev/null
+++ b/src/store/userMemory/slices/memoryLists.replica.test.ts
@@ -0,0 +1,712 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The four offset-paged memory lists (activities, contexts, experiences,
+ * preferences) share one implementation (`MemoryQueryList` +
+ * `OffsetListPager`). This suite runs the same local-first, query, purge, edit
+ * and delete/paging guarantees against each of them through the store, with
+ * the real replica engine and IndexedDB-backed storage.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, REPLICA_INDEX_KEY, type ReplicaPagedData } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
+import { LayersEnum } from '@/types/userMemory';
+
+import { initialState } from '../initialState';
+import { useUserMemoryStore } from '../store';
+import { identityScopeOf, MAX_RECENT_MEMORY_QUERIES, memoryListKey } from '../utils/replica';
+import { activityListResource } from './activity/projection';
+import { contextListResource } from './context/projection';
+import { experienceListResource } from './experience/projection';
+import { preferenceListResource } from './preference/projection';
+
+type Row = { id: string; title?: string };
+type ListData = ReplicaPagedData<Row, number> & { q?: string; sort?: string };
+
+interface ListCase {
+ deleteMethod: 'deleteActivity' | 'deleteContext' | 'deleteExperience' | 'deletePreference';
+ /** Fetch method on `userMemoryService`. */
+ fetch: 'queryActivities' | 'queryExperiences' | 'queryMemories';
+ /** Extra args the fetch is scoped by (the memory layer). */
+ fetchArgs?: Record<string, unknown>;
+ name: string;
+ p: string;
+ P: string;
+ /** Server row as the endpoint returns it. */
+ raw: (id: string) => unknown;
+ resource: { storage?: any; storageKey: (params: any) => string };
+ /** Store field / action names, `s` singular and `p` plural. */
+ s: string;
+ S: string;
+ sort: string;
+}
+
+const flat = (id: string) => ({ id, title: id });
+
+const CASES: ListCase[] = [
+ {
+ P: 'Activities',
+ S: 'Activity',
+ deleteMethod: 'deleteActivity',
+ fetch: 'queryActivities',
+ name: 'activities',
+ p: 'activities',
+ raw: flat,
+ resource: activityListResource,
+ s: 'activity',
+ sort: 'startsAt',
+ },
+ {
+ P: 'Contexts',
+ S: 'Context',
+ deleteMethod: 'deleteContext',
+ fetch: 'queryMemories',
+ fetchArgs: { layer: LayersEnum.Context },
+ name: 'contexts',
+ p: 'contexts',
+ raw: (id) => ({ context: {}, memory: { id, title: id } }),
+ resource: contextListResource,
+ s: 'context',
+ sort: 'scoreImpact',
+ },
+ {
+ P: 'Experiences',
+ S: 'Experience',
+ deleteMethod: 'deleteExperience',
+ fetch: 'queryExperiences',
+ name: 'experiences',
+ p: 'experiences',
+ raw: flat,
+ resource: experienceListResource,
+ s: 'experience',
+ sort: 'scoreConfidence',
+ },
+ {
+ P: 'Preferences',
+ S: 'Preference',
+ deleteMethod: 'deletePreference',
+ fetch: 'queryMemories',
+ fetchArgs: { layer: LayersEnum.Preference },
+ name: 'preferences',
+ p: 'preferences',
+ raw: (id) => ({ memory: { id, title: id }, preference: {} }),
+ resource: preferenceListResource,
+ s: 'preference',
+ sort: 'scorePriority',
+ },
+];
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const page = (items: unknown[], total: number) => ({ items, page: 1, pageSize: 12, total });
+
+describe.each(CASES)('$name list replica', (list) => {
+ const scopes = new Set<string>();
+ let scope = '';
+ /** Storage partition of userMemory replicas: the user, not the workspace. */
+ let rowScope = '';
+ let fetchSpy: ReturnType<typeof vi.spyOn>;
+ const queryKeys = new Set<string>();
+
+ const state = () => useUserMemoryStore.getState() as any;
+ const view = (): ListData | undefined => state()[`${list.s}ListData`];
+ const ids = (data?: ListData) => data?.items.map((row) => row.id);
+ const entry = (query: Record<string, unknown>): ListData | undefined =>
+ state()[`${list.s}ListEntries`][memoryListKey(query)];
+ const storageKey = (query: Record<string, unknown> = {}) => {
+ const key = list.resource.storageKey({ pageSize: 12, ...query });
+ queryKeys.add(key);
+ return key;
+ };
+ const stored = async (query: Record<string, unknown> = {}) =>
+ (await list.resource.storage.get({ queryKey: storageKey(query), scope: rowScope }))?.data as
+ ListData | undefined;
+ const persist = (query: Record<string, unknown>, data: ListData) =>
+ list.resource.storage.set(
+ { queryKey: storageKey(query), scope: rowScope },
+ { data, updatedAt: 1 },
+ );
+
+ const useFetch = (query: Record<string, unknown> = {}) =>
+ useUserMemoryStore((s: any) => s[`useFetch${list.P}`])({ pageSize: 12, ...query });
+ const loadMore = () => state()[`loadMore${list.P}`]();
+ const remove = (id: string) => state()[`delete${list.S}`](id) as Promise<void>;
+
+ /** A paged server: `rows` is read at request time, so a test can mutate it. */
+ const serve = (rows: () => string[]) =>
+ fetchSpy.mockImplementation(
+ async ({ page: pageNo = 1, pageSize = 12 }: { page?: number; pageSize?: number } = {}) => {
+ const all = rows();
+ const start = (pageNo - 1) * pageSize;
+ return page(all.slice(start, start + pageSize).map(list.raw), all.length);
+ },
+ );
+ const rowsOf = (length: number) => Array.from({ length }, (_, i) => `r${i}`);
+
+ const useScope = (next: string) => {
+ scope = next;
+ rowScope = identityScopeOf(scope);
+ scopes.add(rowScope);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`${list.name}-user-${randomUUID()}:personal`);
+ fetchSpy = vi.spyOn(userMemoryService, list.fetch as any);
+ act(() => useUserMemoryStore.setState(initialState, false));
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].flatMap((value) => [
+ ...[...queryKeys].map((queryKey) =>
+ list.resource.storage.remove({ queryKey, scope: value }),
+ ),
+ list.resource.storage.remove({ queryKey: REPLICA_INDEX_KEY, scope: value }),
+ ]),
+ );
+ scopes.clear();
+ queryKeys.clear();
+ vi.restoreAllMocks();
+ });
+
+ it('keeps one entry per search / sort, independent of the page size', () => {
+ expect(memoryListKey({ pageSize: 12 })).toBe(memoryListKey({ q: '' }));
+ expect(memoryListKey({ q: 'foo' })).not.toBe(memoryListKey({}));
+ expect(memoryListKey({ sort: list.sort })).not.toBe(memoryListKey({}));
+ });
+
+ it('paints the persisted head page before the network answers', async () => {
+ await persist({}, { currentPage: 0, hasMore: true, items: [flat('cached')], pageSize: 12 });
+ fetchSpy.mockImplementation(pending);
+
+ renderHook(() => useFetch(), { wrapper });
+
+ await waitFor(() => expect(ids(view())).toEqual(['cached']));
+ expect(state()[list.p].map((row: Row) => row.id)).toEqual(['cached']);
+ expect(state()[`${list.p}Init`]).toBe(true);
+ });
+
+ it('pre-hydrates the query a route asks for before it mounts', async () => {
+ await persist(
+ { q: 'foo' },
+ { currentPage: 0, hasMore: false, items: [flat('foo-1')], pageSize: 12, q: 'foo' },
+ );
+ fetchSpy.mockImplementation(pending);
+
+ await expect(state()[`preHydrate${list.P}`]({ q: 'foo' })).resolves.toBe(true);
+
+ expect(ids(entry({ q: 'foo' }))).toEqual(['foo-1']);
+ expect(entry({})).toBeUndefined();
+ });
+
+ it('replaces the head page with the server response and persists it', async () => {
+ serve(() => ['a', 'b']);
+
+ renderHook(() => useFetch(), { wrapper });
+
+ await waitFor(() => expect(ids(view())).toEqual(['a', 'b']));
+ expect(state()[`${list.p}Total`]).toBe(2);
+ expect(state()[list.p][0]).toMatchObject({ id: 'a', title: 'a' });
+ if (list.fetchArgs)
+ expect(fetchSpy).toHaveBeenCalledWith(expect.objectContaining(list.fetchArgs));
+ await waitFor(async () => expect(ids(await stored())).toEqual(['a', 'b']));
+ });
+
+ it('appends the next page with the loaded query params', async () => {
+ serve(() => rowsOf(24));
+
+ renderHook(() => useFetch({ q: 'foo' }), { wrapper });
+ await waitFor(() => expect(view()?.items).toHaveLength(12));
+
+ await act(async () => {
+ await loadMore();
+ });
+
+ await waitFor(() => expect(view()?.items).toHaveLength(24));
+ expect(view()).toMatchObject({ currentPage: 1, hasMore: false });
+ expect(fetchSpy).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2, q: 'foo' }));
+ });
+
+ it('switches queries without dropping a page set, and switches back from memory', async () => {
+ serve(() => ['a']);
+ const hook = renderHook((query: Record<string, unknown>) => useFetch(query), {
+ initialProps: {},
+ wrapper,
+ });
+ await waitFor(() => expect(ids(view())).toEqual(['a']));
+ await waitFor(async () => expect(await stored()).toBeDefined());
+
+ fetchSpy.mockImplementation(pending);
+ hook.rerender({ sort: list.sort });
+
+ // The new query has no rows yet: the previous query's rows never show under it.
+ expect(view()).toBeUndefined();
+ expect(state()[list.p]).toEqual([]);
+ expect(ids(entry({}))).toEqual(['a']);
+ expect(ids(await stored())).toEqual(['a']);
+
+ // Back to the first query while its revalidation hangs: it repaints at once.
+ hook.rerender({});
+ expect(ids(view())).toEqual(['a']);
+ expect(hook.result.current.data).toBeDefined();
+ });
+
+ it('hydrates a query persisted by an earlier session when switching to it', async () => {
+ await persist(
+ { q: 'foo' },
+ { currentPage: 0, hasMore: false, items: [flat('cached-foo')], pageSize: 12, q: 'foo' },
+ );
+ fetchSpy.mockResolvedValueOnce(page([list.raw('a')], 1)).mockImplementation(pending);
+
+ const hook = renderHook((query: Record<string, unknown>) => useFetch(query), {
+ initialProps: {},
+ wrapper,
+ });
+ await waitFor(() => expect(ids(view())).toEqual(['a']));
+
+ hook.rerender({ q: 'foo' });
+
+ await waitFor(() => expect(ids(view())).toEqual(['cached-foo']));
+ });
+
+ it('surfaces only the failure of the query on screen, and keeps painted rows', async () => {
+ const rejectByQuery = new Map<string, (error: Error) => void>();
+ fetchSpy.mockImplementation(
+ (params: { q?: string } = {}) =>
+ new Promise((_, reject) => rejectByQuery.set(params.q ?? '', reject)),
+ );
+
+ const hook = renderHook((query: Record<string, unknown>) => useFetch(query), {
+ initialProps: { q: 'a' } as Record<string, unknown>,
+ wrapper,
+ });
+ await waitFor(() => expect(rejectByQuery.has('a')).toBe(true));
+ hook.rerender({ q: 'b' });
+ await waitFor(() => expect(rejectByQuery.has('b')).toBe(true));
+
+ await act(async () => {
+ rejectByQuery.get('a')!(new Error('stale failure'));
+ });
+ expect(hook.result.current.error).toBeUndefined();
+
+ const failure = new Error('current failure');
+ await act(async () => {
+ rejectByQuery.get('b')!(failure);
+ });
+ await waitFor(() => expect(hook.result.current.error).toBe(failure));
+ });
+
+ it('applies an edit to every loaded and persisted query', async () => {
+ serve(() => ['a', 'b']);
+ const hook = renderHook((query: Record<string, unknown>) => useFetch(query), {
+ initialProps: {},
+ wrapper,
+ });
+ await waitFor(async () => expect(ids(await stored())).toEqual(['a', 'b']));
+ hook.rerender({ q: 'foo' });
+ await waitFor(async () => expect(ids(await stored({ q: 'foo' }))).toEqual(['a', 'b']));
+
+ act(() => {
+ state()[`internal_update${list.S}Entity`]('a', (row: Row) => ({ ...row, title: 'edited' }));
+ });
+
+ expect(view()?.items[0].title).toBe('edited');
+ expect(entry({})?.items[0].title).toBe('edited');
+ await waitFor(async () => {
+ expect((await stored())?.items[0].title).toBe('edited');
+ expect((await stored({ q: 'foo' }))?.items[0].title).toBe('edited');
+ });
+ });
+
+ it('purges every persisted query, not only the one on screen', async () => {
+ serve(() => ['a']);
+ const hook = renderHook((query: Record<string, unknown>) => useFetch(query), {
+ initialProps: {},
+ wrapper,
+ });
+ await waitFor(async () => expect(await stored()).toBeDefined());
+ hook.rerender({ q: 'foo' });
+ await waitFor(async () => expect(await stored({ q: 'foo' })).toBeDefined());
+
+ let cleared = false;
+ await act(async () => {
+ cleared = await state()[`internal_clear${list.S}List`]();
+ });
+
+ expect(cleared).toBe(true);
+ expect(state()[`${list.s}ListEntries`]).toEqual({});
+ expect(state()[list.p]).toEqual([]);
+ await expect(stored()).resolves.toBeUndefined();
+ await expect(stored({ q: 'foo' })).resolves.toBeUndefined();
+ });
+
+ it('purges the deleted user’s persisted queries after an account switch, not the active user’s', async () => {
+ serve(() => ['a']);
+ const hook = renderHook((query: Record<string, unknown>) => useFetch(query), {
+ initialProps: {},
+ wrapper,
+ });
+ await waitFor(async () => expect(await stored()).toBeDefined());
+ hook.rerender({ q: 'foo' });
+ await waitFor(async () => expect(await stored({ q: 'foo' })).toBeDefined());
+ hook.unmount();
+ const deletedUser = rowScope;
+
+ // Another account becomes active and paints its own list.
+ useScope(`${list.name}-user-${randomUUID()}:personal`);
+ serve(() => ['b']);
+ renderHook(() => useFetch(), { wrapper });
+ await waitFor(() => expect(ids(view())).toEqual(['b']));
+ await waitFor(async () => expect(ids(await stored())).toEqual(['b']));
+
+ let cleared = false;
+ await act(async () => {
+ cleared = await state()[`internal_clear${list.S}List`](deletedUser);
+ });
+
+ expect(cleared).toBe(true);
+ const deletedRow = (query: Record<string, unknown>) =>
+ list.resource.storage.get({ queryKey: storageKey(query), scope: deletedUser });
+ await expect(deletedRow({})).resolves.toBeUndefined();
+ await expect(deletedRow({ q: 'foo' })).resolves.toBeUndefined();
+ // The active user's view and persisted row are untouched.
+ expect(ids(view())).toEqual(['b']);
+ expect(ids(await stored())).toEqual(['b']);
+ });
+
+ it('removes a row optimistically and rolls it back when the server rejects', async () => {
+ serve(() => ['a', 'b']);
+ renderHook(() => useFetch(), { wrapper });
+ await waitFor(() => expect(ids(view())).toEqual(['a', 'b']));
+
+ let reject: ((error: Error) => void) | undefined;
+ vi.spyOn(memoryCRUDService, list.deleteMethod).mockImplementation(
+ () => new Promise((_, rej) => (reject = rej)) as never,
+ );
+
+ let deleting!: Promise<void>;
+ act(() => {
+ deleting = remove('a');
+ });
+ expect(ids(view())).toEqual(['b']);
+ await waitFor(() => expect(reject).toBeTypeOf('function'));
+
+ await act(async () => {
+ reject!(new Error('offline'));
+ await expect(deleting).rejects.toThrow('offline');
+ });
+ expect(ids(view())).toEqual(['a', 'b']);
+ });
+
+ it('drops a deleted row from the view and the persisted row', async () => {
+ let server = ['a', 'b'];
+ serve(() => server);
+ vi.spyOn(memoryCRUDService, list.deleteMethod).mockResolvedValue(undefined as never);
+ renderHook(() => useFetch(), { wrapper });
+ await waitFor(() => expect(ids(view())).toEqual(['a', 'b']));
+
+ server = ['b'];
+ await act(async () => {
+ await remove('a');
+ });
+
+ expect(ids(view())).toEqual(['b']);
+ await waitFor(async () => expect(ids(await stored())).toEqual(['b']));
+ });
+
+ it('keeps offset pagination contiguous after deleting from a loaded page', async () => {
+ let server = rowsOf(30);
+ serve(() => server);
+ vi.spyOn(memoryCRUDService, list.deleteMethod).mockResolvedValue(undefined as never);
+ renderHook(() => useFetch(), { wrapper });
+ await waitFor(() => expect(view()?.items).toHaveLength(12));
+ await act(async () => {
+ await loadMore();
+ });
+ await waitFor(() => expect(view()?.items).toHaveLength(24));
+
+ server = server.filter((id) => id !== 'r5');
+ await act(async () => {
+ await remove('r5');
+ });
+ // Collapsed to a refetched head.
+ await waitFor(() => expect(ids(view())).toEqual(server.slice(0, 12)));
+
+ await act(async () => {
+ await loadMore();
+ });
+
+ // No row skipped at the page boundary by a stale offset.
+ await waitFor(() => expect(ids(view())).toEqual(server.slice(0, 24)));
+ });
+
+ it('never pages from a stale offset when the post-delete head refresh fails', async () => {
+ let server = rowsOf(30);
+ let headDown = false;
+ fetchSpy.mockImplementation(
+ async ({ page: pageNo = 1, pageSize = 12 }: { page?: number; pageSize?: number } = {}) => {
+ if (pageNo === 1 && headDown) throw new Error('head down');
+ const start = (pageNo - 1) * pageSize;
+ return page(server.slice(start, start + pageSize).map(list.raw), server.length);
+ },
+ );
+ vi.spyOn(memoryCRUDService, list.deleteMethod).mockResolvedValue(undefined as never);
+ renderHook(() => useFetch(), { wrapper });
+ await waitFor(() => expect(view()?.items).toHaveLength(12));
+
+ server = server.filter((id) => id !== 'r5');
+ headDown = true;
+ await act(async () => {
+ await remove('r5');
+ });
+
+ fetchSpy.mockClear();
+ await act(async () => {
+ await loadMore();
+ });
+
+ // The head was retried first; no page 2 was asked for, and the footer shows the failure.
+ expect(fetchSpy).toHaveBeenCalled();
+ expect(fetchSpy).not.toHaveBeenCalledWith(expect.objectContaining({ page: 2 }));
+ expect(view()?.loadMoreError).toBeInstanceOf(Error);
+
+ // The retry refreshes the head, then pages contiguously.
+ headDown = false;
+ await act(async () => {
+ await loadMore();
+ });
+ await waitFor(() => expect(ids(view())).toEqual(server.slice(0, 24)));
+ expect(view()?.loadMoreError).toBeUndefined();
+ });
+
+ it('never pages a persisted query a delete shortened, even after a reload, when its head refresh fails', async () => {
+ let server = rowsOf(30);
+ let headDown = false;
+ fetchSpy.mockImplementation(
+ async ({ page: pageNo = 1, pageSize = 12 }: { page?: number; pageSize?: number } = {}) => {
+ if (pageNo === 1 && headDown) throw new Error('head down');
+ const start = (pageNo - 1) * pageSize;
+ return page(server.slice(start, start + pageSize).map(list.raw), server.length);
+ },
+ );
+ vi.spyOn(memoryCRUDService, list.deleteMethod).mockResolvedValue(undefined as never);
+
+ // Query B (a search) was persisted earlier...
+ const search = renderHook(() => useFetch({ q: 'foo' }), { wrapper });
+ await waitFor(async () => expect((await stored({ q: 'foo' }))?.items).toHaveLength(12));
+ search.unmount();
+ // ...and a reload leaves it in storage only.
+ act(() => useUserMemoryStore.setState(initialState, false));
+
+ // Delete from query A: B's persisted row is patched (not loaded, not marked).
+ const base = renderHook(() => useFetch(), { wrapper });
+ await waitFor(() => expect(view()?.items).toHaveLength(12));
+ server = server.filter((id) => id !== 'r5');
+ await act(async () => {
+ await remove('r5');
+ });
+ await waitFor(async () => expect((await stored({ q: 'foo' }))?.items).toHaveLength(11));
+ base.unmount();
+
+ // Open B while its head revalidation fails: it paints the shortened row.
+ headDown = true;
+ const reopened = renderHook(() => useFetch({ q: 'foo' }), { wrapper });
+ await waitFor(() => expect(view()?.items).toHaveLength(11));
+
+ fetchSpy.mockClear();
+ await act(async () => {
+ await loadMore();
+ });
+
+ // No page 2 from the shifted offset (it would skip r12); the footer shows why.
+ expect(fetchSpy).not.toHaveBeenCalledWith(expect.objectContaining({ page: 2 }));
+ expect(view()?.loadMoreError).toBeInstanceOf(Error);
+
+ // Once the head is back, the retry pages contiguously.
+ headDown = false;
+ await act(async () => {
+ await loadMore();
+ });
+ await waitFor(() => expect(ids(view())).toEqual(server.slice(0, 24)));
+ reopened.unmount();
+ });
+
+ it('makes a delete wait for a page in flight, so the page cannot land past the shift', async () => {
+ let server = rowsOf(30);
+ let releasePage!: () => void;
+ const pageGate = new Promise<void>((resolve) => (releasePage = resolve));
+ fetchSpy.mockImplementation(
+ async ({ page: pageNo = 1, pageSize = 12 }: { page?: number; pageSize?: number } = {}) => {
+ // The first page-2 request is held while the user deletes.
+ if (pageNo === 2) await pageGate;
+ const start = (pageNo - 1) * pageSize;
+ return page(server.slice(start, start + pageSize).map(list.raw), server.length);
+ },
+ );
+ const serverDelete = vi
+ .spyOn(memoryCRUDService, list.deleteMethod)
+ .mockImplementation(async () => {
+ server = server.filter((id) => id !== 'r5');
+ return undefined as never;
+ });
+ renderHook(() => useFetch(), { wrapper });
+ await waitFor(() => expect(view()?.items).toHaveLength(12));
+
+ let paging!: Promise<void>;
+ let deleting!: Promise<void>;
+ act(() => {
+ paging = loadMore();
+ deleting = remove('r5');
+ });
+ await waitFor(() => expect(view()?.isLoadingMore).toBe(true));
+ expect(serverDelete).not.toHaveBeenCalled();
+
+ await act(async () => {
+ releasePage();
+ await Promise.all([paging, deleting]);
+ });
+ await act(async () => {
+ await loadMore();
+ });
+
+ await waitFor(() => expect(ids(view())).toEqual(server.slice(0, 24)));
+ });
+
+ it('reports a page in flight and a failed page for the list footer', async () => {
+ let failPage = false;
+ let releasePage: (() => void) | undefined;
+ fetchSpy.mockImplementation(async ({ page: pageNo = 1 }: { page?: number } = {}) => {
+ if (pageNo === 2) {
+ await new Promise<void>((resolve) => (releasePage = resolve));
+ if (failPage) throw new Error('page failed');
+ }
+ return page(rowsOf(12).map(list.raw), 24);
+ });
+ const hook = renderHook(() => useFetch(), { wrapper });
+ await waitFor(() => expect(view()?.items).toHaveLength(12));
+ expect(hook.result.current.isLoading).toBe(false);
+
+ failPage = true;
+ let paging!: Promise<void>;
+ act(() => {
+ paging = loadMore();
+ });
+ await waitFor(() => expect(hook.result.current.isLoading).toBe(true));
+ expect(view()?.isLoadingMore).toBe(true);
+
+ await act(async () => {
+ releasePage!();
+ await paging;
+ });
+ expect(hook.result.current.isLoading).toBe(false);
+ expect(view()?.loadMoreError).toBeInstanceOf(Error);
+ // A failed page is the footer's, not a full-surface error.
+ expect(hook.result.current.error).toBeUndefined();
+ });
+
+ it('does not fetch another page when the head page is the last one', async () => {
+ serve(() => ['only']);
+ renderHook(() => useFetch(), { wrapper });
+ await waitFor(() => expect(view()?.items).toHaveLength(1));
+ expect(state()[`${list.p}HasMore`]).toBe(false);
+
+ await act(async () => {
+ await loadMore();
+ });
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('bounds how many query page sets are kept', async () => {
+ fetchSpy.mockImplementation(async ({ q }: { q?: string } = {}) => page([list.raw(`${q}`)], 1));
+ const queries = Array.from({ length: MAX_RECENT_MEMORY_QUERIES + 2 }, (_, i) => `q-${i}`);
+ for (const q of queries) storageKey({ q });
+
+ const hook = renderHook((props: { q: string }) => useFetch({ q: props.q }), {
+ initialProps: { q: queries[0] },
+ wrapper,
+ });
+ for (const q of queries.slice(1)) {
+ hook.rerender({ q });
+ await waitFor(() => expect(entry({ q })).toBeDefined());
+ }
+
+ expect(Object.keys(state()[`${list.s}ListEntries`])).toHaveLength(MAX_RECENT_MEMORY_QUERIES);
+ expect(entry({ q: queries[0] })).toBeUndefined();
+ // Evicted from IndexedDB too, not only from memory.
+ await waitFor(async () => expect(await stored({ q: queries[0] })).toBeUndefined());
+ expect(await stored({ q: queries.at(-1) })).toBeDefined();
+ });
+
+ it('never evicts the query on screen, however many others are visited', async () => {
+ fetchSpy.mockImplementation(async ({ q }: { q?: string } = {}) => page([list.raw(`${q}`)], 1));
+ const queries = Array.from({ length: MAX_RECENT_MEMORY_QUERIES + 3 }, (_, i) => `other-${i}`);
+ for (const q of [...queries, 'pinned']) storageKey({ q });
+
+ // The pinned query stays mounted (oldest of all) while the others cycle.
+ renderHook(() => useFetch({ q: 'pinned' }), { wrapper });
+ await waitFor(async () => expect(await stored({ q: 'pinned' })).toBeDefined());
+ const other = renderHook((props: { q: string }) => useFetch({ q: props.q }), {
+ initialProps: { q: queries[0] },
+ wrapper,
+ });
+ for (const q of queries) {
+ other.rerender({ q });
+ await waitFor(async () => expect(await stored({ q })).toBeDefined());
+ }
+
+ expect(entry({ q: 'pinned' })).toBeDefined();
+ expect(await stored({ q: 'pinned' })).toBeDefined();
+ await waitFor(async () => expect(await stored({ q: queries[0] })).toBeUndefined());
+ });
+
+ it('keeps the cap across reloads, from the queries an earlier session persisted', async () => {
+ // An earlier session persisted the cap's worth of queries (index oldest first).
+ const previous = Array.from({ length: MAX_RECENT_MEMORY_QUERIES }, (_, i) => `old-${i}`);
+ for (const q of previous) {
+ await persist({ q }, { currentPage: 0, hasMore: false, items: [flat(q)], pageSize: 12, q });
+ }
+ await list.resource.storage.set(
+ { queryKey: REPLICA_INDEX_KEY, scope: rowScope },
+ { data: previous.map((q) => storageKey({ q })), updatedAt: 1 },
+ );
+ fetchSpy.mockImplementation(async ({ q }: { q?: string } = {}) => page([list.raw(`${q}`)], 1));
+ storageKey({ q: 'fresh' });
+
+ renderHook(() => useFetch({ q: 'fresh' }), { wrapper });
+ await waitFor(async () => expect(await stored({ q: 'fresh' })).toBeDefined());
+
+ // The least recently used persisted query made room; the others stay.
+ await waitFor(async () => expect(await stored({ q: 'old-0' })).toBeUndefined());
+ expect(await stored({ q: 'old-1' })).toBeDefined();
+ const index = await list.resource.storage.get({ queryKey: REPLICA_INDEX_KEY, scope: rowScope });
+ expect(index?.data as string[]).toHaveLength(MAX_RECENT_MEMORY_QUERIES);
+ });
+});
diff --git a/src/store/userMemory/slices/preference/action.test.ts b/src/store/userMemory/slices/preference/action.test.ts
deleted file mode 100644
index 0cbfa5b59c9..00000000000
--- a/src/store/userMemory/slices/preference/action.test.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { beforeEach, describe, expect, it } from 'vitest';
-
-import { useUserMemoryStore } from '@/store/userMemory';
-import { initialState } from '@/store/userMemory/initialState';
-
-const resultItem = (id: string) => ({ memory: { id }, preference: {} });
-
-beforeEach(() => {
- useUserMemoryStore.setState(
- {
- ...initialState,
- preferences: [{ id: 'existing' } as never],
- preferencesInit: true,
- preferencesPage: 2,
- preferencesQuery: undefined,
- preferencesSearchLoading: false,
- preferencesTotal: 22,
- },
- false,
- );
-});
-
-describe('preference actions', () => {
- it('ignores a late response from the list state that preceded a search', () => {
- useUserMemoryStore.getState().resetPreferencesList({ q: 'late night' });
- useUserMemoryStore
- .getState()
- .internal_acceptPreferencesList(
- { items: [resultItem('matching')], total: 1 },
- { page: 1, pageSize: 12, q: 'late night' },
- );
- useUserMemoryStore
- .getState()
- .internal_acceptPreferencesList(
- { items: [resultItem('stale')], total: 22 },
- { page: 2, pageSize: 12 },
- );
-
- expect(useUserMemoryStore.getState()).toMatchObject({
- preferences: [{ id: 'matching' }],
- preferencesSearchLoading: false,
- preferencesTotal: 1,
- });
- });
-
- it('accepts an earlier page when pagination advances before its response arrives', () => {
- useUserMemoryStore.setState({ preferencesPage: 3 });
- useUserMemoryStore
- .getState()
- .internal_acceptPreferencesList(
- { items: [resultItem('page-2')], total: 22 },
- { page: 2, pageSize: 12 },
- );
-
- expect(useUserMemoryStore.getState().preferences).toEqual([
- { id: 'existing' },
- { id: 'page-2' },
- ]);
- });
-});
diff --git a/src/store/userMemory/slices/preference/action.ts b/src/store/userMemory/slices/preference/action.ts
index 99aab4fa64d..d8083e77da8 100644
--- a/src/store/userMemory/slices/preference/action.ts
+++ b/src/store/userMemory/slices/preference/action.ts
@@ -1,8 +1,5 @@
-import { uniqBy } from 'es-toolkit/compat';
-import { produce } from 'immer';
-import { useEffect } from 'react';
+import { type PreferenceMemorySimple, type UserMemoryItemSimple } from '@lobechat/types';
import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
import { type DisplayPreferenceMemory } from '@/database/repositories/userMemory';
import { userMemoryKeys } from '@/libs/swr/keys';
@@ -11,179 +8,138 @@ import { type StoreSetter } from '@/store/types';
import { LayersEnum } from '@/types/userMemory';
import { setNamespace } from '@/utils/storeDebug';
-import { type UserMemoryStore } from '../../store';
-import { isMemoryListRequestCurrent } from '../utils/isMemoryListRequestCurrent';
-import { shouldSurfaceMemoryListError } from '../utils/shouldSurfaceMemoryListError';
+import { type UserMemoryStore, useUserMemoryStore } from '../../store';
+import { type MemoryListPageResult, MemoryQueryList } from '../utils/memoryQueryList';
+import {
+ PREFERENCE_LIST_PAGE_SIZE,
+ type PreferenceListData,
+ type PreferenceListParams,
+ preferenceListResource,
+} from './projection';
const n = setNamespace('userMemory/preference');
-export interface PreferenceQueryParams {
+export interface PreferenceQueryParams extends Partial<PreferenceListParams> {
page?: number;
- pageSize?: number;
- q?: string;
- sort?: 'capturedAt' | 'scorePriority';
}
-type PreferenceListRequest = PreferenceQueryParams & { page: number };
+/** Flat mirrors of one page set (`undefined` = the active query has no view yet). */
+const mirrorsOf = (data: PreferenceListData | undefined): Partial<UserMemoryStore> =>
+ data
+ ? {
+ preferenceListData: data,
+ preferences: data.items,
+ preferencesHasMore: data.hasMore,
+ preferencesInit: true,
+ preferencesPage: data.currentPage + 1,
+ preferencesTotal: data.total ?? data.items.length,
+ }
+ : {
+ preferenceListData: undefined,
+ preferences: [],
+ preferencesHasMore: true,
+ preferencesInit: false,
+ preferencesPage: 1,
+ preferencesTotal: 0,
+ };
+
+/**
+ * Flatten a `queryMemories` row into the display shape the preference list
+ * renders. The endpoint returns `{ memory, preference }`; the row is merged in
+ * the same order the previous slice did.
+ */
+const toDisplayPreference = (item: UserMemoryItemSimple): DisplayPreferenceMemory => {
+ const { memory, preference } = item as PreferenceMemorySimple;
+ return { ...memory, ...preference } as unknown as DisplayPreferenceMemory;
+};
type Setter = StoreSetter<UserMemoryStore>;
export const createPreferenceSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
new PreferenceActionImpl(set, get, _api);
+/**
+ * The user-memory preference list: one `MemoryQueryList` (shared with the other
+ * offset-paged memory lists) behind the slice's long-standing action names.
+ */
export class PreferenceActionImpl {
- readonly #get: () => UserMemoryStore;
- readonly #set: Setter;
+ readonly #list: MemoryQueryList<
+ PreferenceListParams,
+ DisplayPreferenceMemory,
+ PreferenceListData
+ >;
constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
void _api;
- this.#set = set;
- this.#get = get;
+ this.#list = new MemoryQueryList({
+ actionPrefix: n('preferenceList'),
+ activeKeyField: 'preferenceListKey',
+ entriesField: 'preferenceListEntries',
+ fetchPage: async (params, page) => {
+ const response = await userMemoryService.queryMemories({
+ layer: LayersEnum.Preference,
+ page,
+ pageSize: params.pageSize,
+ q: params.q,
+ sort: params.sort,
+ });
+ return { items: response.items.map(toDisplayPreference), total: response.total };
+ },
+ get,
+ mirror: mirrorsOf,
+ queryFields: ({ q, sort }) => ({ preferencesQuery: q || undefined, preferencesSort: sort }),
+ replicaField: 'preferenceListReplica',
+ resource: preferenceListResource,
+ rootKey: userMemoryKeys.preferences.root,
+ set,
+ useStore: (selector) => useUserMemoryStore(selector),
+ });
}
- deletePreference = async (id: string): Promise<void> => {
- await memoryCRUDService.deletePreference(id);
- // Reset list to refresh
- this.#get().resetPreferencesList({
- q: this.#get().preferencesQuery,
- sort: this.#get().preferencesSort,
- });
- };
+ /** Delete one preference: optimistic, then the offset repair (see `OffsetListPager`). */
+ deletePreference = (id: string): Promise<void> =>
+ this.#list.delete(id, () => memoryCRUDService.deletePreference(id));
- loadMorePreferences = (): void => {
- const { preferencesPage, preferencesTotal, preferences } = this.#get();
- if (preferences.length < (preferencesTotal || 0)) {
- this.#set(
- produce((draft) => {
- draft.preferencesPage = preferencesPage + 1;
- }),
- false,
- n('loadMorePreferences'),
- );
- }
+ /** Purge for "delete all memories" (every query, memory + IndexedDB). */
+ internal_clearPreferenceList = (user?: string): Promise<boolean> => this.#list.clear(user);
+
+ /** Confirmed edit of one preference in every loaded and persisted query. */
+ internal_updatePreferenceEntity = (
+ id: string,
+ fn: (item: DisplayPreferenceMemory) => DisplayPreferenceMemory,
+ ): void => {
+ this.#list.updateEntity(id, fn);
};
- internal_acceptPreferencesList = (data: any, request: PreferenceListRequest): void => {
- const state = this.#get();
- if (
- !isMemoryListRequestCurrent(
- {
- page: state.preferencesPage,
- q: state.preferencesQuery,
- sort: state.preferencesSort,
- },
- { page: request.page, q: request.q, sort: request.sort },
- )
- )
- return;
-
- this.#set(
- produce((draft) => {
- draft.preferencesSearchError = undefined;
- draft.preferencesSearchLoading = false;
- draft.preferencesTotal = data.total;
-
- if (!draft.preferencesInit) {
- draft.preferencesInit = true;
- }
-
- const transformedItems: DisplayPreferenceMemory[] = data.items.map((item: any) => ({
- ...item.memory,
- ...item.preference,
- }));
-
- if (request.page === 1) {
- draft.preferences = uniqBy(transformedItems, 'id');
- } else {
- draft.preferences = uniqBy([...draft.preferences, ...transformedItems], 'id');
- }
-
- draft.preferencesHasMore = data.items.length >= (request.pageSize || 20);
- }),
- false,
- n('internal_acceptPreferencesList'),
- );
+ /** Append the next page of the query on screen. */
+ loadMorePreferences = (): void => {
+ void this.#list.loadMore();
};
- internal_failPreferencesList = (error: unknown, request: PreferenceListRequest): void => {
- const state = this.#get();
- if (
- !isMemoryListRequestCurrent(
- {
- page: state.preferencesPage,
- q: state.preferencesQuery,
- sort: state.preferencesSort,
- },
- { page: request.page, q: request.q, sort: request.sort },
- )
- )
- return;
-
- const shouldSurfaceError = shouldSurfaceMemoryListError({
- initialized: state.preferencesInit,
- page: request.page,
- resetting: state.preferencesSearchLoading,
+ /** Seed the persisted head page of a query before its route paints. */
+ preHydratePreferences = (
+ query?: Omit<PreferenceQueryParams, 'page' | 'pageSize'>,
+ ): Promise<boolean> =>
+ this.#list.preHydrate({
+ ...query,
+ pageSize: PREFERENCE_LIST_PAGE_SIZE,
+ q: query?.q || undefined,
});
- this.#set(
- produce((draft) => {
- if (shouldSurfaceError) draft.preferencesSearchError = error;
- draft.preferencesSearchLoading = false;
- }),
- false,
- n('internal_failPreferencesList'),
- );
- };
-
+ /** Point the list at another search / sort (no page set is dropped). */
resetPreferencesList = (params?: Omit<PreferenceQueryParams, 'page' | 'pageSize'>): void => {
- this.#set(
- produce((draft) => {
- draft.preferences = [];
- draft.preferencesPage = 1;
- draft.preferencesQuery = params?.q;
- draft.preferencesSearchError = undefined;
- draft.preferencesSearchLoading = true;
- draft.preferencesSort = params?.sort;
- }),
- false,
- n('resetPreferencesList'),
- );
+ this.#list.select({ ...params, q: params?.q || undefined });
};
- /**
- * Hydrate the store from SWR's rendered state because deduped cache hits do not invoke SWR's
- * request lifecycle callbacks.
- */
- useFetchPreferences = (params: PreferenceQueryParams): SWRResponse<any> => {
- const page = params.page ?? 1;
- const response = useSWR(
- userMemoryKeys.preferences(params),
- async () => {
- const result = await userMemoryService.queryMemories({
- layer: LayersEnum.Preference,
- page: params.page,
- pageSize: params.pageSize,
- q: params.q,
- sort: params.sort,
- });
-
- return result;
- },
- {
- revalidateOnFocus: false,
- },
- );
-
- useEffect(() => {
- if (response.data !== undefined)
- this.internal_acceptPreferencesList(response.data, { ...params, page });
- }, [page, params.pageSize, params.q, params.sort, response.data]);
-
- useEffect(() => {
- if (response.error !== undefined)
- this.internal_failPreferencesList(response.error, { ...params, page });
- }, [page, params.pageSize, params.q, params.sort, response.error]);
-
- return response;
+ /** Fetch orchestration for the preference list page (see `MemoryQueryList.useFetch`). */
+ useFetchPreferences = (
+ params: PreferenceQueryParams,
+ ): SWRResponse<MemoryListPageResult<DisplayPreferenceMemory>> => {
+ const { page: _page, ...query } = params;
+ return this.#list.useFetch({
+ ...query,
+ pageSize: params.pageSize ?? PREFERENCE_LIST_PAGE_SIZE,
+ q: params.q || undefined,
+ });
};
}
diff --git a/src/store/userMemory/slices/preference/index.ts b/src/store/userMemory/slices/preference/index.ts
index 1bbcb7900bc..ab0205fd8e5 100644
--- a/src/store/userMemory/slices/preference/index.ts
+++ b/src/store/userMemory/slices/preference/index.ts
@@ -1,2 +1,3 @@
export { createPreferenceSlice, type PreferenceAction } from './action';
export { preferenceInitialState, type PreferenceSliceState } from './initialState';
+export type { PreferenceListData, PreferenceListParams, PreferenceListSort } from './projection';
diff --git a/src/store/userMemory/slices/preference/initialState.ts b/src/store/userMemory/slices/preference/initialState.ts
index 43e493ea94a..a56faf6fee6 100644
--- a/src/store/userMemory/slices/preference/initialState.ts
+++ b/src/store/userMemory/slices/preference/initialState.ts
@@ -1,14 +1,36 @@
import { type DisplayPreferenceMemory } from '@/database/repositories/userMemory';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import { memoryListKey } from '../../utils/replica';
+import { type PreferenceListData, type PreferenceListSort } from './projection';
+
+/**
+ * The preference list is a `@lobechat/replica` paged resource with one page set
+ * per search / sort (`preferenceListEntries`). The long-standing flat fields
+ * (`preferenceListData`, `preferences`, `preferencesTotal`, `preferencesPage`,
+ * `preferencesHasMore`, `preferencesInit`) mirror the active query's entry so every
+ * existing consumer keeps reading the place it always has.
+ */
export interface PreferenceSliceState {
+ /** View of the active query's page set. Mirror of `preferenceListEntries[preferenceListKey]`. */
+ preferenceListData?: PreferenceListData;
+ /** Canonical replica views, one page set per query. Engine-owned. */
+ preferenceListEntries: Record<string, PreferenceListData>;
+ /** Entry key of the query on screen (see `memoryListKey`). */
+ preferenceListKey: string;
+ /** Local-first bookkeeping for `preferenceListEntries`. */
+ preferenceListReplica: ReplicaState<PreferenceListData>;
+ /** Rows of the active page set. Mirror of `preferenceListData.items`. */
preferences: DisplayPreferenceMemory[];
+ /** Mirror of `preferenceListData.hasMore`. */
preferencesHasMore: boolean;
+ /** Whether the active query has a view (persisted row hydrated or a page landed). */
preferencesInit: boolean;
+ /** Mirror of `preferenceListData.currentPage + 1`. */
preferencesPage: number;
preferencesQuery?: string;
- preferencesSearchError?: unknown;
- preferencesSearchLoading?: boolean;
- preferencesSort?: 'capturedAt' | 'scorePriority';
+ preferencesSort?: PreferenceListSort;
+ /** Mirror of `preferenceListData.total`. */
preferencesTotal: number;
}
@@ -18,8 +40,10 @@ export const preferenceInitialState: PreferenceSliceState = {
preferencesInit: false,
preferencesPage: 1,
preferencesQuery: undefined,
- preferencesSearchError: undefined,
- preferencesSearchLoading: undefined,
preferencesSort: undefined,
preferencesTotal: 0,
+ preferenceListData: undefined,
+ preferenceListEntries: {},
+ preferenceListKey: memoryListKey({}),
+ preferenceListReplica: createReplicaState<PreferenceListData>(),
};
diff --git a/src/store/userMemory/slices/preference/projection.ts b/src/store/userMemory/slices/preference/projection.ts
new file mode 100644
index 00000000000..1cce3318007
--- /dev/null
+++ b/src/store/userMemory/slices/preference/projection.ts
@@ -0,0 +1,63 @@
+import { type DisplayPreferenceMemory } from '@/database/repositories/userMemory';
+import { type ReplicaPagedData } from '@/libs/replica';
+import { userMemoryKeys } from '@/libs/swr/keys';
+
+import {
+ defineUserMemoryPagedReplica,
+ MAX_RECENT_MEMORY_QUERIES,
+ memoryListKey,
+} from '../../utils/replica';
+
+/** Server-side ordering of the preference list (`QueryUserMemoriesSort`). */
+export type PreferenceListSort = 'capturedAt' | 'scorePriority';
+
+/** Page size the memory preference list asks for when the caller does not name one. */
+export const PREFERENCE_LIST_PAGE_SIZE = 12;
+
+/**
+ * Query of one page set. `page` is NOT here β€” it is the paging cursor, owned by
+ * the replica. Everything but `pageSize` is the entry key (`memoryListKey`).
+ */
+export interface PreferenceListParams {
+ pageSize: number;
+ q?: string;
+ sort?: PreferenceListSort;
+}
+
+/** One page set of the preference list, tagged with the query it answers. */
+export interface PreferenceListData extends ReplicaPagedData<DisplayPreferenceMemory, number> {
+ q?: string;
+ sort?: PreferenceListSort;
+}
+
+/**
+ * The user-memory preference list: a local-first, offset-paged replica with one
+ * entry per search / sort (see `MemoryQueryList`). Each query paints its
+ * persisted head page on the first frame and the network confirms it.
+ *
+ * It adopts the long-standing `userMemory:preferences` SWR key as its sync key, so
+ * code that revalidates the list by its key root (`purgeAllMemories`,
+ * `updateMemory`) reaches it.
+ */
+export const preferenceListResource = defineUserMemoryPagedReplica<
+ PreferenceListParams,
+ DisplayPreferenceMemory,
+ number,
+ PreferenceListData
+>({
+ key: memoryListKey,
+ name: 'preferenceList',
+ paging: {
+ direction: 'forward',
+ getId: (item) => item.id,
+ mode: 'offset',
+ // A reload repaints what the first network page would show, never a stale tail.
+ persist: { pages: 1 },
+ },
+ // Bounded: least recently used queries leave IndexedDB and memory together;
+ // the query on screen is pinned by its mounted `useSync`.
+ persist: { maxEntries: MAX_RECENT_MEMORY_QUERIES },
+ storage: 'indexedDB',
+ syncKey: (params) => userMemoryKeys.preferences(params),
+ version: 1,
+});
diff --git a/src/store/userMemory/slices/utils/isMemoryListRequestCurrent.test.ts b/src/store/userMemory/slices/utils/isMemoryListRequestCurrent.test.ts
deleted file mode 100644
index 2b6d36e43ae..00000000000
--- a/src/store/userMemory/slices/utils/isMemoryListRequestCurrent.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { isMemoryListRequestCurrent } from './isMemoryListRequestCurrent';
-
-describe('isMemoryListRequestCurrent', () => {
- it('rejects a page beyond the current page after a list reset', () => {
- expect(
- isMemoryListRequestCurrent(
- { page: 1, q: 'late night', sort: undefined },
- { page: 2, q: 'late night', sort: undefined },
- ),
- ).toBe(false);
- });
-
- it('accepts an earlier page when pagination advances before its response arrives', () => {
- expect(
- isMemoryListRequestCurrent(
- { page: 3, q: 'late night', sort: undefined },
- { page: 2, q: 'late night', sort: undefined },
- ),
- ).toBe(true);
- });
-
- it('rejects responses from an earlier search or sort', () => {
- expect(
- isMemoryListRequestCurrent(
- { page: 1, q: 'late night', sort: 'scorePriority' },
- { page: 1, q: undefined, sort: undefined },
- ),
- ).toBe(false);
- });
-});
diff --git a/src/store/userMemory/slices/utils/isMemoryListRequestCurrent.ts b/src/store/userMemory/slices/utils/isMemoryListRequestCurrent.ts
deleted file mode 100644
index 18ac4ce31d1..00000000000
--- a/src/store/userMemory/slices/utils/isMemoryListRequestCurrent.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-interface MemoryListRequest {
- page: number;
- q?: string;
- sort?: string;
-}
-
-/**
- * Reject responses from a list state that was replaced by a search, sort, or pagination reset.
- * Earlier pages remain valid after pagination advances, so only pages beyond the current one are stale.
- */
-export const isMemoryListRequestCurrent = (
- current: MemoryListRequest,
- request: MemoryListRequest,
-) => current.page >= request.page && current.q === request.q && current.sort === request.sort;
diff --git a/src/store/userMemory/slices/utils/memoryQueryList.ts b/src/store/userMemory/slices/utils/memoryQueryList.ts
new file mode 100644
index 00000000000..b6ef712c7b8
--- /dev/null
+++ b/src/store/userMemory/slices/utils/memoryQueryList.ts
@@ -0,0 +1,254 @@
+import { useLayoutEffect, useMemo } from 'react';
+import { type SWRResponse } from 'swr';
+
+import {
+ createReplicaSlice,
+ linkReplicaEntity,
+ recordLens,
+ type ReplicaLens,
+ type ReplicaPagedData,
+ type ReplicaPageResult,
+ type ReplicaResource,
+} from '@/libs/replica';
+import { mutate } from '@/libs/swr';
+import { type StoreSetter } from '@/store/types';
+
+import { type UserMemoryStore } from '../../store';
+import { clearReplicas, clearUserReplicas, memoryListKey } from '../../utils/replica';
+import { OffsetListPager } from './offsetListPager';
+
+/** Query of one memory list page set; `pageSize` is not part of its identity. */
+export interface MemoryListParams {
+ pageSize: number;
+ q?: string;
+ sort?: string;
+}
+
+/** A memory list page set, tagged with the query it answers. */
+export interface MemoryListData<TItem, TSort extends string = string> extends ReplicaPagedData<
+ TItem,
+ number
+> {
+ q?: string;
+ sort?: TSort;
+}
+
+/** The `SWRResponse`-shaped result the memory list pages already consume. */
+export interface MemoryListPageResult<TItem> {
+ items: TItem[];
+ page: number;
+ pageSize: number;
+ total: number;
+}
+
+type StoreField = keyof UserMemoryStore & string;
+
+export interface MemoryQueryListOptions<TParams extends MemoryListParams, TItem, TData> {
+ /** Devtools prefix of the replica writes. */
+ actionPrefix: string;
+ /** Store field holding the active query's entry key. */
+ activeKeyField: StoreField;
+ /** Store field holding every page set by entry key (the replica view). */
+ entriesField: StoreField;
+ /** One server page; `page` is 1-based. */
+ fetchPage: (params: TParams, page: number) => Promise<{ items: TItem[]; total: number }>;
+ get: () => UserMemoryStore;
+ /**
+ * The flat fields existing consumers read, mirrored from the active query's
+ * page set (`undefined` = the active query has no view yet).
+ */
+ mirror: (data: TData | undefined) => Partial<UserMemoryStore>;
+ /** Plain UI fields of a newly selected query (search / sort descriptors). */
+ queryFields: (params: Omit<TParams, 'pageSize'>) => Partial<UserMemoryStore>;
+ /** Store field holding the replica bookkeeping slot. */
+ replicaField: StoreField;
+ resource: ReplicaResource<TParams, TData, ReplicaPageResult<TItem, number>>;
+ /** SWR key root the resource adopts as its sync key (`userMemoryKeys.<list>.root`). */
+ rootKey: string;
+ set: StoreSetter<UserMemoryStore>;
+ /** `useUserMemoryStore`, passed in so this module never imports the store at runtime. */
+ useStore: <T>(selector: (state: UserMemoryStore) => T) => T;
+}
+
+/**
+ * One offset-paged memory list (activities, contexts, experiences,
+ * preferences), shared so every list behaves the same:
+ *
+ * - **One entry per query.** Each search / sort is its own replica entry
+ * (`memoryListKey`), so a query switch keeps the previous query's pages and
+ * persisted row, and every query paints its own cached head on the first
+ * frame. The flat store fields mirror the active query's entry.
+ * - **Bounded.** At most `MAX_RECENT_MEMORY_QUERIES` query page sets
+ * survive, in memory and in IndexedDB, across reloads too.
+ * - **Delete / load more / purge** go through {@link OffsetListPager}.
+ * - **Edits** patch every loaded and persisted query (`linkReplicaEntity`).
+ */
+export class MemoryQueryList<
+ TParams extends MemoryListParams,
+ TItem extends { id: string },
+ TData extends MemoryListData<TItem>,
+> {
+ readonly #entity;
+ readonly #list;
+ readonly #options: MemoryQueryListOptions<TParams, TItem, TData>;
+ readonly #pager: OffsetListPager;
+
+ constructor(options: MemoryQueryListOptions<TParams, TItem, TData>) {
+ this.#options = options;
+ const { activeKeyField, entriesField, get, mirror, replicaField, resource, set } = options;
+ const entries = recordLens<UserMemoryStore, TData>(entriesField);
+ const isActive = (state: UserMemoryStore, key: string) => state[activeKeyField] === key;
+
+ // The canonical value is one page set per query; the flat fields mirror
+ // the active query's entry in the same commit as any write to it.
+ const lens: ReplicaLens<UserMemoryStore, TData> = {
+ clear: (state) => ({ ...entries.clear(state), ...mirror(undefined) }),
+ get: entries.get,
+ keys: entries.keys,
+ set: (state, key, data) => ({
+ ...entries.set(state, key, data),
+ ...(isActive(state, key) ? mirror(data) : undefined),
+ }),
+ };
+
+ this.#list = createReplicaSlice(resource, {
+ actionPrefix: options.actionPrefix,
+ fetcher: async (params, cursor) => {
+ const page = await options.fetchPage(params, (cursor ?? 0) + 1);
+ return { items: page.items, total: page.total };
+ },
+ get,
+ set,
+ stateKey: replicaField,
+ view: lens,
+ // Keep each painted page set self-describing (which query it answers).
+ viewFields: ({ q, sort }) => ({ q: q || undefined, sort }) as Partial<TData>,
+ });
+ this.#entity = linkReplicaEntity<TItem>([this.#list]);
+ this.#pager = new OffsetListPager({
+ keys: () => Object.keys(get()[entriesField] as Record<string, TData>),
+ read: (key) => (get()[entriesField] as Record<string, TData>)[key],
+ refreshHead: this.#revalidate,
+ slice: this.#list,
+ });
+ }
+
+ #activeKey = (): string => this.#options.get()[this.#options.activeKeyField] as string;
+
+ /**
+ * Revalidate the mounted query. The resource syncs under its legacy SWR key
+ * (`rootKey`), which the replica's own `revalidate()` (it matches
+ * `replica:sync` keys only) never reaches. The bare matcher form resolves
+ * once the refetch settled.
+ */
+ #revalidate = (): Promise<unknown> =>
+ mutate((key) => Array.isArray(key) && key[0] === this.#options.rootKey);
+
+ /**
+ * Purge for "delete all memories": every query page set, in memory and in
+ * IndexedDB, after any page or delete in flight. Retried once; `false` when a
+ * persisted row survived.
+ */
+ clear = (user?: string): Promise<boolean> =>
+ user === undefined || user === this.#options.resource.scope.get()
+ ? this.#pager.clear(() => clearReplicas(this.#list.clear))
+ : clearUserReplicas(user, this.#list);
+
+ /** Optimistic delete with the offset repair (see `OffsetListPager`). */
+ delete = (id: string, serverCall: () => Promise<unknown>): Promise<void> =>
+ this.#pager.delete(id, serverCall);
+
+ /** Next page of the active query, once its head is trustworthy. */
+ loadMore = (): Promise<void> => this.#pager.loadMore(this.#activeKey());
+
+ /**
+ * Fill one query's slot from IndexedDB before the route commits, so a cold
+ * visit paints the cached rows instead of the loading skeleton. A later
+ * `useSync` hydrate is a no-op once filled.
+ */
+ preHydrate = (params: TParams): Promise<boolean> => {
+ const scope = this.#options.resource.scope.get();
+ // The slot may still hold the previous user's rows; drop them before seeding.
+ this.#list.ensureScope(scope);
+ return this.#list.hydrate(params, scope);
+ };
+
+ /**
+ * Point the flat mirrors at another query. Each query keeps its own entry,
+ * so this never drops a page set: a query loaded before repaints from
+ * memory, one persisted before hydrates from storage, and a new one shows the
+ * loading state until its head lands. A no-op when the query is unchanged.
+ */
+ select = (query: Omit<TParams, 'pageSize'>): void => {
+ const { activeKeyField, actionPrefix, entriesField, get, mirror, queryFields, set } =
+ this.#options;
+ const key = memoryListKey(query);
+ const state = get();
+ if (state[activeKeyField] === key) return;
+
+ const entry = (state[entriesField] as Record<string, TData>)[key];
+ set(
+ {
+ [activeKeyField]: key,
+ ...queryFields(query),
+ ...mirror(entry),
+ } as Partial<UserMemoryStore>,
+ false,
+ `${actionPrefix}/select`,
+ );
+ };
+
+ /** Confirmed patch of one row in every loaded query and every persisted one. */
+ updateEntity = (id: string, fn: (item: TItem) => TItem): void => {
+ this.#entity.update(id, fn);
+ };
+
+ /**
+ * Fetch orchestration for the list page. Returns an `SWRResponse`-shaped
+ * result whose `data` reads the active query's page set, so the list pages
+ * (which pass it to `MemoryListBoundary`) keep their shape.
+ *
+ * - `error` is the head failure of the query on screen, only while it has
+ * nothing painted: a failed background revalidation keeps its rows.
+ * - `isLoading` covers a head load with no rows yet and a "load more" in
+ * flight (rows stay mounted under the footer). A failed page is the page
+ * set's `loadMoreError`, rendered by the list footer with a retry.
+ */
+ useFetch = (params: TParams): SWRResponse<MemoryListPageResult<TItem>> => {
+ const { pageSize: _pageSize, ...query } = params;
+ const key = memoryListKey(params);
+
+ // Select the query before paint, so a frame never shows another query's rows.
+ useLayoutEffect(() => {
+ this.select(query as Omit<TParams, 'pageSize'>);
+ }, [key]);
+
+ const sync = this.#list.useSync(params, {
+ ...this.#pager.syncCallbacks(key),
+ });
+
+ const view = this.#options.useStore(
+ (state) => (state[this.#options.entriesField] as Record<string, TData>)[key],
+ );
+ const data = useMemo<MemoryListPageResult<TItem> | undefined>(
+ () =>
+ view
+ ? {
+ items: view.items,
+ page: view.currentPage + 1,
+ pageSize: view.pageSize,
+ total: view.total ?? view.items.length,
+ }
+ : undefined,
+ [view],
+ );
+
+ return {
+ data,
+ error: data ? undefined : sync.error,
+ isLoading: data ? Boolean(view?.isLoadingMore) : sync.isValidating || !sync.isHydrated,
+ isValidating: sync.isValidating,
+ mutate: sync.revalidate,
+ } as unknown as SWRResponse<MemoryListPageResult<TItem>>;
+ };
+}
diff --git a/src/store/userMemory/slices/utils/offsetListPager.test.ts b/src/store/userMemory/slices/utils/offsetListPager.test.ts
new file mode 100644
index 00000000000..aea79e5c596
--- /dev/null
+++ b/src/store/userMemory/slices/utils/offsetListPager.test.ts
@@ -0,0 +1,244 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { OffsetListPager, type OffsetPagedSlice } from './offsetListPager';
+
+const deferred = <T = void>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, reject, resolve };
+};
+
+const setup = ({ refreshHead = vi.fn(async () => undefined) } = {}) => {
+ const log: string[] = [];
+ const tokens = { commit: vi.fn(), rollback: vi.fn() };
+ const views: Record<string, any> = { all: { items: [] } };
+ const slice: OffsetPagedSlice = {
+ beginEntityOptimistic: vi.fn(() => {
+ log.push('optimistic');
+ return [tokens];
+ }),
+ collapse: vi.fn((key: string) => log.push(`collapse:${key}`)),
+ loadMore: vi.fn(async (key: string) => {
+ log.push(`loadMore:${key}`);
+ }),
+ removeEntity: vi.fn((id: string) => log.push(`removeEntity:${id}`)),
+ update: vi.fn((key: string, apply: (data: any) => any) => {
+ views[key] = apply(views[key]);
+ }),
+ };
+ const pager = new OffsetListPager({
+ keys: () => ['all'],
+ read: (key) => views[key],
+ refreshHead,
+ slice,
+ });
+ return { log, pager, refreshHead, slice, tokens, views };
+};
+
+describe('OffsetListPager', () => {
+ it('removes optimistically, then collapses every page set and refreshes the head', async () => {
+ const { log, pager, refreshHead, tokens } = setup();
+ const server = deferred();
+
+ const deleting = pager.delete('a', () => server.promise);
+ // The row leaves the view before the server answers.
+ expect(log).toEqual(['optimistic']);
+
+ server.resolve();
+ await deleting;
+
+ expect(tokens.commit).toHaveBeenCalledTimes(1);
+ expect(log).toEqual(['optimistic', 'removeEntity:a', 'collapse:all']);
+ expect(refreshHead).toHaveBeenCalledTimes(1);
+ expect(pager.isHeadStale('all')).toBe(true);
+ });
+
+ it('rolls the optimistic removal back when the server rejects', async () => {
+ const { log, pager, tokens } = setup();
+
+ await expect(pager.delete('a', () => Promise.reject(new Error('offline')))).rejects.toThrow(
+ 'offline',
+ );
+
+ expect(tokens.rollback).toHaveBeenCalledTimes(1);
+ expect(log).toEqual(['optimistic']);
+ expect(pager.isHeadStale('all')).toBe(false);
+ });
+
+ it('pages only once a fresh head landed after a delete', async () => {
+ const refreshHead = vi.fn(async () => undefined);
+ const { log, pager, slice } = setup({ refreshHead });
+ await pager.delete('a', async () => undefined);
+
+ // The head refresh landed (the list's useSync reports it).
+ pager.headLanded('all');
+ await pager.loadMore('all');
+
+ expect(slice.loadMore).toHaveBeenCalledWith('all');
+ expect(log.at(-1)).toBe('loadMore:all');
+ // No extra head refresh was needed.
+ expect(refreshHead).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries the head refresh before paging, and surfaces its failure instead of paging', async () => {
+ const refreshHead = vi.fn(async () => undefined);
+ const { pager, slice, views } = setup({ refreshHead });
+ await pager.delete('a', async () => undefined);
+ const failure = new Error('head failed');
+ pager.headFailed('all', failure);
+
+ await pager.loadMore('all');
+
+ // The head was refreshed again, still stale: no page from a stale offset.
+ expect(refreshHead).toHaveBeenCalledTimes(2);
+ expect(slice.loadMore).not.toHaveBeenCalled();
+ expect(views.all).toMatchObject({ isLoadingMore: false, loadMoreError: failure });
+
+ // The retry refreshes the head; once it lands, the page is fetched.
+ refreshHead.mockImplementationOnce(async () => {
+ pager.headLanded('all');
+ });
+ await pager.loadMore('all');
+ expect(slice.loadMore).toHaveBeenCalledTimes(1);
+ });
+
+ it('makes load-more wait for an in-flight delete and its head refresh', async () => {
+ const head = deferred();
+ const refreshHead = vi.fn(() => head.promise);
+ const { pager, slice } = setup({ refreshHead });
+
+ const deleting = pager.delete('a', async () => undefined);
+ const paging = pager.loadMore('all');
+ // The delete is refreshing the head: paging must not start yet.
+ await vi.waitFor(() => expect(refreshHead).toHaveBeenCalledTimes(1));
+ expect(slice.loadMore).not.toHaveBeenCalled();
+
+ pager.headLanded('all');
+ head.resolve();
+ await Promise.all([deleting, paging]);
+ expect(slice.loadMore).toHaveBeenCalledTimes(1);
+ });
+
+ it('makes a delete wait for a page already in flight', async () => {
+ const page = deferred();
+ const { log, pager, slice } = setup();
+ vi.mocked(slice.loadMore).mockImplementation(async () => {
+ log.push('page-start');
+ await page.promise;
+ log.push('page-end');
+ });
+ const serverDelete = vi.fn(async () => {
+ log.push('server-delete');
+ });
+
+ const paging = pager.loadMore('all');
+ const deleting = pager.delete('a', serverDelete);
+ await Promise.resolve();
+ expect(serverDelete).not.toHaveBeenCalled();
+
+ page.resolve();
+ await Promise.all([paging, deleting]);
+ // The page's offset predates the shift, so it lands before the server deletes.
+ expect(log.indexOf('page-end')).toBeLessThan(log.indexOf('server-delete'));
+ });
+
+ it('purges at once when nothing is in flight', async () => {
+ const { pager } = setup();
+ const clear = vi.fn(async () => true);
+
+ const clearing = pager.clear(clear);
+ expect(clear).toHaveBeenCalledTimes(1);
+ await expect(clearing).resolves.toBe(true);
+ expect(clear).toHaveBeenCalledTimes(1);
+ });
+
+ it('treats a page set short of its loaded pages as head-stale, with no delete this session', async () => {
+ const refreshHead = vi.fn(async () => undefined);
+ const { pager, slice, views } = setup({ refreshHead });
+ // A persisted variant a delete patched: 11 of 12 head rows, more to load.
+ views.all = { currentPage: 0, hasMore: true, items: Array.from({ length: 11 }), pageSize: 12 };
+
+ expect(pager.isHeadStale('all')).toBe(true);
+ await pager.loadMore('all');
+
+ // The head is refreshed first; it failed, so no page from the stale offset.
+ expect(refreshHead).toHaveBeenCalledTimes(1);
+ expect(slice.loadMore).not.toHaveBeenCalled();
+ expect(views.all.loadMoreError).toBeInstanceOf(Error);
+ });
+
+ it('pages a full or final page set without refreshing the head', async () => {
+ const refreshHead = vi.fn(async () => undefined);
+ const { pager, slice, views } = setup({ refreshHead });
+ views.all = { currentPage: 0, hasMore: true, items: Array.from({ length: 12 }), pageSize: 12 };
+ expect(pager.isHeadStale('all')).toBe(false);
+ views.all = { currentPage: 1, hasMore: false, items: Array.from({ length: 15 }), pageSize: 12 };
+ expect(pager.isHeadStale('all')).toBe(false);
+
+ views.all = { currentPage: 0, hasMore: true, items: Array.from({ length: 12 }), pageSize: 12 };
+ await pager.loadMore('all');
+ expect(refreshHead).not.toHaveBeenCalled();
+ expect(slice.loadMore).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores a head failure captured under another account', async () => {
+ const refreshHead = vi.fn(async () => undefined);
+ const { pager, views } = setup({ refreshHead });
+ const previousUser = new Error('previous user failed');
+ const callbacks = pager.syncCallbacks('all');
+
+ // A request of the previous account settles after the switch.
+ callbacks.onError(previousUser, { isActive: false });
+ // The active user's page set is short, and its head refresh reports nothing.
+ views.all = { currentPage: 0, hasMore: true, items: Array.from({ length: 11 }), pageSize: 12 };
+ await pager.loadMore('all');
+
+ expect(views.all.loadMoreError).toBeInstanceOf(Error);
+ expect(views.all.loadMoreError).not.toBe(previousUser);
+
+ // The active user's own failure is surfaced.
+ const own = new Error('own failure');
+ callbacks.onError(own, { isActive: true });
+ await pager.loadMore('all');
+ expect(views.all.loadMoreError).toBe(own);
+ });
+
+ it('shares one run between concurrent load-more calls', async () => {
+ const { pager, slice } = setup();
+
+ await Promise.all([pager.loadMore('all'), pager.loadMore('all')]);
+
+ expect(slice.loadMore).toHaveBeenCalledTimes(1);
+ });
+
+ it('purges after a page in flight, and nothing is head-stale afterwards', async () => {
+ const page = deferred();
+ const { log, pager, slice } = setup();
+ await pager.delete('a', async () => undefined);
+ pager.headLanded('all');
+ vi.mocked(slice.loadMore).mockImplementation(async () => {
+ await page.promise;
+ log.push('page-end');
+ });
+ const clear = vi.fn(async () => {
+ log.push('clear');
+ return true;
+ });
+
+ const paging = pager.loadMore('all');
+ const clearing = pager.clear(clear);
+ page.resolve();
+
+ await expect(clearing).resolves.toBe(true);
+ await paging;
+ // Cleared at once (the view empties now), and again after the page settled.
+ expect(clear).toHaveBeenCalledTimes(2);
+ expect(log.indexOf('clear')).toBeLessThan(log.indexOf('page-end'));
+ expect(log.lastIndexOf('clear')).toBeGreaterThan(log.indexOf('page-end'));
+ expect(pager.isHeadStale('all')).toBe(false);
+ });
+});
diff --git a/src/store/userMemory/slices/utils/offsetListPager.ts b/src/store/userMemory/slices/utils/offsetListPager.ts
new file mode 100644
index 00000000000..9da4ad9c9c7
--- /dev/null
+++ b/src/store/userMemory/slices/utils/offsetListPager.ts
@@ -0,0 +1,198 @@
+import { type ReplicaOptimisticToken, type ReplicaPagedData } from '@/libs/replica';
+
+/** The part of a paged replica slice the pager drives (structural, so any slice fits). */
+export interface OffsetPagedSlice {
+ beginEntityOptimistic: <TItem>(
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ ) => ReplicaOptimisticToken<any>[];
+ collapse: (key: string) => unknown;
+ loadMore: (key: string) => Promise<void>;
+ removeEntity: (id: string) => void;
+ update: (key: string, apply: (data: any) => any, options?: { persist?: boolean }) => unknown;
+}
+
+interface OffsetListPagerOptions {
+ /** Entry keys loaded in memory (every page set a delete may have shifted). */
+ keys: () => string[];
+ /** The loaded page set of one entry (`undefined` = not loaded). */
+ read: (key: string) => ReplicaPagedData<unknown, unknown> | undefined;
+ /**
+ * Re-read the head page of the mounted query through the list's own SWR key
+ * (the awaitable bare `mutate(matcher)` form). Resolves once the refetch
+ * settled, whether or not it succeeded.
+ */
+ refreshHead: () => Promise<unknown>;
+ slice: OffsetPagedSlice;
+}
+
+/** Shown on the footer when the head could not be refreshed and no request error is known. */
+const staleHeadError = () => new Error('Failed to refresh the list before loading more');
+
+/**
+ * Delete / "load more" / purge for an offset-paged memory list.
+ *
+ * The memory lists page by offset (cursor = page index), so a server-side
+ * delete shifts every later row one slot up: the next page asked for with the
+ * loaded cursor would skip the row that crossed the page boundary. The pager
+ * repairs that the same way for every list:
+ *
+ * - **Delete**: the row leaves every loaded page set at once (optimistic, rolled
+ * back if the server rejects). Once the server confirms, `removeEntity` drops
+ * it from persisted rows too, every loaded page set collapses to its head
+ * and is marked *head-stale*, and the head is refreshed.
+ * - **Head-stale guard**: "load more" on a head-stale page set β€” marked by a
+ * delete in this session, or *short* (fewer rows than its loaded pages hold,
+ * e.g. a persisted variant the delete patched and a later visit hydrated) β€”
+ * first refreshes the head; it only fetches the next page once a fresh head landed
+ * (`headLanded`). If the refresh fails, the footer shows the failure with a
+ * retry instead of paging from a stale offset.
+ * - **Serialization**: deletes, pages and the purge run one after another, so
+ * load-more waits for an in-flight delete + refresh, a delete waits for a
+ * page already in flight (its offset predates the shift), and a purge never
+ * races a page that would land into the emptied list.
+ */
+export class OffsetListPager {
+ readonly #headErrors = new Map<string, unknown>();
+ readonly #keys: () => string[];
+ readonly #loadingMore = new Map<string, Promise<void>>();
+ readonly #read: OffsetListPagerOptions['read'];
+ readonly #refreshHead: () => Promise<unknown>;
+ readonly #slice: OffsetPagedSlice;
+ readonly #staleHeads = new Set<string>();
+ /** Serialized paging work not settled yet. */
+ #inFlight = 0;
+ /** Tail of the serialized paging work. */
+ #tail: Promise<unknown> = Promise.resolve();
+
+ constructor({ keys, read, refreshHead, slice }: OffsetListPagerOptions) {
+ this.#keys = keys;
+ this.#read = read;
+ this.#refreshHead = refreshHead;
+ this.#slice = slice;
+ }
+
+ #serialize = <T>(work: () => Promise<T>): Promise<T> => {
+ this.#inFlight++;
+ const run = this.#tail.then(work).finally(() => {
+ this.#inFlight--;
+ });
+ this.#tail = run.catch(() => undefined);
+ return run;
+ };
+
+ /**
+ * Whether a page set lost rows under its loaded offsets: it still has more
+ * to load, yet holds fewer rows than its loaded pages hold on the server. A
+ * delete patches every persisted query variant (`removeEntity`), including
+ * ones this session never loaded β€” or a delete in an earlier session did β€” so
+ * a page set hydrated later can be short without this session having marked
+ * it. Its next offset would skip the row that shifted into its last page.
+ */
+ #isShort = (key: string): boolean => {
+ const data = this.#read(key);
+ if (!data?.hasMore) return false;
+ return data.items.length < (data.currentPage + 1) * data.pageSize;
+ };
+
+ /** Whether `key` must refresh its head before paging again. */
+ isHeadStale = (key: string): boolean => this.#staleHeads.has(key) || this.#isShort(key);
+
+ /** A head page of `key` landed: its offsets are the server's again. */
+ headLanded = (key: string): void => {
+ this.#staleHeads.delete(key);
+ this.#headErrors.delete(key);
+ };
+
+ /**
+ * The `useSync` callbacks of `key`'s head request. A failure captured under
+ * another identity / workspace (`isActive: false` β€” a request of the previous
+ * account settling after a switch) is not this page set's: query keys repeat
+ * across users, so recording it would surface the previous user's error on
+ * the new user's footer.
+ */
+ syncCallbacks = (key: string) => ({
+ onError: (error: unknown, context?: { isActive?: boolean }) => {
+ if (context?.isActive === false) return;
+ this.headFailed(key, error);
+ },
+ // A landed head makes this page set's offsets the server's again.
+ onSuccess: () => this.headLanded(key),
+ });
+
+ /** The head request of `key` failed (surfaced if paging is blocked on it). */
+ headFailed = (key: string, error: unknown): void => {
+ this.#headErrors.set(key, error);
+ };
+
+ /**
+ * Delete one row (see the class doc). Rejects with the server error after
+ * rolling the optimistic removal back.
+ */
+ delete = (id: string, serverCall: () => Promise<unknown>): Promise<void> => {
+ const tokens = this.#slice.beginEntityOptimistic(id, () => undefined);
+
+ return this.#serialize(async () => {
+ try {
+ await serverCall();
+ } catch (error) {
+ for (const token of tokens) token.rollback();
+ throw error;
+ }
+ for (const token of tokens) token.commit();
+ // Drop the row from every loaded and persisted page set, and keep a read
+ // already in flight from bringing it back.
+ this.#slice.removeEntity(id);
+ for (const key of this.#keys()) {
+ this.#staleHeads.add(key);
+ this.#slice.collapse(key);
+ }
+ await this.#refreshHead();
+ });
+ };
+
+ /** Append the next page of `key` once its head is trustworthy. Concurrent calls share one run. */
+ loadMore = (key: string): Promise<void> => {
+ const running = this.#loadingMore.get(key);
+ if (running) return running;
+
+ const run = this.#serialize(async () => {
+ if (this.isHeadStale(key)) {
+ this.#staleHeads.add(key);
+ await this.#refreshHead();
+ if (this.#staleHeads.has(key)) {
+ const error = this.#headErrors.get(key) ?? staleHeadError();
+ this.#slice.update(
+ key,
+ (data) => data && { ...data, isLoadingMore: false, loadMoreError: error },
+ { persist: false },
+ );
+ return;
+ }
+ }
+ await this.#slice.loadMore(key);
+ }).finally(() => this.#loadingMore.delete(key));
+
+ this.#loadingMore.set(key, run);
+ return run;
+ };
+
+ /**
+ * Run the list's purge now β€” the view empties at once β€” and, when a page or
+ * a delete is still in flight, once more after it settled, so nothing it
+ * brings back survives. Nothing is head-stale afterwards.
+ */
+ clear = (clear: () => Promise<boolean>): Promise<boolean> => {
+ this.#staleHeads.clear();
+ this.#headErrors.clear();
+ const now = clear();
+ if (this.#inFlight === 0) return now;
+
+ return this.#serialize(async () => {
+ await now.catch(() => false);
+ this.#staleHeads.clear();
+ this.#headErrors.clear();
+ return clear();
+ });
+ };
+}
diff --git a/src/store/userMemory/slices/utils/shouldSurfaceMemoryListError.ts b/src/store/userMemory/slices/utils/shouldSurfaceMemoryListError.ts
deleted file mode 100644
index 8f7e3d10a82..00000000000
--- a/src/store/userMemory/slices/utils/shouldSurfaceMemoryListError.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-interface MemoryListErrorContext {
- initialized: boolean;
- page: number;
- resetting?: boolean;
-}
-
-/**
- * Only replace a list with an error when its first page has no current content. Background
- * refresh and pagination failures must keep already-settled content visible.
- */
-export const shouldSurfaceMemoryListError = ({
- initialized,
- page,
- resetting,
-}: MemoryListErrorContext) => page === 1 && (Boolean(resetting) || !initialized);
diff --git a/src/store/userMemory/utils/replica.test.ts b/src/store/userMemory/utils/replica.test.ts
new file mode 100644
index 00000000000..39445b54231
--- /dev/null
+++ b/src/store/userMemory/utils/replica.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+
+import { clearReplicas, identityScopeOf, userMemoryIdentityScope } from './replica';
+
+describe('userMemory replica scope', () => {
+ it('drops the workspace from the cache scope', () => {
+ expect(identityScopeOf('user-1:personal')).toBe('user-1:*');
+ expect(identityScopeOf('user-1:ws-2')).toBe('user-1:*');
+ expect(identityScopeOf('anon')).toBe('anon:*');
+ });
+
+ it('maps every workspace of one user to the same partition', () => {
+ const get = vi.spyOn(cacheScope, 'get').mockReturnValue('user-1:personal');
+ const personal = userMemoryIdentityScope.get();
+ get.mockReturnValue('user-1:ws-2');
+ expect(userMemoryIdentityScope.get()).toBe(personal);
+ get.mockReturnValue('user-2:personal');
+ expect(userMemoryIdentityScope.get()).not.toBe(personal);
+ vi.restoreAllMocks();
+ });
+});
+
+describe('clearReplicas', () => {
+ it('clears every replica once when storage is purged', async () => {
+ const a = vi.fn().mockResolvedValue(true);
+ const b = vi.fn().mockResolvedValue(true);
+
+ await expect(clearReplicas(a, b)).resolves.toBe(true);
+ expect(a).toHaveBeenCalledTimes(1);
+ expect(b).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries a failed purge once', async () => {
+ const flaky = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true);
+
+ await expect(clearReplicas(flaky)).resolves.toBe(true);
+ expect(flaky).toHaveBeenCalledTimes(2);
+ });
+
+ it('reports a persisted row that survived both attempts', async () => {
+ const broken = vi.fn().mockResolvedValue(false);
+ const fine = vi.fn().mockResolvedValue(true);
+
+ await expect(clearReplicas(fine, broken)).resolves.toBe(false);
+ expect(broken).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/src/store/userMemory/utils/replica.ts b/src/store/userMemory/utils/replica.ts
new file mode 100644
index 00000000000..54db0aee8f7
--- /dev/null
+++ b/src/store/userMemory/utils/replica.ts
@@ -0,0 +1,154 @@
+import {
+ cacheScope,
+ definePagedReplica,
+ defineReplica,
+ REPLICA_INDEX_KEY,
+ type ReplicaScope,
+ type ReplicaStorage,
+ stableQueryKey,
+} from '@/libs/replica';
+
+/**
+ * The identity half of a cache scope (`${userId}:${workspaceId}`), with the
+ * workspace replaced by a marker no workspace id can take.
+ */
+export const identityScopeOf = (scope: string): string => {
+ const separator = scope.indexOf(':');
+ return `${separator === -1 ? scope : scope.slice(0, separator)}:*`;
+};
+
+/**
+ * User memories belong to the user, not to a workspace: the server reads and
+ * deletes them by user id alone (`buildUserMemoryWhere`). Partitioning their
+ * replicas per workspace would let "purge all memories" in one workspace leave
+ * another workspace's persisted copy to hydrate after a switch, so every
+ * userMemory replica is partitioned by identity only β€” one `clear()` reaches
+ * the rows written in every workspace, and a workspace switch keeps showing
+ * the same user's memories.
+ */
+export const userMemoryIdentityScope: ReplicaScope = {
+ canHydrate: () => cacheScope.canHydrate?.() ?? true,
+ canPersist: () => cacheScope.canPersist(),
+ get: () => identityScopeOf(cacheScope.get()),
+ use: () => identityScopeOf(cacheScope.use()),
+};
+
+/**
+ * How many distinct search / sort page sets each memory list keeps persisted
+ * (`persist.maxEntries`). The query on screen is pinned by its mounted
+ * `useSync`, so it is never evicted; older queries leave IndexedDB and memory
+ * together, least recently used first, across reloads too.
+ */
+export const MAX_RECENT_MEMORY_QUERIES = 8;
+
+/**
+ * How many topic memory bundles stay persisted (`persist.maxEntries`). Every
+ * visited topic gets its own row; deleted and long-unvisited topics fall out
+ * instead of accumulating until a full purge.
+ */
+export const MAX_RECENT_TOPIC_MEMORIES = 32;
+
+/** `defineReplica` for a userMemory resource: always scoped per user. */
+export const defineUserMemoryReplica: typeof defineReplica = (options) =>
+ defineReplica({ ...options, scope: userMemoryIdentityScope });
+
+/** `definePagedReplica` for a userMemory list: always scoped per user. */
+export const defineUserMemoryPagedReplica: typeof definePagedReplica = (options) =>
+ definePagedReplica({ ...options, scope: userMemoryIdentityScope });
+
+/**
+ * Wipe a slice's replicas for "delete all memories": memory, every persisted
+ * row of the user and reads in flight (`clear()`). A storage failure leaves a
+ * row the next session would hydrate back, so a failed purge is retried once.
+ * Resolves `false` when a persisted row survived both attempts; the caller
+ * (`purgeAllMemories`) surfaces that after its in-memory reset.
+ */
+export const clearReplicas = async (...clears: (() => Promise<boolean>)[]): Promise<boolean> => {
+ let cleared = false;
+ for (let attempt = 0; attempt < 2 && !cleared; attempt++) {
+ const results = await Promise.all(clears.map((clear) => clear()));
+ cleared = results.every(Boolean);
+ }
+ return cleared;
+};
+
+/**
+ * Entry key of one memory list page set: the query (search, sort, filters)
+ * without the page size. Every query is its own replica entry, so a query
+ * switch never overwrites another query's pages and each query hydrates its
+ * own persisted head page (the reducer only hydrates an empty entry). With no
+ * separate replica `query`, the persisted row key equals the entry key.
+ */
+export const memoryListKey = <T extends { pageSize?: number; q?: string }>({
+ pageSize: _pageSize,
+ q,
+ ...filters
+}: T): string => stableQueryKey({ ...filters, q: q || undefined });
+
+/** The part of a replica slice the user-wide purge needs (structural). */
+export interface PurgeableReplica {
+ clear: () => Promise<boolean>;
+ /** Off-scope `remove(key, scope)` purges that key's rows in `scope` (engine). */
+ remove: (key: string, scope?: string) => boolean;
+ resource: { storage?: ReplicaStorage<any> };
+}
+
+/** How long an off-scope purge waits for its row deletes to land. */
+const OFF_SCOPE_PURGE_TIMEOUT = 2000;
+const OFF_SCOPE_PURGE_POLL = 25;
+
+/**
+ * Purge every persisted row a replica holds in `scope` β€” a partition that is
+ * NOT the active one (the user whose memories were deleted switched account
+ * while the server purge ran). The view on screen belongs to the active user
+ * and is left alone.
+ *
+ * Every userMemory resource keys its persisted rows by entry key (no replica
+ * `query`), so the partition's index lists entry keys; each goes through the
+ * engine's off-scope `remove(key, scope)`, which orders the delete behind the
+ * resource's queued writes and refuses to hydrate the key again in this
+ * session. Resolves `true` once every indexed row is gone.
+ */
+const purgeOffScope = async (replica: PurgeableReplica, scope: string): Promise<boolean> => {
+ const storage = replica.resource.storage;
+ if (!storage) return true;
+ const read = (queryKey: string) =>
+ storage.getStrict ? storage.getStrict({ queryKey, scope }) : storage.get({ queryKey, scope });
+
+ let keys: string[];
+ try {
+ keys = ((await read(REPLICA_INDEX_KEY))?.data as unknown as string[] | undefined) ?? [];
+ } catch {
+ return false;
+ }
+ for (const key of keys) replica.remove(key, scope);
+
+ const deadline = Date.now() + OFF_SCOPE_PURGE_TIMEOUT;
+ for (;;) {
+ try {
+ const rows = await Promise.all(keys.map((key) => read(key)));
+ if (rows.every((row) => row === undefined)) return true;
+ } catch {
+ return false;
+ }
+ if (Date.now() >= deadline) return false;
+ await new Promise((resolve) => setTimeout(resolve, OFF_SCOPE_PURGE_POLL));
+ }
+};
+
+/**
+ * `clearReplicas` for the user `user` (a `userMemoryIdentityScope` value).
+ * For the active user (or none given) it is the ordinary `clear()`. For
+ * another user β€” an account switch while "delete all memories" ran β€” it
+ * purges that user's persisted partition without touching the active view,
+ * so their next session cannot hydrate the deleted memories back.
+ */
+export const clearUserReplicas = (
+ user: string | undefined,
+ ...replicas: PurgeableReplica[]
+): Promise<boolean> => {
+ if (user === undefined || user === userMemoryIdentityScope.get())
+ return clearReplicas(...replicas.map((replica) => replica.clear));
+
+ return clearReplicas(...replicas.map((replica) => () => purgeOffScope(replica, user)));
+};