🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(userMemory): follow-ups to the replica migration (#20774) (#20805)
Arvin Xub673f37948cf
diff --git a/packages/replica/README.md b/packages/replica/README.mdindex a144fd42253..78f7f48130e 100644--- a/packages/replica/README.md+++ b/packages/replica/README.md@@ -57,11 +57,12 @@ Inside LobeHub, use `@/libs/replica`. It presets the cache scope, IndexedDB / loPersisted 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; 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. |+| 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. |+| The whole resource for a scope that is no longer active (an account switched away mid-"delete all") | `slice.clearScope(scope)` | Deletes every persisted row and the index of `scope` behind the writes this session already queued for it; memory (another scope's, on screen) is untouched. For the active scope it is `clear()`. 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.diff --git a/packages/replica/src/core/engine.persistence.test.ts b/packages/replica/src/core/engine.persistence.test.tsindex 2048db6c8fb..bf6dfd0d5b9 100644--- a/packages/replica/src/core/engine.persistence.test.ts+++ b/packages/replica/src/core/engine.persistence.test.ts@@ -305,6 +305,38 @@ describe('redundant persist writes', () => {expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1')]);});+ it('does not count an unconfirmed write as stored: a dropped write is retried', async () => {+ resetScope();+ const storage = createStorage();+ const { engine } = setupList(storage);+ // The first write of the row is slow, then fails (an aborted transaction).+ let failFirst!: () => void;+ const { set } = storage.storage;+ let held = true;+ storage.storage.set = (key, row) =>+ held && key.queryKey === 'a?{}'+ ? ((held = false),+ new Promise<void>((_, reject) => (failFirst = () => reject(new Error('aborted')))))+ : set(key, row);++ engine.replace({ id: 'a' }, [item('1')]);+ await flush();+ // A deep-equal revalidation while that write is still in flight.+ engine.replace({ id: 'a' }, [item('1')]);+ await flush();+ failFirst();+ await flush();++ // The second persist was not skipped: the row holds the value.+ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('1')]);++ // Once a write is confirmed, an equal revalidation is skipped again.+ const writes = rowWrites(storage, 'a?{}');+ engine.replace({ id: 'a' }, [item('1')]);+ await flush();+ expect(rowWrites(storage, 'a?{}')).toBe(writes);+ });+it('writes again after an entity patch rewrote the row behind it', async () => {resetScope();const storage = createStorage();@@ -328,6 +360,173 @@ describe('redundant persist writes', () => {});});+describe('clearScope purges an inactive scope behind its queued writes', () => {+ it('purges a row and index entry whose writes were still queued, and leaves the active scope alone', async () => {+ resetScope();+ const storage = createStorage();+ const { engine, host } = setupList(storage);+ // The previous user's row write is still in flight when the purge starts.+ let release!: () => void;+ const held = new Promise<void>((resolve) => (release = resolve));+ const { set } = storage.storage;+ storage.storage.set = async (key, row) => {+ if (key.scope === SCOPE && key.queryKey === 'a?{}') await held;+ return set(key, row);+ };+ engine.replace({ id: 'a' }, [item('deleted')]);++ // The account switches; the new user paints and persists its own row.+ scopeState.current = 'u2';+ engine.replace({ id: 'b' }, [item('active')]);+ await flush();++ const purging = engine.clearScope(SCOPE);+ release();+ await expect(purging).resolves.toBe(true);+ await flush();++ expect(storage.rows.has(`${SCOPE}|a?{}`)).toBe(false);+ expect(storage.index()).not.toContain('a?{}');+ // The active user's view and row are untouched.+ expect(host.view().b).toEqual([item('active')]);+ expect(storage.rows.get('u2|b?{}')?.data).toEqual([item('active')]);+ resetScope();+ });++ it('is clear() for the active scope', async () => {+ resetScope();+ const storage = createStorage();+ const { engine, host } = setupList(storage);+ engine.replace({ id: 'a' }, [item('1')]);+ await flush();++ await expect(engine.clearScope(SCOPE)).resolves.toBe(true);++ expect(host.view()).toEqual({});+ expect(storage.dataKeys()).toEqual([]);+ });+});++describe('entity changes confirmed for a captured scope', () => {+ it('removeEntity({ scope }) patches only that scope’s rows, leaving the active view alone', async () => {+ resetScope();+ const storage = createStorage();+ const { engine, host } = setupList(storage);+ engine.replace({ id: 'a' }, [item('1'), item('2')]);+ await flush();++ // The account switches; the new one shows a list holding the same id.+ scopeState.current = 'u2';+ engine.replace({ id: 'b' }, [item('1')]);+ await flush();++ engine.removeEntity('1', { scope: SCOPE });+ await flush();++ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([item('2')]);+ // The active account's view and row are untouched.+ expect(host.view().b).toEqual([item('1')]);+ expect(storage.rows.get('u2|b?{}')?.data).toEqual([item('1')]);++ // Back on the first account, its list hydrates without the entity.+ scopeState.current = SCOPE;+ engine.ensureScope(SCOPE);+ await engine.hydrate({ id: 'a' });+ expect(host.view().a).toEqual([item('2')]);+ resetScope();+ });++ it('reconciles an entry hydrated while an off-scope update was still landing', async () => {+ resetScope();+ const storage = createStorage();+ const { engine, host } = setupList(storage);+ engine.replace({ id: 'a' }, [item('1'), item('2')]);+ await flush();+ scopeState.current = 'u2';+ engine.ensureScope('u2');++ // Hold the patch on its index read, so the switch back lands first.+ let release!: () => void;+ const held = new Promise<void>((resolve) => (release = resolve));+ const { getStrict } = storage.storage;+ storage.storage.getStrict = async (key) => {+ if (key.scope === SCOPE && key.queryKey === REPLICA_INDEX_KEY) await held;+ return getStrict!(key);+ };+ engine.updateEntity<Item>('1', () => ({ id: '1', renamed: true }) as Item, { scope: SCOPE });++ // Back on the first account: its list hydrates the pre-patch row.+ scopeState.current = SCOPE;+ engine.ensureScope(SCOPE);+ await engine.hydrate({ id: 'a' });+ expect(host.view().a).toEqual([item('1'), item('2')]);++ release();+ await flush();+ await flush();++ // The patch landed in storage and in the view now on screen.+ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([+ { id: '1', renamed: true },+ item('2'),+ ]);+ expect(host.view().a).toEqual([{ id: '1', renamed: true }, item('2')]);+ resetScope();+ });++ it('patches a captured scope’s rows whose writes were still queued at the switch', async () => {+ resetScope();+ const storage = createStorage();+ const { engine, host } = setupList(storage);+ // Every write of the first account is still queued when the account switches.+ let release!: () => void;+ const held = new Promise<void>((resolve) => (release = resolve));+ const { set } = storage.storage;+ storage.storage.set = async (key, row) => {+ if (key.scope === SCOPE) await held;+ return set(key, row);+ };+ engine.replace({ id: 'a' }, [item('1'), item('2')]);+ engine.replace({ id: 'b' }, [item('1')]);++ scopeState.current = 'u2';+ engine.ensureScope('u2');+ engine.replace({ id: 'c' }, [item('1')]);+ engine.removeEntity('1', { scope: SCOPE });+ engine.updateEntity<Item>('2', () => ({ id: '2', renamed: true }) as Item, { scope: SCOPE });++ release();+ for (let i = 0; i < 5; i++) await flush();++ // Neither row was in the persisted index yet, yet both got the change.+ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([{ id: '2', renamed: true }]);+ expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([]);+ // The active account is untouched.+ expect(host.view().c).toEqual([item('1')]);+ expect(storage.rows.get('u2|c?{}')?.data).toEqual([item('1')]);+ resetScope();+ });++ it('updateEntity({ scope }) patches only that scope’s rows', async () => {+ resetScope();+ const storage = createStorage();+ const { engine, host } = setupList(storage);+ engine.replace({ id: 'a' }, [item('1')]);+ await flush();+ scopeState.current = 'u2';+ engine.replace({ id: 'b' }, [item('1')]);+ await flush();++ engine.updateEntity<Item>('1', () => ({ id: '1', renamed: true }) as Item, { scope: SCOPE });+ await flush();++ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toEqual([{ id: '1', renamed: true }]);+ expect(host.view().b).toEqual([item('1')]);+ expect(storage.rows.get('u2|b?{}')?.data).toEqual([item('1')]);+ resetScope();+ });+});+describe('bounded persisted entries (persist.maxEntries)', () => {const bounded = (storage = createStorage()) => ({storage,diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.tsindex 22cdf070aa7..44b54d67a1d 100644--- a/packages/replica/src/core/engine.ts+++ b/packages/replica/src/core/engine.ts@@ -272,8 +272,10 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(};// ---- 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+ // What this session knows a row holds in storage: the value of its latest+ // write once that write is confirmed (`ReplicaStorage.set` resolved), or the+ // value read back by a hydrate no write raced. A write still in flight, or one+ // that failed, leaves the row unknown. 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.@@ -584,13 +586,18 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(touchStorageKey(effect.scope, key.queryKey);continue;}- rememberStored(effect.scope, key.queryKey, data);+ // Until this write is confirmed the row's content is unknown: forget what+ // it held, and only remember `data` once the write observably landed and+ // is still the latest queued for the row. A failed (or best-effort,+ // silently dropped) write therefore never makes a later identical persist+ // look redundant — that one writes again.+ forgetStored(effect.scope, [key.queryKey]);+ trackStorageKey(effect.scope, key.queryKey);+ const id = rowId(effect.scope, key.queryKey);+ const seq = rowWrites.get(id);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]);+ if (written && rowWrites.get(id) === seq) rememberStored(effect.scope, key.queryKey, data);});- trackStorageKey(effect.scope, key.queryKey);}};@@ -966,6 +973,25 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(return purge;};+ /**+ * `clear()` for any scope, including one that is not active (a user who+ * switched away while their data was being deleted): every persisted row of+ * `scope` and its index go, and for the active scope memory is wiped too+ * (exactly `clear()`). An inactive scope's memory is not on screen and is+ * left alone. The row deletes go through the write queue, so they land after+ * any write this session already queued for that scope — a row (or index+ * entry) written just before is purged rather than landing after the purge.+ * A later hydrate of `scope` waits for the purge. Resolves `true` once the+ * persisted rows are gone.+ */+ const clearScope = (scope: string): Promise<boolean> => {+ if (scope === resource.scope.get()) return clear();+ clearGenerations.set(scope, clearGeneration(scope) + 1);+ const purge = purgeScope(scope);+ scopePurges.set(scope, purge);+ return purge;+ };+/** Delete every persisted row of `scope` (see `clear`). */const purgeScope = async (scope: string): Promise<boolean> => {if (!writeQueue) return true;@@ -1211,6 +1237,12 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(}// Identity changed while reading the index: those rows are not ours to touch.if (!offScope && resource.scope.get() !== scope) return false;+ // Rows this session wrote to the scope may not be in the persisted index yet+ // (their row or index write is still queued — e.g. just before an account+ // switch). Patch them too: each patch is queued behind the row's own write,+ // so it reads the row once that write landed.+ for (const queryKey of indexed.get(scope) ?? [])+ if (!keys.includes(queryKey)) keys.push(queryKey);const patches: Promise<boolean>[] = [];for (const queryKey of keys) {if (loaded.has(queryKey)) continue;@@ -1326,22 +1358,65 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(return patch;};+ /**+ * An entity patch started for a scope that was not active settled. If the+ * user switched back to that scope meanwhile, an entry may have hydrated the+ * pre-patch row before the patch landed: apply the same change to what is+ * loaded now, in memory only — storage already holds it.+ */+ const reconcileLoaded = <TItem>(+ scope: string,+ id: string,+ fn: (item: TItem) => TItem | undefined,+ ) => {+ if (resource.scope.get() !== scope || getSlot().scope !== scope) return;+ for (const key of entityKeys(id)) {+ const current = port.read(key);+ if (current === undefined) continue;+ // A hydrate during the patch may have recorded the pre-patch row as stored.+ forgetStored(scope, [storageKey(key, getSlot().entries[key]?.query).queryKey]);+ if (mapEntity(current, id, fn) === undefined) remove(key);+ else+ update(key, (data) => (data === undefined ? data : (mapEntity(data, id, fn) ?? data)), {+ persist: false,+ });+ }+ };++ /**+ * Confirmed patch of one entity everywhere it is loaded and in the persisted+ * rows of unloaded entries. `scope` targets a scope captured earlier (a+ * write confirmed after the account switched): when it is no longer active,+ * only that scope's persisted rows are patched and the view on screen —+ * another identity's — is left alone.+ */const updateEntity = <TItem>(id: string,fn: (item: TItem) => TItem | undefined,- options?: { persist?: boolean },+ options?: { persist?: boolean; scope?: string },) => {+ if (options?.scope !== undefined && options.scope !== resource.scope.get()) {+ const scope = options.scope;+ if (options.persist === false) return;+ const settle = () => reconcileLoaded(scope, id, fn);+ void patchStoredEntityRows(id, fn, scope).then(settle, settle);+ return;+ }void applyEntity(id, fn, options);};/**- * Confirmed removal of one entity everywhere (see `updateEntity`). Unlike a- * plain mapper returning `undefined`, it is also remembered for this scope:+ * Confirmed removal of one entity everywhere (see `updateEntity`, including+ * its captured `scope`). Unlike a plain mapper returning `undefined`, it is+ * also remembered for that scope:* a value hydrated afterwards — even by a read already in flight — comes* back without the entity (see `removedEntities`).*/const removeEntity = (id: string, options?: { persist?: boolean; scope?: string }) => {const scope = options?.scope ?? resource.scope.get();+ // A removal confirmed after the account switched belongs to the scope that+ // asked for it: guard and patch that scope's rows, never the active view.+ const offScope = scope !== resource.scope.get();const guard: { releasedAt?: number } = {};const guards = removedEntities.get(scope) ?? new Map<string, { releasedAt?: number }>();removedEntities.set(scope, guards);@@ -1354,10 +1429,15 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(};// A scope left behind has nothing on screen: only its persisted rows drop// the entity, and the guard keeps a later hydrate there from reading it back.- const patch =- scope === resource.scope.get()- ? applyEntity(id, () => undefined, options)- : patchStoredEntityRows(id, () => undefined, scope);+ const patch = offScope+ ? options?.persist === false+ ? undefined+ : patchStoredEntityRows(id, () => undefined, scope).then((patched) => {+ // Switched back meanwhile: drop it from anything hydrated since.+ reconcileLoaded(scope, id, () => undefined);+ return patched;+ })+ : 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.// A patch that did not land (untrusted scope, unreadable index or row, a@@ -1393,6 +1473,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(beginOptimistic,clear,clearGeneration,+ clearScope,removalGeneration,collapse,dispatch,diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.tsindex 2edd473decb..189f94892f0 100644--- a/packages/replica/src/core/types.ts+++ b/packages/replica/src/core/types.ts@@ -15,9 +15,10 @@ export interface ReplicaRow<T> {/*** Where a replica keeps its rows between sessions (IndexedDB, localStorage …).- * Reads and writes are best-effort: the server stays the durable source of- * truth, so `get` and `set` should swallow their own I/O failures (a failed- * read is a cache miss, a failed write is retried by the next one).+ * The server stays the durable source of truth, so `get` is best-effort: it+ * swallows its own I/O failures and reports a miss. Writes are not: `set` and+ * `remove` must reject when they did not land (see each method), so the+ * engine can retry them instead of treating a dropped row as persisted.*/export interface ReplicaStorage<T> {get: (key: ReplicaRowKey) => Promise<ReplicaRow<T> | undefined>;@@ -41,6 +42,13 @@ export interface ReplicaStorage<T> {* of letting a row the user deleted hydrate again. A missing row is a success.*/remove: (key: ReplicaRowKey) => Promise<void>;+ /**+ * Write a row. Should **reject** when the write did not land: the engine only+ * treats a row as holding a value after `set` resolved, so a rejected write is+ * retried by the next persist rather than skipped as redundant. A storage that+ * swallows failures still works, but a dropped write then survives until the+ * value changes or the next session.+ */set: (key: ReplicaRowKey, row: ReplicaRow<T>) => Promise<void>;}diff --git a/src/libs/queryProjectionStorage/indexedDB.test.ts b/src/libs/queryProjectionStorage/indexedDB.test.tsindex 0541243cf59..9de758cc39a 100644--- a/src/libs/queryProjectionStorage/indexedDB.test.ts+++ b/src/libs/queryProjectionStorage/indexedDB.test.ts@@ -21,6 +21,16 @@ describe('IndexedDBQueryProjectionStorage', () => {});});+ it('rejects a write that did not land, so the replica retries it', async () => {+ vi.spyOn(localDatabase, 'initialize').mockResolvedValue();+ vi.spyOn(localDatabase, 'set').mockRejectedValue(new Error('transaction aborted'));+ const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });++ await expect(+ storage.set({ queryKey: 'all', scope: 'personal' }, { data: ['x'], updatedAt: 1 }),+ ).rejects.toThrow('transaction aborted');+ });+it('treats persistence failures as a cache miss', async () => {vi.spyOn(localDatabase, 'initialize').mockRejectedValue(new Error('unavailable'));const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });diff --git a/src/libs/queryProjectionStorage/indexedDB.ts b/src/libs/queryProjectionStorage/indexedDB.tsindex 184a059e903..aff09c2d3fa 100644--- a/src/libs/queryProjectionStorage/indexedDB.ts+++ b/src/libs/queryProjectionStorage/indexedDB.ts@@ -33,20 +33,22 @@ 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.+ * Rejects when the delete did not land, unlike reads: 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));};+ /**+ * Rejects when the write did not land (see `ReplicaStorage.set`): the replica+ * engine only treats a row as holding a value after a confirmed write, so a+ * dropped write is retried by the next persist instead of being skipped as+ * redundant. Callers that persist best-effort catch it.+ */set = async (key: QueryProjectionKey, projection: QueryProjection<T>): Promise<void> => {- try {- await localDatabase.initialize();- await localDatabase.set(COLLECTION, this.#key(key), projection);- } catch {- // Projection persistence is best-effort; the server remains the durable SoT.- }+ await localDatabase.initialize();+ await localDatabase.set(COLLECTION, this.#key(key), projection);};}diff --git a/src/libs/queryProjectionStorage/localStorage.test.ts b/src/libs/queryProjectionStorage/localStorage.test.tsindex a174235867c..100abe3ccc6 100644--- a/src/libs/queryProjectionStorage/localStorage.test.ts+++ b/src/libs/queryProjectionStorage/localStorage.test.ts@@ -18,6 +18,17 @@ describe('LocalStorageQueryProjectionStorage', () => {expect(storage.getSync({ ...key, scope: 'user-b' })).toBeUndefined();});+ it('rejects a write that did not land (quota), so the replica retries it', async () => {+ const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new Error('QuotaExceededError');+ });++ await expect(+ storage.set({ queryKey: 'q', scope: 'user-a' }, { data: ['x'], updatedAt: 1 }),+ ).rejects.toThrow('QuotaExceededError');+ });+it('reads and writes one scoped query through the async interface', async () => {const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });const key = { queryKey: 'limit:10', scope: 'user:workspace' };diff --git a/src/libs/queryProjectionStorage/localStorage.ts b/src/libs/queryProjectionStorage/localStorage.tsindex ec34a2b73d7..aeaf8bbf341 100644--- a/src/libs/queryProjectionStorage/localStorage.ts+++ b/src/libs/queryProjectionStorage/localStorage.ts@@ -61,13 +61,14 @@ export class LocalStorageQueryProjectionStorage<T> implements QueryProjectionStolocalStorage.removeItem(this.#key(key));};+ /**+ * Rejects when the write did not land (a quota error, see `ReplicaStorage.set`):+ * the replica engine only treats a row as holding a value after a confirmed+ * write. Callers that persist best-effort catch it.+ */set = async (key: QueryProjectionKey, projection: QueryProjection<T>): Promise<void> => {if (typeof window === 'undefined') return;- try {- localStorage.setItem(this.#key(key), this.#codec.stringify(projection));- } catch {- // Projection persistence is best-effort; the server remains the durable SoT.- }+ localStorage.setItem(this.#key(key), this.#codec.stringify(projection));};}diff --git a/src/libs/queryProjectionStorage/types.ts b/src/libs/queryProjectionStorage/types.tsindex 49fac7f6793..a0206cf8c0e 100644--- a/src/libs/queryProjectionStorage/types.ts+++ b/src/libs/queryProjectionStorage/types.ts@@ -18,6 +18,7 @@ export interface QueryProjectionStorage<T> {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>;+ /** Rejects when the write did not land (see `ReplicaStorage.set`). */set: (key: QueryProjectionKey, projection: QueryProjection<T>) => Promise<void>;}diff --git a/src/routes/(main)/memory/activities/activitiesLoader.test.ts b/src/routes/(main)/memory/activities/activitiesLoader.test.tsnew file mode 100644index 00000000000..7cbf89ce14e--- /dev/null+++ b/src/routes/(main)/memory/activities/activitiesLoader.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 { activityListLoader } from './activitiesLoader';++const argsOf = (url: string) => ({ request: new Request(url) }) as LoaderFunctionArgs;++describe('activityListLoader', () => {+ afterEach(() => vi.restoreAllMocks());++ it('pre-hydrates the query the route URL encodes', async () => {+ const preHydrate = vi+ .spyOn(useUserMemoryStore.getState(), 'preHydrateActivities')+ .mockResolvedValue(true);++ await expect(+ activityListLoader(argsOf('https://app.lobehub.com/memory/activities?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(), 'preHydrateActivities')+ .mockResolvedValue(true);++ await activityListLoader(argsOf('https://app.lobehub.com/memory/activities'));++ expect(preHydrate).toHaveBeenCalledWith({ q: undefined });+ });+});diff --git a/src/routes/(main)/memory/activities/activitiesLoader.ts b/src/routes/(main)/memory/activities/activitiesLoader.tsnew file mode 100644index 00000000000..00f5c20fcf2--- /dev/null+++ b/src/routes/(main)/memory/activities/activitiesLoader.ts@@ -0,0 +1,24 @@+import type { LoaderFunctionArgs } from 'react-router';++import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { useUserMemoryStore } from '@/store/userMemory';++/**+ * Seed the persisted activity 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. 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).+ */+export const activityListLoader = async ({ request }: LoaderFunctionArgs): Promise<null> => {+ const q = new URL(request.url).searchParams.get('q') || undefined;++ await settleWithin(+ useUserMemoryStore.getState().preHydrateActivities({ q }),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );++ return null;+};diff --git a/src/routes/(main)/memory/contexts/contextsLoader.test.ts b/src/routes/(main)/memory/contexts/contextsLoader.test.tsnew file mode 100644index 00000000000..425d1cf3861--- /dev/null+++ b/src/routes/(main)/memory/contexts/contextsLoader.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 { contextListLoader } from './contextsLoader';++const argsOf = (url: string) => ({ request: new Request(url) }) as LoaderFunctionArgs;++describe('contextListLoader', () => {+ afterEach(() => vi.restoreAllMocks());++ it('pre-hydrates the query the route URL encodes', async () => {+ const preHydrate = vi+ .spyOn(useUserMemoryStore.getState(), 'preHydrateContexts')+ .mockResolvedValue(true);++ await expect(+ contextListLoader(argsOf('https://app.lobehub.com/memory/contexts?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(), 'preHydrateContexts')+ .mockResolvedValue(true);++ await contextListLoader(argsOf('https://app.lobehub.com/memory/contexts'));++ expect(preHydrate).toHaveBeenCalledWith({ q: undefined });+ });+});diff --git a/src/routes/(main)/memory/contexts/contextsLoader.ts b/src/routes/(main)/memory/contexts/contextsLoader.tsnew file mode 100644index 00000000000..ed4f8c580a6--- /dev/null+++ b/src/routes/(main)/memory/contexts/contextsLoader.ts@@ -0,0 +1,24 @@+import type { LoaderFunctionArgs } from 'react-router';++import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { useUserMemoryStore } from '@/store/userMemory';++/**+ * Seed the persisted context 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. 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).+ */+export const contextListLoader = async ({ request }: LoaderFunctionArgs): Promise<null> => {+ const q = new URL(request.url).searchParams.get('q') || undefined;++ await settleWithin(+ useUserMemoryStore.getState().preHydrateContexts({ q }),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );++ return null;+};diff --git a/src/spa/router/activityListLoader.ts b/src/spa/router/activityListLoader.tsnew file mode 100644index 00000000000..0ff327ca762--- /dev/null+++ b/src/spa/router/activityListLoader.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 activities route's lazy+// chunks. The loader arguments carry the request, so the pre-hydrate can+// target the query the URL encodes.+export const activityListLoader = (args: LoaderFunctionArgs) =>+ import('@/routes/(main)/memory/activities/activitiesLoader').then((module) =>+ module.activityListLoader(args),+ );diff --git a/src/spa/router/activityListLoader.wiring.test.ts b/src/spa/router/activityListLoader.wiring.test.tsnew file mode 100644index 00000000000..8c10dd47ee7--- /dev/null+++ b/src/spa/router/activityListLoader.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 { activityListLoader } from './activityListLoader';+import { desktopRoutes } from './desktopRouter.config';++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/activities/activitiesLoader', () => {+ loaderModule.evaluated = true;+ return { activityListLoader: vi.fn(async () => null) };+});++const flatten = (routes: RouteObject[]): RouteObject[] =>+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);++describe('activity 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 activity list on the desktop activities route', () => {+ const routes = flatten(desktopRoutes).filter((r) => r.path === 'activities');++ expect(routes.length).toBeGreaterThan(0);++ expect(routes.map((r) => r.loader)).toEqual(routes.map(() => activityListLoader));+ });++ it('delegates to the real loader on first use', async () => {+ const { activityListLoader: realLoader } =+ await import('@/routes/(main)/memory/activities/activitiesLoader');++ const args = {+ request: new Request('https://app.lobehub.com/memory/activities?q=foo'),+ } as LoaderFunctionArgs;++ await expect(activityListLoader(args)).resolves.toBeNull();+ expect(realLoader).toHaveBeenCalledWith(args);+ });+});diff --git a/src/spa/router/contextListLoader.ts b/src/spa/router/contextListLoader.tsnew file mode 100644index 00000000000..8644b523463--- /dev/null+++ b/src/spa/router/contextListLoader.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 contexts route's lazy+// chunks. The loader arguments carry the request, so the pre-hydrate can+// target the query the URL encodes.+export const contextListLoader = (args: LoaderFunctionArgs) =>+ import('@/routes/(main)/memory/contexts/contextsLoader').then((module) =>+ module.contextListLoader(args),+ );diff --git a/src/spa/router/contextListLoader.wiring.test.ts b/src/spa/router/contextListLoader.wiring.test.tsnew file mode 100644index 00000000000..b259d4cefcc--- /dev/null+++ b/src/spa/router/contextListLoader.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 { contextListLoader } from './contextListLoader';+import { desktopRoutes } from './desktopRouter.config';++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/contexts/contextsLoader', () => {+ loaderModule.evaluated = true;+ return { contextListLoader: vi.fn(async () => null) };+});++const flatten = (routes: RouteObject[]): RouteObject[] =>+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);++describe('context 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 context list on the desktop contexts route', () => {+ const routes = flatten(desktopRoutes).filter((r) => r.path === 'contexts');++ expect(routes.length).toBeGreaterThan(0);++ expect(routes.map((r) => r.loader)).toEqual(routes.map(() => contextListLoader));+ });++ it('delegates to the real loader on first use', async () => {+ const { contextListLoader: realLoader } =+ await import('@/routes/(main)/memory/contexts/contextsLoader');++ const args = {+ request: new Request('https://app.lobehub.com/memory/contexts?q=foo'),+ } as LoaderFunctionArgs;++ await expect(contextListLoader(args)).resolves.toBeNull();+ expect(realLoader).toHaveBeenCalledWith(args);+ });+});diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 354924c7acc..f43e9ce3ad1 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -78,8 +78,10 @@ import {} from '@/routes/(main)/group/features/routeMeta';import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShellSkeleton';import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';+import { activityListLoader } from '@/spa/router/activityListLoader';import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';import { channelDataLoader } from '@/spa/router/channelDataLoader';+import { contextListLoader } from '@/spa/router/contextListLoader';import { identitiesListLoader } from '@/spa/router/identitiesListLoader';import { pageListLoader } from '@/spa/router/pageListLoader';import { preferenceListLoader } from '@/spa/router/preferenceListLoader';@@ -793,6 +795,8 @@ export const sharedMainAreaChildren: RouteObject[] = [handle: {meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),},+ // Seed the persisted head page before the page paints (see `contextListLoader`).+ loader: contextListLoader,path: 'contexts',},{@@ -825,6 +829,8 @@ export const sharedMainAreaChildren: RouteObject[] = [handle: {meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),},+ // Seed the persisted head page before the page paints (see `activityListLoader`).+ loader: activityListLoader,path: 'activities',},],diff --git a/src/store/user/displaySnapshot.ts b/src/store/user/displaySnapshot.tsindex a9d0a631d91..27cc97b9feb 100644--- a/src/store/user/displaySnapshot.ts+++ b/src/store/user/displaySnapshot.ts@@ -59,10 +59,15 @@ export const writeUserDisplaySnapshot = (const sanitized = sanitizeSnapshot(snapshot);if (!sanitized) return;- void storage.set(snapshotKey(userId), {- data: { ...readUserDisplaySnapshot(userId), ...sanitized },- updatedAt: Date.now(),- });+ // Best-effort: a failed write only costs the next cold start its snapshot.+ storage+ .set(snapshotKey(userId), {+ data: { ...readUserDisplaySnapshot(userId), ...sanitized },+ updatedAt: Date.now(),+ })+ .catch((error) => {+ console.error('[displaySnapshot] failed to persist the display snapshot', error);+ });};/**diff --git a/src/store/userMemory/slices/agent/replica.test.ts b/src/store/userMemory/slices/agent/replica.test.tsindex fa24eeb0954..5c6c45f407d 100644--- a/src/store/userMemory/slices/agent/replica.test.ts+++ b/src/store/userMemory/slices/agent/replica.test.ts@@ -374,6 +374,45 @@ describe('userMemory topic memories replica', () => {expect((await rowOf(TOPIC_B, rowScope))?.data).toEqual(bundle('active'));});+ it('purges a deleted user’s bundle whose write was still queued when the account switched', async () => {+ const storage = topicMemoriesResource.storage!;+ const rowOf = (topicId: string, scopeValue: string) =>+ storage.get({ queryKey: topicMemoriesResource.storageKey(topicId), scope: scopeValue });+ const deletedUser = rowScope;+ // The deleted user's bundle write is slow to land in IndexedDB.+ let release!: () => void;+ const held = new Promise<void>((resolve) => (release = resolve));+ const { set } = storage;+ vi.spyOn(storage, 'set').mockImplementation(async (key, row) => {+ if (key.scope === deletedUser) await held;+ return set(key, row);+ });+ vi.mocked(userMemoryService.retrieveMemoryForTopic).mockResolvedValue(bundle('deleted'));+ const first = renderHook(() => useUserMemoryStore((s) => s.useFetchMemoriesForTopic)(TOPIC_A), {+ wrapper,+ });+ await waitFor(() => expect(topicMemories(TOPIC_A)).toEqual(bundle('deleted')));+ first.unmount();++ // The account switches while that write is still queued; the purge runs now.+ useScope(`memory-user-${randomUUID()}:personal`);+ let purging!: Promise<boolean>;+ act(() => {+ purging = useUserMemoryStore.getState().internal_clearTopicMemories(deletedUser);+ });+ release();+ let cleared = false;+ await act(async () => {+ cleared = await purging;+ });++ expect(cleared).toBe(true);+ // The queued write landed before the purge's delete, never after it.+ await waitFor(async () => expect(await rowOf(TOPIC_A, deletedUser)).toBeUndefined());+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(await rowOf(TOPIC_A, deletedUser)).toBeUndefined();+ });+it('bounds the persisted topic bundles to the most recently visited topics', async () => {vi.mocked(userMemoryService.retrieveMemoryForTopic).mockImplementation(async (topicId) =>bundle(topicId),diff --git a/src/store/userMemory/slices/base/action.ts b/src/store/userMemory/slices/base/action.tsindex 93c7b4df2ed..7cff5a06b17 100644--- a/src/store/userMemory/slices/base/action.ts+++ b/src/store/userMemory/slices/base/action.ts@@ -119,10 +119,12 @@ export class BaseActionImpl {/** PersonaHeader confirmation deletes the persona through memoryCRUDService, then refreshes its replica. */deletePersona = async (): Promise<void> => {const { memoryCRUDService } = await import('@/services/userMemory');+ // The account whose persona is deleted (see `refreshPersona`).+ const user = userMemoryIdentityScope.get();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();+ await this.#get().refreshPersona(user);};/**diff --git a/src/store/userMemory/slices/home/action.ts b/src/store/userMemory/slices/home/action.tsindex 98e6f047c14..110d93802a2 100644--- a/src/store/userMemory/slices/home/action.ts+++ b/src/store/userMemory/slices/home/action.ts@@ -146,10 +146,19 @@ export class HomeActionImpl {* 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+ * trip. `user` is the account that asked (captured before the DELETE); when+ * another account is active by now, only that account's persisted persona is+ * purged. 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> => {+ refreshPersona = async (user?: string): Promise<void> => {+ // The account that deleted its persona switched away while the request ran:+ // purge that account's persisted persona (and keep it from hydrating back),+ // never the persona of the account now on screen.+ if (user !== undefined && user !== personaResource.scope.get()) {+ this.#persona.remove(PERSONA_KEY, user);+ return;+ }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.diff --git a/src/store/userMemory/slices/home/replica.test.ts b/src/store/userMemory/slices/home/replica.test.tsindex e9fda126512..d72b200bb47 100644--- a/src/store/userMemory/slices/home/replica.test.ts+++ b/src/store/userMemory/slices/home/replica.test.ts@@ -178,6 +178,47 @@ describe('userMemory home replicas', () => {});});+ it('clears the persona of the account that deleted it, not the account switched to', async () => {+ const rowOf = (scopeValue: string) =>+ personaResource.storage!.get({ queryKey: PERSONA_STORAGE_KEY, scope: scopeValue });+ // The deleting account has a persisted persona.+ personaSpy.mockResolvedValue(persona);+ const first = renderHook(() => useUserMemoryStore((s) => s.useFetchPersona)(), { wrapper });+ await waitFor(async () => expect((await rowOf(rowScope))?.data).toEqual({ persona }));+ first.unmount();+ const deletingUser = rowScope;++ // The DELETE is slow; the account switches while it runs.+ let finishDelete!: () => void;+ vi.spyOn(memoryCRUDService, 'deletePersona').mockImplementation(+ () => new Promise((resolve) => (finishDelete = () => resolve({ success: true }))) as never,+ );+ let deleting!: Promise<void>;+ act(() => {+ deleting = useUserMemoryStore.getState().deletePersona();+ });+ await waitFor(() => expect(finishDelete).toBeTypeOf('function'));++ const otherPersona = { content: 'Other persona', summary: 'Other' };+ useScope(`home-user-${randomUUID()}:personal`);+ personaSpy.mockResolvedValue(otherPersona);+ renderHook(() => useUserMemoryStore((s) => s.useFetchPersona)(), { wrapper });+ await waitFor(() => expect(useUserMemoryStore.getState().persona).toEqual(otherPersona));++ await act(async () => {+ finishDelete();+ await deleting;+ });++ // The deleting account's persisted persona is gone...+ await waitFor(async () => expect(await rowOf(deletingUser)).toBeUndefined());+ // ...and the account on screen keeps its own.+ expect(useUserMemoryStore.getState().persona).toEqual(otherPersona);+ await waitFor(async () =>+ expect((await rowOf(rowScope))?.data).toEqual({ persona: otherPersona }),+ );+ });+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)));diff --git a/src/store/userMemory/slices/identity/action.ts b/src/store/userMemory/slices/identity/action.tsindex 6fdb9d930d7..bc8589c01a5 100644--- a/src/store/userMemory/slices/identity/action.ts+++ b/src/store/userMemory/slices/identity/action.ts@@ -134,6 +134,7 @@ export class IdentityActionImpl {keys: () => Object.keys(get().identityListEntries),read: (key) => get().identityListEntries[key],refreshHead: () => this.refreshIdentities(),+ scope: () => identityListResource.scope.get(),slice: this.#identities,});}diff --git a/src/store/userMemory/slices/memoryLists.replica.test.ts b/src/store/userMemory/slices/memoryLists.replica.test.tsindex a1305500a7e..a5d42ad5af8 100644--- a/src/store/userMemory/slices/memoryLists.replica.test.ts+++ b/src/store/userMemory/slices/memoryLists.replica.test.ts@@ -401,6 +401,49 @@ describe.each(CASES)('$name list replica', (list) => {expect(ids(await stored())).toEqual(['b']);});+ it('applies a delete confirmed after an account switch to the account that asked', async () => {+ serve(() => ['a', 'b']);+ const first = renderHook(() => useFetch(), { wrapper });+ await waitFor(async () => expect(ids(await stored())).toEqual(['a', 'b']));+ const deletingUser = rowScope;++ let finishDelete!: () => void;+ vi.spyOn(memoryCRUDService, list.deleteMethod).mockImplementation(+ () => new Promise((resolve) => (finishDelete = () => resolve(undefined))) as never,+ );+ let deleting!: Promise<void>;+ act(() => {+ deleting = remove('a');+ });+ await waitFor(() => expect(finishDelete).toBeTypeOf('function'));+ first.unmount();++ // The account switches while the server deletes; the new one shows its own 'a'.+ useScope(`${list.name}-user-${randomUUID()}:personal`);+ serve(() => ['a', 'c']);+ renderHook(() => useFetch(), { wrapper });+ await waitFor(() => expect(ids(view())).toEqual(['a', 'c']));+ await waitFor(async () => expect(ids(await stored())).toEqual(['a', 'c']));++ await act(async () => {+ finishDelete();+ await deleting;+ });++ // The asking account's persisted rows lose the row...+ await waitFor(async () =>+ expect(+ ids(+ (await list.resource.storage.get({ queryKey: storageKey(), scope: deletingUser }))+ ?.data as ListData,+ ),+ ).toEqual(['b']),+ );+ // ...while the account on screen keeps its own list.+ expect(ids(view())).toEqual(['a', 'c']);+ expect(ids(await stored())).toEqual(['a', 'c']);+ });+it('removes a row optimistically and rolls it back when the server rejects', async () => {serve(() => ['a', 'b']);renderHook(() => useFetch(), { wrapper });diff --git a/src/store/userMemory/slices/utils/memoryQueryList.ts b/src/store/userMemory/slices/utils/memoryQueryList.tsindex b6ef712c7b8..67156c2be5f 100644--- a/src/store/userMemory/slices/utils/memoryQueryList.ts+++ b/src/store/userMemory/slices/utils/memoryQueryList.ts@@ -129,6 +129,7 @@ export class MemoryQueryList<keys: () => Object.keys(get()[entriesField] as Record<string, TData>),read: (key) => (get()[entriesField] as Record<string, TData>)[key],refreshHead: this.#revalidate,+ scope: () => resource.scope.get(),slice: this.#list,});}diff --git a/src/store/userMemory/slices/utils/offsetListPager.test.ts b/src/store/userMemory/slices/utils/offsetListPager.test.tsindex aea79e5c596..007ec66ada7 100644--- a/src/store/userMemory/slices/utils/offsetListPager.test.ts+++ b/src/store/userMemory/slices/utils/offsetListPager.test.ts@@ -1,6 +1,10 @@import { describe, expect, it, vi } from 'vitest';-import { OffsetListPager, type OffsetPagedSlice } from './offsetListPager';+import {+ MemoryDeleteScopeChangedError,+ OffsetListPager,+ type OffsetPagedSlice,+} from './offsetListPager';const deferred = <T = void>() => {let resolve!: (value: T) => void;@@ -12,6 +16,8 @@ const deferred = <T = void>() => {return { promise, reject, resolve };};+const scopeRef = { current: 'user-1:*' };+const setup = ({ refreshHead = vi.fn(async () => undefined) } = {}) => {const log: string[] = [];const tokens = { commit: vi.fn(), rollback: vi.fn() };@@ -33,6 +39,7 @@ const setup = ({ refreshHead = vi.fn(async () => undefined) } = {}) => {const pager = new OffsetListPager({keys: () => ['all'],read: (key) => views[key],+ scope: () => scopeRef.current,refreshHead,slice,});@@ -57,6 +64,50 @@ describe('OffsetListPager', () => {expect(pager.isHeadStale('all')).toBe(true);});+ it('routes a delete confirmed after an account switch to the account that asked', async () => {+ scopeRef.current = 'user-1:*';+ const { log, pager, refreshHead, slice } = setup();+ const server = deferred();+ const serverDelete = vi.fn(() => server.promise);++ const deleting = pager.delete('a', serverDelete);+ // The account switches while the server deletes (the request was sent).+ await vi.waitFor(() => expect(serverDelete).toHaveBeenCalled());+ scopeRef.current = 'user-2:*';+ server.resolve();+ await deleting;++ expect(slice.removeEntity).toHaveBeenCalledWith('a', { scope: 'user-1:*' });+ // Nothing on screen (the other account's lists) is collapsed or refreshed.+ expect(log).not.toContain('collapse:all');+ expect(refreshHead).not.toHaveBeenCalled();+ expect(pager.isHeadStale('all')).toBe(false);+ scopeRef.current = 'user-1:*';+ });++ it('does not send a queued delete once another account is active', async () => {+ scopeRef.current = 'user-1:*';+ const page = deferred();+ const { pager, slice, tokens } = setup();+ vi.mocked(slice.loadMore).mockImplementation(() => page.promise);+ const serverDelete = vi.fn(async () => undefined);++ // The delete queues behind a page in flight...+ const paging = pager.loadMore('all');+ const deleting = pager.delete('a', serverDelete);+ // ...and the account switches before its turn comes.+ scopeRef.current = 'user-2:*';+ page.resolve();+ await paging;++ await expect(deleting).rejects.toBeInstanceOf(MemoryDeleteScopeChangedError);+ // Never sent under the new account; the optimistic removal is rolled back.+ expect(serverDelete).not.toHaveBeenCalled();+ expect(tokens.rollback).toHaveBeenCalledTimes(1);+ expect(slice.removeEntity).not.toHaveBeenCalled();+ scopeRef.current = 'user-1:*';+ });+it('rolls the optimistic removal back when the server rejects', async () => {const { log, pager, tokens } = setup();diff --git a/src/store/userMemory/slices/utils/offsetListPager.ts b/src/store/userMemory/slices/utils/offsetListPager.tsindex 9da4ad9c9c7..65416061ba3 100644--- a/src/store/userMemory/slices/utils/offsetListPager.ts+++ b/src/store/userMemory/slices/utils/offsetListPager.ts@@ -8,7 +8,8 @@ export interface OffsetPagedSlice {) => ReplicaOptimisticToken<any>[];collapse: (key: string) => unknown;loadMore: (key: string) => Promise<void>;- removeEntity: (id: string) => void;+ /** `scope` routes a removal confirmed after an account switch to the scope that asked. */+ removeEntity: (id: string, options?: { scope?: string }) => void;update: (key: string, apply: (data: any) => any, options?: { persist?: boolean }) => unknown;}@@ -23,9 +24,23 @@ interface OffsetListPagerOptions {* settled, whether or not it succeeded.*/refreshHead: () => Promise<unknown>;+ /** The list resource's active scope (the user the store shows). */+ scope: () => string;slice: OffsetPagedSlice;}+/**+ * A delete that waited behind other paging work and found another account+ * active when its turn came. It was not sent: the server call would run with+ * the new account's credentials. The optimistic removal is rolled back.+ */+export class MemoryDeleteScopeChangedError extends Error {+ constructor() {+ super('The account changed before the delete could be sent');+ this.name = 'MemoryDeleteScopeChangedError';+ }+}+/** 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');@@ -58,6 +73,7 @@ export class OffsetListPager {readonly #loadingMore = new Map<string, Promise<void>>();readonly #read: OffsetListPagerOptions['read'];readonly #refreshHead: () => Promise<unknown>;+ readonly #scope: () => string;readonly #slice: OffsetPagedSlice;readonly #staleHeads = new Set<string>();/** Serialized paging work not settled yet. */@@ -65,7 +81,8 @@ export class OffsetListPager {/** Tail of the serialized paging work. */#tail: Promise<unknown> = Promise.resolve();- constructor({ keys, read, refreshHead, slice }: OffsetListPagerOptions) {+ constructor({ keys, read, refreshHead, scope, slice }: OffsetListPagerOptions) {+ this.#scope = scope;this.#keys = keys;this.#read = read;this.#refreshHead = refreshHead;@@ -130,9 +147,18 @@ export class OffsetListPager {* rolling the optimistic removal back.*/delete = (id: string, serverCall: () => Promise<unknown>): Promise<void> => {+ // The account that asks for the delete. If another one is active once the+ // server confirms, the removal belongs to this one's persisted rows only.+ const scope = this.#scope();const tokens = this.#slice.beginEntityOptimistic(id, () => undefined);return this.#serialize(async () => {+ // Queued behind a page or another delete: by the time it runs, another+ // account may be active. Never send it under that account's credentials.+ if (this.#scope() !== scope) {+ for (const token of tokens) token.rollback();+ throw new MemoryDeleteScopeChangedError();+ }try {await serverCall();} catch (error) {@@ -140,6 +166,15 @@ export class OffsetListPager {throw error;}for (const token of tokens) token.commit();++ if (this.#scope() !== scope) {+ // Account switched meanwhile: drop the row from the requesting account's+ // persisted query rows (and guard its hydrates). The page sets on screen+ // belong to the other account — no collapse, no head refresh for them.+ this.#slice.removeEntity(id, { scope });+ return;+ }+// 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);diff --git a/src/store/userMemory/utils/replica.ts b/src/store/userMemory/utils/replica.tsindex 54db0aee8f7..fd3596277d4 100644--- a/src/store/userMemory/utils/replica.ts+++ b/src/store/userMemory/utils/replica.ts@@ -2,9 +2,7 @@ import {cacheScope,definePagedReplica,defineReplica,- REPLICA_INDEX_KEY,type ReplicaScope,- type ReplicaStorage,stableQueryKey,} from '@/libs/replica';@@ -88,54 +86,13 @@ export const memoryListKey = <T extends { pageSize?: number; q?: string }>({/** 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> };+ /**+ * `clear()` for a scope that may not be active: purges its persisted rows+ * behind the writes already queued for it (`engine.clearScope`).+ */+ clearScope: (scope: string) => Promise<boolean>;}-/** 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@@ -150,5 +107,5 @@ export const clearUserReplicas = (if (user === undefined || user === userMemoryIdentityScope.get())return clearReplicas(...replicas.map((replica) => replica.clear));- return clearReplicas(...replicas.map((replica) => () => purgeOffScope(replica, user)));+ return clearReplicas(...replicas.map((replica) => () => replica.clearScope(user)));};