🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(userMemory): move the base slice onto @lobechat/replica (#20740)
Arvin Xu7dfa9e8547df
diff --git a/src/store/userMemory/initialState.ts b/src/store/userMemory/initialState.tsindex fb917e1ecf1..a24febe4880 100644--- a/src/store/userMemory/initialState.ts+++ b/src/store/userMemory/initialState.ts@@ -1,9 +1,12 @@import { type RetrieveMemoryParams, type RetrieveMemoryResult } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import { type ActivitySliceState } from './slices/activity';import { activityInitialState } from './slices/activity';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';@@ -31,8 +34,17 @@ export interface UserMemoryStoreStateeditingMemoryContent?: string;editingMemoryId?: string;editingMemoryLayer?: 'activity' | 'context' | 'experience' | 'identity' | 'preference';+ /**+ * Canonical replica view of one memory detail, keyed `${layer}:${id}`. The+ * engine owns every write; readers go through `useFetchMemoryDetail`.+ */+ memoryDetailMap: Record<string, MemoryDetailDisplay>;+ /** Local-first bookkeeping for `memoryDetailMap`. */+ memoryDetailReplica: ReplicaState<MemoryDetailDisplay>;memoryFetchedAtMap: Record<string, number>;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 }[];@@ -52,8 +64,11 @@ export const initialState: UserMemoryStoreState = {editingMemoryContent: undefined,editingMemoryId: undefined,editingMemoryLayer: undefined,+ memoryDetailMap: {},+ memoryDetailReplica: createReplicaState<MemoryDetailDisplay>(),memoryFetchedAtMap: {},memoryMap: {},+ memoryRetrieveReplica: createReplicaState<RetrieveMemoryResult>(),persona: undefined,personaInit: false,roles: [],diff --git a/src/store/userMemory/slices/base/action.ts b/src/store/userMemory/slices/base/action.tsindex b132b2b6332..6ab54d32b46 100644--- a/src/store/userMemory/slices/base/action.ts+++ b/src/store/userMemory/slices/base/action.ts@@ -1,9 +1,8 @@-import isEqual from 'fast-deep-equal';import { produce } from 'immer';import { type SWRResponse } from 'swr';-import useSWR from 'swr';-import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';+import { createReplicaSlice, type ReplicaLens, type ReplicaSyncResult } from '@/libs/replica';+import { mutate, useClientDataSWRWithSync } from '@/libs/swr';import { userMemoryKeys } from '@/libs/swr/keys';import { memoryCRUDService, userMemoryService } from '@/services/userMemory';import { type StoreSetter } from '@/store/types';@@ -11,7 +10,7 @@ import { type RetrieveMemoryParams, type RetrieveMemoryResult } from '@/types/usimport { LayersEnum } from '@/types/userMemory';import { setNamespace } from '@/utils/storeDebug';-import { type UserMemoryStore } from '../../store';+import { type UserMemoryStore, useUserMemoryStore } from '../../store';import { type IdentityForInjection } from '../../types';import { userMemoryCacheKey } from '../../utils/cacheKey';import { createMemorySearchParams } from '../../utils/searchParams';@@ -20,23 +19,94 @@ import { contextInitialState } from '../context/initialState';import { experienceInitialState } from '../experience/initialState';import { identityInitialState } from '../identity/initialState';import { preferenceInitialState } from '../preference/initialState';+import {+ type MemoryDetailDisplay,+ memoryDetailKey,+ type MemoryDetailParams,+ userMemoryDetailResource,+ userMemoryRetrieveResource,+} from './projection';const n = setNamespace('userMemory');type MemoryContext = Parameters<typeof createMemorySearchParams>[0];+/**+ * The retrieve result map keeps its long-standing flat field (`memoryMap`) as the+ * replica view, plus the per-entry fetched-at stamp the memory selectors read.+ * The engine owns every write; the selectors keep reading the same place.+ */+const retrieveMapLens: ReplicaLens<UserMemoryStore, RetrieveMemoryResult> = {+ clear: () => ({ memoryFetchedAtMap: {}, memoryMap: {} }),+ get: (state, key) => state.memoryMap[key],+ keys: (state) => Object.keys(state.memoryMap),+ set: (state, key, data) => {+ const memoryMap = { ...state.memoryMap };+ const memoryFetchedAtMap = { ...state.memoryFetchedAtMap };++ if (data === undefined) {+ delete memoryMap[key];+ delete memoryFetchedAtMap[key];+ } else {+ memoryMap[key] = data;+ memoryFetchedAtMap[key] = Date.now();+ }++ return { memoryFetchedAtMap, memoryMap };+ },+};++/**+ * One memory detail per `${layer}:${id}`, mirrored into `memoryDetailMap` so the+ * right-hand panels read the replica view instead of a raw SWR cache entry.+ */+const detailMapLens: ReplicaLens<UserMemoryStore, MemoryDetailDisplay> = {+ clear: () => ({ memoryDetailMap: {} }),+ get: (state, key) => state.memoryDetailMap[key],+ keys: (state) => Object.keys(state.memoryDetailMap),+ set: (state, key, data) => {+ const memoryDetailMap = { ...state.memoryDetailMap };++ if (data === undefined) delete memoryDetailMap[key];+ else memoryDetailMap[key] = data;++ return { memoryDetailMap };+ },+};+type Setter = StoreSetter<UserMemoryStore>;export const createBaseSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>new BaseActionImpl(set, get, _api);export class BaseActionImpl {+ readonly #detail;readonly #get: () => UserMemoryStore;+ readonly #retrieve;readonly #set: Setter;constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#detail = createReplicaSlice(userMemoryDetailResource, {+ actionPrefix: n('memoryDetail'),+ fetcher: (params) => this.#fetchDetail(params),+ get,+ // A detail the server no longer has removes the cached one, so a memory+ // deleted elsewhere (or a stale detail URL) renders the not-found state.+ isMissing: (detail) => detail === null,+ set,+ stateKey: 'memoryDetailReplica',+ view: detailMapLens,+ });+ this.#retrieve = createReplicaSlice(userMemoryRetrieveResource, {+ actionPrefix: n('memoryRetrieve'),+ fetcher: (params) => userMemoryService.retrieveMemory(params),+ get,+ set,+ stateKey: 'memoryRetrieveReplica',+ view: retrieveMapLens,+ });}clearEditingMemory = (): void => {@@ -65,11 +135,71 @@ export class BaseActionImpl {);};+ /**+ * Flatten the nested detail response into the shape the right-hand panel+ * reads. `null` means "no such memory": it removes the cached detail+ * (`isMissing`), and the panel renders as empty.+ */+ #fetchDetail = async ({ id, layer }: MemoryDetailParams): Promise<MemoryDetailDisplay | null> => {+ const detail = await userMemoryService.getMemoryDetail({ id, layer });+ if (!detail || detail.layer !== layer) return null;++ const source = { source: detail.source, sourceType: detail.sourceType };++ switch (detail.layer) {+ case LayersEnum.Activity: {+ return { ...detail.memory, ...detail.activity, ...source };+ }+ case LayersEnum.Context: {+ return { ...detail.memory, ...detail.context, ...source };+ }+ case LayersEnum.Experience: {+ return { ...detail.memory, ...detail.experience, ...source };+ }+ case LayersEnum.Identity: {+ return { ...detail.memory, ...detail.identity, ...source };+ }+ case LayersEnum.Preference: {+ return { ...detail.memory, ...detail.preference, ...source };+ }+ default: {+ return null;+ }+ }+ };++ /**+ * Drop the retrieve map and every memory detail through their replicas:+ * memory, every persisted row of the active scope (including query variants+ * not loaded in memory) and reads in flight. Called by `purgeAllMemories`+ * before it revalidates. A storage failure leaves a row the next session has+ * 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;+ };+purgeAllMemories = async (): Promise<void> => {const { memoryCRUDService } = await import('@/services/userMemory');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).+ const replicaPurges: boolean[] = [+ // One line per replica-backed slice.+ await this.#get().internal_clearMemoryReplicas(),+ ];+this.#set(produce((draft) => {Object.assign(draft, activityInitialState);@@ -83,8 +213,6 @@ export class BaseActionImpl {draft.editingMemoryContent = undefined;draft.editingMemoryId = undefined;draft.editingMemoryLayer = undefined;- draft.memoryFetchedAtMap = {};- draft.memoryMap = {};draft.persona = undefined;draft.personaInit = true;draft.roles = [];@@ -133,6 +261,13 @@ export class BaseActionImpl {{ revalidate: false },),]);++ // 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)) {+ throw new Error('Failed to purge persisted memories from local storage');+ }};refreshUserMemory = async (params: RetrieveMemoryParams): Promise<void> => {@@ -249,85 +384,35 @@ export class BaseActionImpl {}};+ /**+ * Fetch orchestration for one memory detail. Returns an `SWRResponse`-shaped+ * value — `data` reads the replica view — so the existing right panels are+ * untouched; the detail lands in `memoryDetailMap`, never in this return value.+ */useFetchMemoryDetail = (id: string | null, layer: LayersEnum): SWRResponse<any> => {- const swrKey = id ? userMemoryKeys.memoryDetail(layer, id) : null;-- return useSWR(- swrKey,- async () => {- if (!id) return null;-- const detail = await userMemoryService.getMemoryDetail({ id, layer });-- if (!detail) return null;-- // Transform nested structure to flat structure- switch (layer) {- case LayersEnum.Activity: {- if (detail.layer === LayersEnum.Activity) {- return {- ...detail.memory,- ...detail.activity,- source: detail.source,- sourceType: detail.sourceType,- };- }- break;- }- case LayersEnum.Context: {- if (detail.layer === LayersEnum.Context) {- return {- ...detail.memory,- ...detail.context,- source: detail.source,- sourceType: detail.sourceType,- };- }- break;- }- case LayersEnum.Experience: {- if (detail.layer === LayersEnum.Experience) {- return {- ...detail.memory,- ...detail.experience,- source: detail.source,- sourceType: detail.sourceType,- };- }- break;- }- case LayersEnum.Identity: {- if (detail.layer === LayersEnum.Identity) {- return {- ...detail.memory,- ...detail.identity,- source: detail.source,- sourceType: detail.sourceType,- };- }- break;- }- case LayersEnum.Preference: {- if (detail.layer === LayersEnum.Preference) {- return {- ...detail.memory,- ...detail.preference,- source: detail.source,- sourceType: detail.sourceType,- };- }- break;- }- }+ const sync: ReplicaSyncResult = this.#detail.useSync(id ? { id, layer } : null, {+ enabled: Boolean(id),+ revalidateOnFocus: false,+ });- return null;- },- {- revalidateOnFocus: false,- },+ const detail = useUserMemoryStore((state) =>+ id ? state.memoryDetailMap[memoryDetailKey({ id, layer })] : undefined,);++ return {+ data: detail,+ error: sync.error,+ isLoading: !detail && (sync.isValidating || !sync.isHydrated),+ isValidating: sync.isValidating,+ mutate: sync.revalidate,+ } as unknown as SWRResponse<any>;};+ /**+ * Fetch orchestration for the retrieve memory map. The rows land in+ * `memoryMap` (keyed by the query cache key); this return value only carries+ * the sync flags, so any existing consumer keeps its shape.+ */useFetchUserMemory = (enable: boolean,params?: RetrieveMemoryParams,@@ -335,66 +420,20 @@ export class BaseActionImpl {const resolvedParams = params ?? this.#get().activeParams;const key = resolvedParams ? userMemoryCacheKey(resolvedParams) : undefined;- return useClientDataSWR<RetrieveMemoryResult>(- enable && resolvedParams ? userMemoryKeys.retrieve(key) : null,- () => userMemoryService.retrieveMemory(resolvedParams!),- {- onSuccess: (result) => {- if (!resolvedParams || !key) return;-- const state = this.#get();- const previous = state.memoryMap[key];- const next = result ?? { activities: [], contexts: [], experiences: [], preferences: [] };- const fetchedAt = Date.now();+ const enabled = enable && Boolean(resolvedParams);+ const sync: ReplicaSyncResult = this.#retrieve.useSync(resolvedParams ?? null, { enabled });- if (previous && isEqual(previous, next)) {- this.#set(- {- memoryFetchedAtMap: {- ...state.memoryFetchedAtMap,- [key]: fetchedAt,- },- },- false,- n('useFetchUserMemory/refresh', {- key,- totals: {- activities: next.activities.length,- contexts: next.contexts.length,- experiences: next.experiences.length,- preferences: next.preferences.length,- },- }),- );-- return;- }+ const data = useUserMemoryStore((state) => (key ? state.memoryMap[key] : undefined));- this.#set(- {- memoryFetchedAtMap: {- ...state.memoryFetchedAtMap,- [key]: fetchedAt,- },- memoryMap: {- ...state.memoryMap,- [key]: next,- },- },- false,- n('useFetchUserMemory/success', {- key,- totals: {- activities: next.activities.length,- contexts: next.contexts.length,- experiences: next.experiences.length,- preferences: next.preferences.length,- },- }),- );- },- },- );+ return {+ data,+ error: sync.error,+ // A disabled read neither hydrates nor fetches: it is not loading (the+ // former null-SWR-key behaviour), even though its row is not hydrated.+ isLoading: enabled && !data && (sync.isValidating || !sync.isHydrated),+ isValidating: sync.isValidating,+ mutate: sync.revalidate,+ } as unknown as SWRResponse<RetrieveMemoryResult>;};useInitIdentities = (isLogin: boolean): SWRResponse<any> => {diff --git a/src/store/userMemory/slices/base/index.ts b/src/store/userMemory/slices/base/index.tsindex ceb887490ed..0b05bc0ed47 100644--- a/src/store/userMemory/slices/base/index.ts+++ b/src/store/userMemory/slices/base/index.ts@@ -1 +1,8 @@export { type BaseAction, createBaseSlice } from './action';+export {+ type MemoryDetailDisplay,+ memoryDetailKey,+ type MemoryDetailParams,+ userMemoryDetailResource,+ userMemoryRetrieveResource,+} from './projection';diff --git a/src/store/userMemory/slices/base/projection.ts b/src/store/userMemory/slices/base/projection.tsnew file mode 100644index 00000000000..5c8455ae6a7--- /dev/null+++ b/src/store/userMemory/slices/base/projection.ts@@ -0,0 +1,61 @@+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';++/**+ * One query of the memory retrieve endpoint (`userMemoryService.retrieveMemory`).+ *+ * The entry key is the long-standing cache key of the query, so the replica view+ * (`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 interface MemoryDetailParams {+ id: string;+ layer: LayersEnum;+}++/**+ * The flattened detail one right-hand panel reads: the base memory fields, the+ * layer's own row and the resolved source link.+ */+export type MemoryDetailDisplay = Record<string, unknown>;++/** Entry key of one memory detail: one entry per layer + id. */+export const memoryDetailKey = ({ id, layer }: MemoryDetailParams): string => `${layer}:${id}`;++/**+ * One memory detail (`userMemoryService.getMemoryDetail`).+ *+ * A detail is a single transient read behind the right panel. It stays out of+ * storage on purpose: a deleted or edited memory must never paint a stale+ * persisted copy before the network confirms it. The fetcher answers `null`+ * for a memory the server no longer has, which removes the cached detail+ * (`isMissing`).+ */+export const userMemoryDetailResource = defineReplica<+ MemoryDetailParams,+ MemoryDetailDisplay,+ MemoryDetailDisplay | null+>({+ key: memoryDetailKey,+ name: 'userMemoryDetail',+ storage: 'memory',+ // Adopt the existing SWR key so a legacy `mutate(memoryDetail(...))` still matches.+ syncKey: ({ id, layer }) => userMemoryKeys.memoryDetail(layer, id),+ version: 1,+});diff --git a/src/store/userMemory/slices/base/replica.test.ts b/src/store/userMemory/slices/base/replica.test.tsnew file mode 100644index 00000000000..200bbfb724b--- /dev/null+++ b/src/store/userMemory/slices/base/replica.test.ts@@ -0,0 +1,382 @@+/**+ * @vitest-environment happy-dom+ *+ * The user-memory base slice's server reads are `@lobechat/replica` resources:+ * the retrieve result map and one memory detail per `${layer}:${id}`. These+ * tests pin the local-first guarantees and the shape the existing consumers+ * keep reading (`memoryMap` / `memoryDetailMap`), plus the purge that drops the+ * views and their persisted rows through the engine.+ */+import { randomUUID } from 'node:crypto';++import { type RetrieveMemoryParams, type RetrieveMemoryResult } 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, REPLICA_INDEX_KEY } 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 {+ memoryDetailKey,+ userMemoryDetailResource,+ userMemoryRetrieveResource,+} from './projection';++const PARAMS = { queries: ['alpha'] } as RetrieveMemoryParams;+const RETRIEVE_KEY = userMemoryRetrieveResource.key(PARAMS);+const OTHER_PARAMS = { queries: ['beta'] } as RetrieveMemoryParams;+const OTHER_RETRIEVE_KEY = userMemoryRetrieveResource.key(OTHER_PARAMS);+const DETAIL_PARAMS = { id: 'pref-1', layer: LayersEnum.Preference };+const DETAIL_KEY = memoryDetailKey(DETAIL_PARAMS);++const emptyResult = (): RetrieveMemoryResult => ({+ activities: [],+ contexts: [],+ experiences: [],+ preferences: [],+});++/** 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 base replica', () => {+ const scopes = new Set<string>();+ let scope = '';+ let retrieveSpy: ReturnType<typeof vi.spyOn>;+ let detailSpy: ReturnType<typeof vi.spyOn>;++ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };++ beforeEach(() => {+ useScope(`base-user-${randomUUID()}:personal`);+ retrieveSpy = vi.spyOn(userMemoryService, 'retrieveMemory');+ detailSpy = vi.spyOn(userMemoryService, 'getMemoryDetail');+ act(() => useUserMemoryStore.setState(initialState, false));+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].flatMap((value) =>+ [RETRIEVE_KEY, OTHER_RETRIEVE_KEY].map((queryKey) =>+ userMemoryRetrieveResource.storage!.remove({ queryKey, scope: value }),+ ),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ describe('retrieve map', () => {+ it('paints the persisted result before the network answers', async () => {+ const cached: RetrieveMemoryResult = {+ ...emptyResult(),+ preferences: [{ id: 'cached-1' } as never],+ };+ await userMemoryRetrieveResource.storage!.set(+ { queryKey: RETRIEVE_KEY, scope },+ { data: cached, updatedAt: 1 },+ );+ retrieveSpy.mockImplementation(pending);++ renderHook(() => useUserMemoryStore((s) => s.useFetchUserMemory)(true, PARAMS), { wrapper });++ await waitFor(() =>+ expect(useUserMemoryStore.getState().memoryMap[RETRIEVE_KEY]).toEqual(cached),+ );+ expect(useUserMemoryStore.getState().memoryFetchedAtMap[RETRIEVE_KEY]).toBeTypeOf('number');+ });++ it('confirms the server result and persists it', async () => {+ const server: RetrieveMemoryResult = {+ ...emptyResult(),+ activities: [{ id: 'a-1' } as never],+ };+ retrieveSpy.mockResolvedValue(server);++ renderHook(() => useUserMemoryStore((s) => s.useFetchUserMemory)(true, PARAMS), { wrapper });++ await waitFor(() =>+ expect(useUserMemoryStore.getState().memoryMap[RETRIEVE_KEY]).toEqual(server),+ );+ await waitFor(async () => {+ const row = await userMemoryRetrieveResource.storage!.get({+ queryKey: RETRIEVE_KEY,+ scope,+ });+ expect(row?.data).toEqual(server);+ });+ });++ it('is not loading while the caller disables it', async () => {+ retrieveSpy.mockImplementation(pending);++ const { result } = renderHook(+ () => useUserMemoryStore((s) => s.useFetchUserMemory)(false, PARAMS),+ { wrapper },+ );++ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(result.current.data).toBeUndefined();+ expect(result.current.isLoading).toBe(false);+ });++ it('does not fetch while the caller disables it', () => {+ retrieveSpy.mockResolvedValue(emptyResult());++ renderHook(() => useUserMemoryStore((s) => s.useFetchUserMemory)(false, PARAMS), { wrapper });++ expect(retrieveSpy).not.toHaveBeenCalled();+ });+ });++ describe('memory detail', () => {+ it('flattens the detail into memoryDetailMap and returns it from the hook', async () => {+ detailSpy.mockResolvedValue({+ layer: LayersEnum.Preference,+ memory: { id: 'mem-1', tags: [], title: 'Preference' },+ preference: { conclusionDirectives: 'Prefer concise answers.', id: 'pref-1' },+ source: { id: 'topic-1' },+ sourceType: 'chat_topic',+ } as never);++ const { result } = renderHook(+ () => useUserMemoryStore((s) => s.useFetchMemoryDetail)('pref-1', LayersEnum.Preference),+ { wrapper },+ );++ await waitFor(() =>+ expect(result.current.data).toMatchObject({+ conclusionDirectives: 'Prefer concise answers.',+ id: 'pref-1',+ sourceType: 'chat_topic',+ title: 'Preference',+ }),+ );+ expect(useUserMemoryStore.getState().memoryDetailMap[DETAIL_KEY]).toMatchObject({+ conclusionDirectives: 'Prefer concise answers.',+ id: 'pref-1',+ });+ expect(detailSpy).toHaveBeenCalledWith({ id: 'pref-1', layer: LayersEnum.Preference });+ });++ it('returns empty when the memory is gone', async () => {+ detailSpy.mockResolvedValue(null as never);++ const { result } = renderHook(+ () => useUserMemoryStore((s) => s.useFetchMemoryDetail)('pref-1', LayersEnum.Preference),+ { wrapper },+ );++ await waitFor(() => expect(detailSpy).toHaveBeenCalled());+ expect(result.current.data).toBeUndefined();+ expect(useUserMemoryStore.getState().memoryDetailMap).toEqual({});+ });++ it('removes a loaded detail when a later fetch reports it missing', async () => {+ detailSpy.mockResolvedValue({+ layer: LayersEnum.Preference,+ memory: { id: 'mem-1', tags: [], title: 'Preference' },+ preference: { conclusionDirectives: 'x', id: 'pref-1' },+ } as never);++ const { result } = renderHook(+ () => useUserMemoryStore((s) => s.useFetchMemoryDetail)('pref-1', LayersEnum.Preference),+ { wrapper },+ );+ await waitFor(() => expect(result.current.data).toBeDefined());++ // Deleted in another tab: the revalidation answers "no such memory".+ detailSpy.mockResolvedValue(null as never);+ await act(async () => {+ await result.current.mutate();+ });++ await waitFor(() => expect(result.current.data).toBeUndefined());+ expect(useUserMemoryStore.getState().memoryDetailMap[DETAIL_KEY]).toBeUndefined();+ expect(result.current.isLoading).toBe(false);+ });++ it('does not fetch without an id', () => {+ detailSpy.mockResolvedValue(null as never);++ renderHook(+ () => useUserMemoryStore((s) => s.useFetchMemoryDetail)(null, LayersEnum.Preference),+ { wrapper },+ );++ expect(detailSpy).not.toHaveBeenCalled();+ });+ });++ describe('purgeAllMemories', () => {+ it('retries a failed local purge, then surfaces it after the in-memory reset', async () => {+ 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 };+ await storage.set(rowKey, { data: emptyResult(), updatedAt: 1 });+ await storage.set(indexRowKey, { data: [RETRIEVE_KEY], updatedAt: 1 });++ const remove = storage.remove.bind(storage);+ let failDeletes = true;+ let removeCalls = 0;+ vi.spyOn(storage, 'remove').mockImplementation(async (key) => {+ if (!failDeletes) return remove(key);+ removeCalls++;+ throw new Error('IndexedDB transaction aborted');+ });+ act(() =>+ useUserMemoryStore.setState({+ memoryMap: { [RETRIEVE_KEY]: emptyResult() },+ tags: ['x'] as never,+ }),+ );++ try {+ await act(async () => {+ await expect(useUserMemoryStore.getState().purgeAllMemories()).rejects.toThrow(+ /local storage/,+ );+ });++ // Retried once, and the in-memory reset still stands.+ expect(removeCalls).toBeGreaterThan(1);+ expect(useUserMemoryStore.getState().memoryMap).toEqual({});+ expect(useUserMemoryStore.getState().tags).toEqual([]);+ } finally {+ // Let the suite's cleanup reach storage again.+ failDeletes = false;+ }+ });++ it('drops the retrieve/detail views and the persisted retrieve row', async () => {+ const server: RetrieveMemoryResult = {+ ...emptyResult(),+ preferences: [{ id: 'p' } as never],+ };+ retrieveSpy.mockResolvedValue(server);+ detailSpy.mockResolvedValue({+ layer: LayersEnum.Preference,+ memory: { id: 'mem-1', tags: [], title: 'Preference' },+ preference: { conclusionDirectives: 'x', id: 'pref-1' },+ } as never);+ vi.spyOn(memoryCRUDService, 'deleteAll').mockResolvedValue({} as never);++ renderHook(+ () => ({+ detail: useUserMemoryStore((s) => s.useFetchMemoryDetail)(+ 'pref-1',+ LayersEnum.Preference,+ ),+ retrieve: useUserMemoryStore((s) => s.useFetchUserMemory)(true, PARAMS),+ }),+ { wrapper },+ );++ await waitFor(() =>+ expect(useUserMemoryStore.getState().memoryMap[RETRIEVE_KEY]).toBeDefined(),+ );+ await waitFor(() =>+ expect(useUserMemoryStore.getState().memoryDetailMap[DETAIL_KEY]).toBeDefined(),+ );+ await waitFor(async () =>+ expect(+ await userMemoryRetrieveResource.storage!.get({ queryKey: RETRIEVE_KEY, scope }),+ ).toBeDefined(),+ );++ // After the purge the server has nothing left to answer with.+ retrieveSpy.mockImplementation(pending);+ detailSpy.mockImplementation(pending);+ await act(async () => {+ await useUserMemoryStore.getState().purgeAllMemories();+ });++ 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 });+ expect(row).toBeUndefined();+ });++ it('purges persisted retrieve rows of queries that are not loaded in memory', async () => {+ retrieveSpy.mockResolvedValue({ ...emptyResult(), preferences: [{ id: 'old' } as never] });+ vi.spyOn(memoryCRUDService, 'deleteAll').mockResolvedValue({} as never);++ // An earlier session persisted OTHER_PARAMS; after a reload it is not in memory.+ const earlier = renderHook(+ () => useUserMemoryStore((s) => s.useFetchUserMemory)(true, OTHER_PARAMS),+ { wrapper },+ );+ await waitFor(async () =>+ expect(+ await userMemoryRetrieveResource.storage!.get({ queryKey: OTHER_RETRIEVE_KEY, scope }),+ ).toBeDefined(),+ );+ earlier.unmount();+ // Keep an SWR provider mounted for the purge's legacy cache mutations.+ renderHook(() => null, { wrapper });+ act(() => useUserMemoryStore.setState(initialState, false));+ expect(useUserMemoryStore.getState().memoryMap).toEqual({});++ await act(async () => {+ await useUserMemoryStore.getState().purgeAllMemories();+ });++ expect(+ await userMemoryRetrieveResource.storage!.get({ queryKey: OTHER_RETRIEVE_KEY, scope }),+ ).toBeUndefined();++ // Requesting that query again paints nothing deleted while the fetch is pending.+ retrieveSpy.mockImplementation(pending);+ const reloaded = renderHook(+ () => useUserMemoryStore((s) => s.useFetchUserMemory)(true, OTHER_PARAMS),+ { wrapper },+ );+ await waitFor(() => expect(reloaded.result.current.isLoading).toBe(true));+ expect(useUserMemoryStore.getState().memoryMap[OTHER_RETRIEVE_KEY]).toBeUndefined();+ });+ });++ it('uses the long-standing SWR keys as the sync keys', () => {+ expect(userMemoryRetrieveResource.syncKey?.(PARAMS)).toEqual([+ 'userMemory:retrieve',+ RETRIEVE_KEY,+ ]);+ expect(userMemoryDetailResource.syncKey?.(DETAIL_PARAMS)).toEqual([+ 'userMemory:memoryDetail',+ 'preference',+ 'pref-1',+ ]);+ });+});