π€― 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
β¨ feat(swr): unified tiered cache provider (localStorage + IndexedDB) with scope isolation (#15844)
Arvin Xuedf058e3251f
diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.tsindex 13b677537c1..31af9c230a4 100644--- a/src/features/Conversation/store/slices/data/action.test.ts+++ b/src/features/Conversation/store/slices/data/action.test.ts@@ -713,7 +713,7 @@ describe('DataSlice', () => {// Key should be an array with prefix and context objectexpect(Array.isArray(swrKey)).toBe(true);- expect(swrKey[0]).toBe('CONVERSATION_FETCH_MESSAGES');+ expect(swrKey[0]).toBe('message:list');expect(swrKey[1]).toEqual({agentId: 'test-session',topicId: 'test-topic',diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex 055fb1c9df6..82176554d4e 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -5,6 +5,7 @@ import { type SWRResponse } from 'swr';import { type StateCreator } from 'zustand/vanilla';import { useClientDataSWRWithSync } from '@/libs/swr';+import { messageKeys } from '@/libs/swr/keys';import { messageService } from '@/services/message';import { getChatStoreState } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';@@ -208,7 +209,7 @@ export const dataSlice: StateCreator<);return useClientDataSWRWithSync<UIChatMessage[]>(- shouldFetch ? ['CONVERSATION_FETCH_MESSAGES', context] : null,+ shouldFetch ? messageKeys.list(context) : null,() => messageService.getMessages(context),{diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsxnew file mode 100644index 00000000000..559517e4f26--- /dev/null+++ b/src/layout/GlobalProvider/CacheHydrationGate.tsx@@ -0,0 +1,52 @@+'use client';++import { type PropsWithChildren, useEffect, useState } from 'react';+import { useSyncExternalStore } from 'react';++import { cacheHydration } from '@/libs/swr/cacheHydration';+import { useCacheScope } from '@/libs/swr/useCacheScope';+import { useUserStore } from '@/store/user';+import { authSelectors } from '@/store/user/selectors';++/**+ * Max time to wait for the IndexedDB cache tier before rendering anyway, so a+ * slow / hung IndexedDB never blocks the app indefinitely.+ */+const HYDRATION_TIMEOUT = 1500;++/**+ * Boot hydration gate.+ *+ * Holds the routed app until the *current identity scope's* IndexedDB cache+ * tier has hydrated, so local-first data (messages, topics, β¦) is present in+ * the SWR cache synchronously by the time components mount β including on a+ * deep-link cold load. Before auth resolves the scope is `anon:*` (whose+ * IndexedDB tier is empty and resolves instantly), so this only ever waits the+ * few milliseconds an IndexedDB read takes for the signed-in scope.+ */+const CacheHydrationGate = ({ children }: PropsWithChildren) => {+ const scope = useCacheScope();+ const isAuthLoaded = useUserStore(authSelectors.isLoaded);++ const ready = useSyncExternalStore(+ cacheHydration.subscribe,+ () => cacheHydration.isReady(scope),+ () => true, // SSR: nothing to hydrate+ );++ // Safety valve: never block longer than HYDRATION_TIMEOUT.+ const [timedOut, setTimedOut] = useState(false);+ useEffect(() => {+ if (ready) return;+ setTimedOut(false);+ const timer = setTimeout(() => setTimedOut(true), HYDRATION_TIMEOUT);+ return () => clearTimeout(timer);+ }, [ready, scope]);++ // Only gate once auth has resolved (so we wait on the real scope, not anon).+ if (isAuthLoaded && !ready && !timedOut) return null;++ return <>{children}</>;+};++export default CacheHydrationGate;diff --git a/src/layout/GlobalProvider/Query.tsx b/src/layout/GlobalProvider/Query.tsxindex bd631c9da38..bee827b48d9 100644--- a/src/layout/GlobalProvider/Query.tsx+++ b/src/layout/GlobalProvider/Query.tsx@@ -2,10 +2,12 @@import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { type PropsWithChildren } from 'react';-import React, { useState } from 'react';-import { SWRConfig } from 'swr';+import React, { useEffect, useRef, useState } from 'react';+import { type Cache, SWRConfig } from 'swr';+import { cacheHydration } from '@/libs/swr/cacheHydration';import { swrCacheProvider } from '@/libs/swr/localStorageProvider';+import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';import { lambdaQuery, lambdaQueryClient } from '@/libs/trpc/client';import SWRMutateInitializer from './SWRMutateInitializer';@@ -17,11 +19,25 @@ const QueryProvider = ({ children }: PropsWithChildren) => {typeof lambdaQuery.Provider>['queryClient'];- // Use useState to ensure the provider is only created once- const [provider] = useState(swrCacheProvider);+ // The persistence namespace follows the live identity scope. `getCacheScope`+ // is read lazily on every load/save, so we don't recreate the provider (and+ // remount the tree) when the scope changes β instead we re-hydrate in place.+ // `cacheHydration.markReady` lets the boot gate wait for the IndexedDB tier.+ const [provider] = useState(() => swrCacheProvider(getCacheScope, cacheHydration.markReady));++ // Re-hydrate the cache from the new scope's namespace whenever the signed-in+ // user or active workspace changes (e.g. once async auth resolves), so data+ // never leaks across scopes and the correct local data is surfaced.+ const scope = useCacheScope();+ const lastScope = useRef(scope);+ useEffect(() => {+ if (lastScope.current === scope) return;+ lastScope.current = scope;+ provider.reloadScope?.();+ }, [scope, provider]);return (- <SWRConfig value={{ provider }}>+ <SWRConfig value={{ provider: provider as unknown as (cache: Readonly<Cache>) => Cache }}><SWRMutateInitializer><lambdaQuery.Provider client={lambdaQueryClient} queryClient={providerQueryClient}><QueryClientProvider client={queryClient}>{children}</QueryClientProvider>diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsxindex d7c5556ced4..854fdde5620 100644--- a/src/layout/SPAGlobalProvider/index.tsx+++ b/src/layout/SPAGlobalProvider/index.tsx@@ -12,6 +12,7 @@ import AgentMockDevtools from '@/features/AgentMockDevtools';import DevFeatureFlagPanel from '@/features/DevFeatureFlagPanel';import AuthProvider from '@/layout/AuthProvider';import AppTheme from '@/layout/GlobalProvider/AppTheme';+import CacheHydrationGate from '@/layout/GlobalProvider/CacheHydrationGate';import DynamicFavicon from '@/layout/GlobalProvider/DynamicFavicon';import { FaviconProvider } from '@/layout/GlobalProvider/FaviconProvider';import { GroupWizardProvider } from '@/layout/GlobalProvider/GroupWizardProvider';@@ -64,7 +65,9 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {<LazyMotion features={domMax}><TooltipGroup layoutAnimation={false}><StyleProvider speedy={import.meta.env.PROD}>- <LobeAnalyticsProviderWrapper>{children}</LobeAnalyticsProviderWrapper>+ <LobeAnalyticsProviderWrapper>+ <CacheHydrationGate>{children}</CacheHydrationGate>+ </LobeAnalyticsProviderWrapper></StyleProvider></TooltipGroup><Suspense>diff --git a/src/libs/swr/cacheHydration.test.ts b/src/libs/swr/cacheHydration.test.tsnew file mode 100644index 00000000000..3fbe2c78f71--- /dev/null+++ b/src/libs/swr/cacheHydration.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it, vi } from 'vitest';++import { cacheHydration } from './cacheHydration';+import { buildCacheScope } from './useCacheScope';++describe('cacheHydration', () => {+ it('tracks readiness per scope and notifies subscribers', () => {+ const scope = 'cacheHydration-test-1';+ const listener = vi.fn();+ const unsubscribe = cacheHydration.subscribe(listener);++ expect(cacheHydration.isReady(scope)).toBe(false);++ cacheHydration.markReady(scope);+ expect(cacheHydration.isReady(scope)).toBe(true);+ expect(listener).toHaveBeenCalledTimes(1);++ // marking again is a no-op (no extra emit)+ cacheHydration.markReady(scope);+ expect(listener).toHaveBeenCalledTimes(1);++ cacheHydration.reset(scope);+ expect(cacheHydration.isReady(scope)).toBe(false);+ expect(listener).toHaveBeenCalledTimes(2);++ unsubscribe();+ cacheHydration.markReady(scope);+ expect(listener).toHaveBeenCalledTimes(2); // unsubscribed+ });+});++describe('buildCacheScope', () => {+ it('falls back to anon/personal', () => {+ expect(buildCacheScope(undefined, undefined)).toBe('anon:personal');+ expect(buildCacheScope(null, null)).toBe('anon:personal');+ });++ it('combines user and workspace', () => {+ expect(buildCacheScope('u1', 'w1')).toBe('u1:w1');+ expect(buildCacheScope('u1', null)).toBe('u1:personal');+ });++ it('isolates different users and workspaces', () => {+ expect(buildCacheScope('u1', 'w1')).not.toBe(buildCacheScope('u2', 'w1'));+ expect(buildCacheScope('u1', 'w1')).not.toBe(buildCacheScope('u1', 'w2'));+ });+});diff --git a/src/libs/swr/cacheHydration.ts b/src/libs/swr/cacheHydration.tsnew file mode 100644index 00000000000..c829be5625a--- /dev/null+++ b/src/libs/swr/cacheHydration.ts@@ -0,0 +1,43 @@+/**+ * Cache hydration readiness store+ *+ * A tiny external store (consumable via `useSyncExternalStore`) that tracks+ * which identity scopes have finished hydrating their IndexedDB cache tier.+ *+ * The unified SWR cache provider marks a scope ready once its async IndexedDB+ * load completes; the boot `CacheHydrationGate` waits on this before mounting+ * the routed app, so local-first data (messages, topics, β¦) is present in the+ * cache synchronously by the time components mount β even on a deep-link cold+ * load. Decoupling through a module singleton lets the provider (high in the+ * tree) and the gate (around the routed children) communicate without prop or+ * context threading.+ */++const readyScopes = new Set<string>();+const listeners = new Set<() => void>();++const emit = () => {+ for (const listener of listeners) listener();+};++export const cacheHydration = {+ isReady: (scope: string): boolean => readyScopes.has(scope),++ /** Mark a scope's IndexedDB tier as hydrated. */+ markReady: (scope: string): void => {+ if (readyScopes.has(scope)) return;+ readyScopes.add(scope);+ emit();+ },++ /** Clear readiness for a scope (e.g. before re-hydrating on scope change). */+ reset: (scope: string): void => {+ if (!readyScopes.delete(scope)) return;+ emit();+ },++ subscribe: (listener: () => void): (() => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+};diff --git a/src/libs/swr/cacheProvider.integration.test.tsx b/src/libs/swr/cacheProvider.integration.test.tsxnew file mode 100644index 00000000000..50302b5e357--- /dev/null+++ b/src/libs/swr/cacheProvider.integration.test.tsx@@ -0,0 +1,89 @@+/**+ * @vitest-environment happy-dom+ *+ * End-to-end test of the local-first chain through real SWR:+ * fetch β provider write-through to IndexedDB β "reload" (fresh provider) β+ * synchronous local-first read before the network resolves.+ */+import { renderHook, waitFor } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+import useSWR, { type Cache, SWRConfig } from 'swr';+import { afterEach, describe, expect, it } from 'vitest';++import { localDataCache } from './localDataCache';+import { createCacheProvider } from './localStorageProvider';++const SCOPE = 'integration-scope';++const makeProvider = () => {+ let resolveHydrated: () => void;+ const hydrated = new Promise<void>((r) => {+ resolveHydrated = r;+ });+ const provider = createCacheProvider({+ debounceMs: 5,+ getScope: () => SCOPE,+ idbPatterns: ['MSGS'],+ localPatterns: [],+ onScopeHydrated: () => resolveHydrated(),+ });+ return { hydrated, provider };+};++const wrapper =+ (provider: ReturnType<typeof createCacheProvider>) =>+ ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { provider: provider as unknown as (c: Readonly<Cache>) => Cache } },+ children,+ );++describe('local-first cache chain (SWR + tiered provider + IndexedDB)', () => {+ afterEach(async () => {+ await localDataCache.clearScope(SCOPE);+ });++ it('persists fetched data to IndexedDB and serves it locally on reload', async () => {+ const key = ['MSGS', 'topic-1'];+ const serverV1 = [{ id: 'm1', text: 'first load' }];++ // --- session 1: fetch, which the provider writes through to IndexedDB ---+ const { provider: p1 } = makeProvider();+ const fetcher1 = () => Promise.resolve(serverV1);+ const r1 = renderHook(() => useSWR(key, fetcher1), { wrapper: wrapper(p1) });++ await waitFor(() => expect(r1.result.current.data).toEqual(serverV1));+ // write-through to the IndexedDB tier (debounced)+ await waitFor(async () => {+ const rows = await localDataCache.entriesByScope(SCOPE);+ expect(rows.length).toBeGreaterThan(0);+ });+ r1.unmount();++ // --- session 2 ("reload"): fresh provider hydrates IndexedDB ------------+ // Model the boot gate: create the cache and await IndexedDB hydration+ // *before* the consuming component mounts, then hand SWR that hydrated map.+ const { hydrated: hydrated2, provider: p2 } = makeProvider();+ const hydratedMap = p2();+ await hydrated2;+ const stableProvider = (() => hydratedMap) as typeof p2;++ // a slow network so the local snapshot must win the first paint+ let resolveSlow: (v: unknown) => void;+ const slow = new Promise((r) => {+ resolveSlow = r;+ });+ const fetcher2 = () => slow;+ const r2 = renderHook(() => useSWR(key, fetcher2), { wrapper: wrapper(stableProvider) });++ // local-first: data is available synchronously from the hydrated cache,+ // before the slow fetch resolves+ expect(r2.result.current.data).toEqual(serverV1);++ // then the fresh server value still flows through+ const serverV2 = [{ id: 'm1', text: 'revalidated' }];+ resolveSlow!(serverV2);+ await waitFor(() => expect(r2.result.current.data).toEqual(serverV2));+ });+});diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsnew file mode 100644index 00000000000..8e219c68bc2--- /dev/null+++ b/src/libs/swr/keys.ts@@ -0,0 +1,109 @@+/**+ * Central SWR key registry+ *+ * Single source of truth for SWR cache keys, organized by business domain and+ * named with one convention: the first array element is `'<domain>:<resource>'`+ * (lowerCamel resource), followed by parameters.+ *+ * Benefits:+ * - Consistent, discoverable naming (`swrKeys.topic.list(...)`).+ * - The `domain:` prefix lets the tiered cache provider route persistence by+ * domain (see `localStorageProvider.ts`) and lets callers refresh a whole+ * domain at once via `matchDomain('topic:')`.+ *+ * Each factory also exposes `.root` (the namespace string) for `mutate`+ * matchers that compare `key[0]`.+ *+ * Document / page / notebook / agent-document keys are defined in+ * `@/services/document/swrKeys` (already a factory, widely imported) and+ * re-exported here so the whole set is reachable from one place.+ */+import {+ agentDocumentSWRKeys,+ documentSWRKeys,+ notebookSWRKeys,+} from '@/services/document/swrKeys';++type KeyFactory<A extends unknown[]> = ((...args: A) => readonly unknown[]) & { root: string };++/** Define a key factory carrying its namespace root (for `mutate` matchers). */+const def = <A extends unknown[]>(+ root: string,+ build: (...args: A) => readonly unknown[],+): KeyFactory<A> => Object.assign(build, { root });++// ---- message ------------------------------------------------------------+export const messageKeys = {+ /** Conversation store messages, keyed by request context. */+ list: def('message:list', (context: unknown) => ['message:list', context]),+ /** Legacy chat store messages, keyed by request context. */+ listLegacy: def('message:listLegacy', (context: unknown) => ['message:listLegacy', context]),+};++// ---- topic --------------------------------------------------------------+export const topicKeys = {+ agentView: def('topic:agentView', (containerKey: string, opts: Record<string, unknown>) => [+ 'topic:agentView',+ containerKey,+ opts,+ ]),+ list: def('topic:list', (containerKey: string, opts: Record<string, unknown>) => [+ 'topic:list',+ containerKey,+ opts,+ ]),+ search: def('topic:search', (keywords: string, agentId?: string, groupId?: string) => [+ 'topic:search',+ keywords,+ agentId,+ groupId,+ ]),+};++// ---- agent --------------------------------------------------------------+export const agentKeys = {+ /** Sidebar agent list. */+ list: def('agent:list', (isLogin: boolean) => ['agent:list', isLogin]),+};++// ---- group --------------------------------------------------------------+export const groupKeys = {+ detail: def('group:detail', (groupId: string) => ['group:detail', groupId]),+};++// ---- task ---------------------------------------------------------------+export const taskKeys = {+ detail: def('task:detail', (taskId: string) => ['task:detail', taskId]),+ groupList: def('task:groupList', (agentKey: string | undefined) => ['task:groupList', agentKey]),+ list: def('task:list', (agentKey: string | undefined) => ['task:list', agentKey]),+};++// ---- brief --------------------------------------------------------------+export const briefKeys = {+ list: def('brief:list', (isLogin: boolean) => ['brief:list', isLogin]),+};++/**+ * Build a `mutate` matcher that selects every key in a `domain:` namespace.+ *+ * @example mutate(matchDomain('topic:')) // refresh all topic caches+ */+export const matchDomain =+ (prefix: string) =>+ (key: unknown): boolean =>+ Array.isArray(key) && typeof key[0] === 'string' && key[0].startsWith(prefix);++/**+ * Aggregate registry β one entry point for every domain's keys.+ */+export const swrKeys = {+ agent: agentKeys,+ agentDocument: agentDocumentSWRKeys,+ brief: briefKeys,+ document: documentSWRKeys,+ group: groupKeys,+ message: messageKeys,+ notebook: notebookSWRKeys,+ task: taskKeys,+ topic: topicKeys,+};diff --git a/src/libs/swr/localDataCache.test.ts b/src/libs/swr/localDataCache.test.tsnew file mode 100644index 00000000000..513829d168e--- /dev/null+++ b/src/libs/swr/localDataCache.test.ts@@ -0,0 +1,76 @@+import { beforeEach, describe, expect, it } from 'vitest';++import { buildLocalDataKey, localDataCache } from './localDataCache';++describe('buildLocalDataKey', () => {+ it('joins scope and string key', () => {+ expect(buildLocalDataKey('user-1:personal', 'fetchMessages')).toBe(+ 'user-1:personal::fetchMessages',+ );+ });++ it('serializes array/object keys', () => {+ expect(buildLocalDataKey('u:w', ['message:list', { topicId: 't1' }])).toBe(+ 'u:w::["message:list",{"topicId":"t1"}]',+ );+ });++ it('partitions identical SWR keys by scope', () => {+ const key = ['message:list', { topicId: 't1' }];+ expect(buildLocalDataKey('userA:personal', key)).not.toBe(+ buildLocalDataKey('userB:personal', key),+ );+ });+});++describe('localDataCache', () => {+ const scope = 'user-test:personal';++ beforeEach(async () => {+ await localDataCache.clearScope(scope);+ });++ it('stores and retrieves data', async () => {+ const key = buildLocalDataKey(scope, ['msgs', 't1']);+ await localDataCache.set(key, [{ content: 'hello', id: 'm1' }]);++ const got = await localDataCache.get<{ content: string; id: string }[]>(key);+ expect(got).toEqual([{ content: 'hello', id: 'm1' }]);+ });++ it('returns undefined for a missing key', async () => {+ const got = await localDataCache.get(buildLocalDataKey(scope, 'missing'));+ expect(got).toBeUndefined();+ });++ it('overwrites on repeated set (last write wins)', async () => {+ const key = buildLocalDataKey(scope, 'k');+ await localDataCache.set(key, { v: 1 });+ await localDataCache.set(key, { v: 2 });++ expect(await localDataCache.get(key)).toEqual({ v: 2 });+ });++ it('deletes a key', async () => {+ const key = buildLocalDataKey(scope, 'k');+ await localDataCache.set(key, { v: 1 });+ await localDataCache.delete(key);++ expect(await localDataCache.get(key)).toBeUndefined();+ });++ it('clearScope removes only the given scope', async () => {+ const otherScope = 'user-other:personal';+ const keyA = buildLocalDataKey(scope, 'a');+ const keyB = buildLocalDataKey(otherScope, 'b');+ await localDataCache.set(keyA, 1);+ await localDataCache.set(keyB, 2);++ await localDataCache.clearScope(scope);++ expect(await localDataCache.get(keyA)).toBeUndefined();+ expect(await localDataCache.get(keyB)).toBe(2);++ await localDataCache.clearScope(otherScope);+ });+});diff --git a/src/libs/swr/localDataCache.ts b/src/libs/swr/localDataCache.tsnew file mode 100644index 00000000000..f2a94c9e39d--- /dev/null+++ b/src/libs/swr/localDataCache.ts@@ -0,0 +1,134 @@+/**+ * IndexedDB local-first data cache+ *+ * A scope-partitioned key/value store used as the IndexedDB *tier* of the+ * unified SWR cache provider (see `localStorageProvider.ts`). It backs large,+ * important business entities (messages, topics, tasks, documents, agents)+ * whose history blows past the ~5MB localStorage origin quota.+ *+ * Why IndexedDB rather than the localStorage SWR provider for these:+ * - localStorage has a ~5MB per-origin quota; large entity data exceeds it and+ * a quota error there wipes the *entire* SWR cache. IndexedDB offers+ * hundreds of MB and stores each entry as an independent row.+ *+ * The provider reads from this tier at boot (async) and writes through on every+ * cache update β consumers never touch it directly.+ *+ * Every key is partitioned by identity scope (`${userId}:${workspaceId}`) so+ * different users / workspaces sharing a browser origin never collide.+ */+import type { Table } from 'dexie';++interface CacheRow {+ data: unknown;+ /** Composite key: `${scope}::${serializedSWRKey}` */+ key: string;+ updatedAt: number;+ /** App cache version; mismatching rows are ignored on load. */+ version?: string;+}++export interface ScopeEntry {+ data: unknown;+ /** The SWR key (scope prefix stripped). */+ key: string;+ updatedAt: number;+ version?: string;+}++const DB_NAME = 'lobehub-local-data';+const STORE_NAME = 'cache';++const isAvailable = () => typeof indexedDB !== 'undefined';++// Lazily-created singleton Dexie instance. Kept out of module scope so SSR+// imports never touch IndexedDB.+let dbPromise: Promise<Table<CacheRow, string>> | null = null;++const getTable = async () => {+ if (!isAvailable()) return null;+ if (!dbPromise) {+ dbPromise = (async () => {+ const { default: Dexie } = await import('dexie');+ const db = new Dexie(DB_NAME);+ db.version(1).stores({ [STORE_NAME]: 'key, updatedAt' });+ return db.table<CacheRow, string>(STORE_NAME);+ })();+ }+ return dbPromise;+};++const scopePrefix = (scope: string) => `${scope}::`;++/**+ * Build the composite IndexedDB key from the identity scope and the SWR key.+ */+export const buildLocalDataKey = (scope: string, swrKey: unknown): string =>+ `${scopePrefix(scope)}${typeof swrKey === 'string' ? swrKey : JSON.stringify(swrKey)}`;++export const localDataCache = {+ /**+ * Remove every entry belonging to a scope. Useful on logout / account switch.+ */+ clearScope: async (scope: string): Promise<void> => {+ try {+ const table = await getTable();+ if (!table) return;+ await table.where('key').startsWith(scopePrefix(scope)).delete();+ } catch {+ // best-effort; ignore+ }+ },++ delete: async (key: string): Promise<void> => {+ try {+ const table = await getTable();+ if (!table) return;+ await table.delete(key);+ } catch {+ // best-effort; ignore+ }+ },++ /**+ * Return every entry belonging to a scope, with the scope prefix stripped+ * back to the original SWR key. Used to hydrate the in-memory SWR cache.+ */+ entriesByScope: async (scope: string): Promise<ScopeEntry[]> => {+ try {+ const table = await getTable();+ if (!table) return [];+ const prefix = scopePrefix(scope);+ const rows = await table.where('key').startsWith(prefix).toArray();+ return rows.map((row) => ({+ data: row.data,+ key: row.key.slice(prefix.length),+ updatedAt: row.updatedAt,+ version: row.version,+ }));+ } catch {+ return [];+ }+ },++ get: async <T>(key: string): Promise<T | undefined> => {+ try {+ const table = await getTable();+ if (!table) return undefined;+ const row = await table.get(key);+ return row?.data as T | undefined;+ } catch {+ return undefined;+ }+ },++ set: async (key: string, data: unknown, version?: string): Promise<void> => {+ try {+ const table = await getTable();+ if (!table) return;+ await table.put({ data, key, updatedAt: Date.now(), version });+ } catch {+ // best-effort; ignore+ }+ },+};diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.tsindex 124eca10ecf..69497362428 100644--- a/src/libs/swr/localStorageProvider.test.ts+++ b/src/libs/swr/localStorageProvider.test.ts@@ -3,292 +3,205 @@*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { clearSWRCache, createLocalStorageProvider } from './localStorageProvider';+import { localDataCache } from './localDataCache';+import {+ CACHE_TIERS,+ clearSWRCache,+ createCacheProvider,+ getScopedCacheKey,+} from './localStorageProvider';++/** Poll until `fn` returns truthy (for async IndexedDB tier assertions). */+const until = async (fn: () => boolean | Promise<boolean>, timeout = 1000): Promise<void> => {+ const start = Date.now();+ while (Date.now() - start < timeout) {+ if (await fn()) return;+ await new Promise((r) => setTimeout(r, 5));+ }+ throw new Error('until: timed out');+};++/** Build a provider whose async IndexedDB hydration we can await. */+const buildProvider = (+ scope: { value: string },+ extra: Partial<Parameters<typeof createCacheProvider>[0]> = {},+) => {+ let resolveHydrated: () => void;+ const hydrated = new Promise<void>((r) => {+ resolveHydrated = r;+ });+ const provider = createCacheProvider({+ debounceMs: 5,+ getScope: () => scope.value,+ idbPatterns: ['MSGS', 'TOPIC'],+ localPatterns: ['recents'],+ onScopeHydrated: () => resolveHydrated(),+ ...extra,+ });+ return { hydrated, provider };+};-describe('createLocalStorageProvider', () => {+describe('createCacheProvider β tiering', () => {beforeEach(() => {localStorage.clear();- vi.useFakeTimers();});- afterEach(() => {- vi.useRealTimers();+ afterEach(async () => {vi.restoreAllMocks();+ await localDataCache.clearScope('s1');+ await localDataCache.clearScope('s2');});- describe('basic functionality', () => {- it('should return a function that creates a Map', () => {- const provider = createLocalStorageProvider();- const map = provider();-- expect(map).toBeInstanceOf(Map);- });-- it('should store and retrieve values', () => {- const provider = createLocalStorageProvider({- cacheablePatterns: ['test-key'],- });- const map = provider();-- map.set('test-key', { value: 'test' });-- expect(map.get('test-key')).toEqual({ value: 'test' });- });-- it('should delete values', () => {- const provider = createLocalStorageProvider({- cacheablePatterns: ['test-key'],- });- const map = provider();-- map.set('test-key', { value: 'test' });- map.delete('test-key');-- expect(map.has('test-key')).toBe(false);- });+ it('getScopedCacheKey namespaces by scope', () => {+ expect(getScopedCacheKey('u1:personal')).toBe('lobechat-swr-cache:u1:personal');+ expect(getScopedCacheKey('anon:personal')).not.toBe(getScopedCacheKey('u1:personal'));});- describe('whitelist filtering', () => {- it('should only persist keys matching cacheablePatterns', () => {- const provider = createLocalStorageProvider({- cacheablePatterns: ['fetchSessions', 'fetchAgentList'],- });- const map = provider();+ it('routes local-tier keys to scoped localStorage only', async () => {+ const scope = { value: 's1' };+ const { provider } = buildProvider(scope);+ const map = provider();- // Set both cacheable and non-cacheable keys- map.set('fetchSessions', { sessions: [] });- map.set('fetchAgentList', { agents: [] });- map.set('fetchMessages', { messages: [] }); // Not in whitelist+ map.set('recents', { items: [1] });+ map.set('MSGS:t1', { items: [2] }); // idb tier+ map.set('random', { x: 1 }); // memory only- // Trigger save via beforeunload event- window.dispatchEvent(new Event('beforeunload'));-- const stored = localStorage.getItem('lobechat-swr-cache');- expect(stored).not.toBeNull();-- const entries = JSON.parse(stored!);- const keys = entries.map(([key]: [string, unknown]) => key);-- expect(keys).toContain('fetchSessions');- expect(keys).toContain('fetchAgentList');- expect(keys).not.toContain('fetchMessages');- });+ await until(() => localStorage.getItem(getScopedCacheKey('s1')) !== null);- it('should match array keys by first element', () => {- const provider = createLocalStorageProvider({- cacheablePatterns: ['fetchSessions'],- });- const map = provider();-- // SWR often uses array keys like ['fetchSessions', userId]- const arrayKey = JSON.stringify(['fetchSessions', 'user-123']);- map.set(arrayKey, { data: 'test' });-- // Trigger save via beforeunload event- window.dispatchEvent(new Event('beforeunload'));-- const stored = localStorage.getItem('lobechat-swr-cache');- const entries = JSON.parse(stored!);-- expect(entries.length).toBe(1);- });+ const stored = JSON.parse(localStorage.getItem(getScopedCacheKey('s1'))!);+ const keys = stored.map(([k]: [string]) => k);+ expect(keys).toContain('recents');+ expect(keys).not.toContain('MSGS:t1');+ expect(keys).not.toContain('random');});- describe('TTL expiration', () => {- it('should load non-expired entries from localStorage', () => {- const now = Date.now();- const validEntry = {- data: { valid: true },- timestamp: now - 1000, // 1 second ago- version: '1.0.0',- };-- localStorage.setItem(- 'lobechat-swr-cache',- JSON.stringify([['valid-key', validEntry]]),- );+ it('routes idb-tier keys to IndexedDB and reloads them on a fresh provider', async () => {+ const scope = { value: 's1' };+ const { provider } = buildProvider(scope);+ const map = provider();- const provider = createLocalStorageProvider({- ttl: 60 * 1000, // 1 minute- version: '1.0.0',- });- const map = provider();-- expect(map.get('valid-key')).toEqual({ valid: true });- });+ map.set('MSGS:t1', { items: ['hello'] });+ await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);- it('should not load expired entries from localStorage', () => {- const now = Date.now();- const expiredEntry = {- data: { expired: true },- timestamp: now - 2 * 60 * 60 * 1000, // 2 hours ago- version: '1.0.0',- };+ // a brand-new provider for the same scope should re-hydrate the idb entry+ const { hydrated: hydrated2, provider: provider2 } = buildProvider(scope);+ const map2 = provider2();+ await hydrated2;- localStorage.setItem(- 'lobechat-swr-cache',- JSON.stringify([['expired-key', expiredEntry]]),- );-- const provider = createLocalStorageProvider({- ttl: 60 * 60 * 1000, // 1 hour- version: '1.0.0',- });- const map = provider();-- expect(map.has('expired-key')).toBe(false);- });+ expect(map2.get('MSGS:t1')).toEqual({ items: ['hello'] });});- describe('version control', () => {- it('should not load entries with different version', () => {- const oldVersionEntry = {- data: { old: true },- timestamp: Date.now(),- version: '0.9.0',- };-- localStorage.setItem(- 'lobechat-swr-cache',- JSON.stringify([['old-key', oldVersionEntry]]),- );-- const provider = createLocalStorageProvider({- version: '1.0.0',- });- const map = provider();-- expect(map.has('old-key')).toBe(false);+ it('idb tier wins when a key matches both pattern sets', async () => {+ const scope = { value: 's1' };+ const { provider } = buildProvider(scope, {+ idbPatterns: ['shared'],+ localPatterns: ['shared'],});+ const map = provider();+ map.set('shared-key', { v: 1 });- it('should load entries with matching version', () => {- const currentVersionEntry = {- data: { current: true },- timestamp: Date.now(),- version: '1.0.0',- };-- localStorage.setItem(- 'lobechat-swr-cache',- JSON.stringify([['current-key', currentVersionEntry]]),- );-- const provider = createLocalStorageProvider({- version: '1.0.0',- });- const map = provider();-- expect(map.get('current-key')).toEqual({ current: true });- });+ await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);+ // not written to the localStorage tier+ expect(localStorage.getItem(getScopedCacheKey('s1'))).toBeNull();});- describe('capacity limits', () => {- it('should respect maxEntries limit', () => {- const provider = createLocalStorageProvider({- cacheablePatterns: ['item'],- maxEntries: 3,- });- const map = provider();-- // Add more entries than the limit- for (let i = 0; i < 5; i++) {- map.set(`item-${i}`, { index: i });- }-- vi.advanceTimersByTime(2500);-- const stored = localStorage.getItem('lobechat-swr-cache');- const entries = JSON.parse(stored!);-- expect(entries.length).toBeLessThanOrEqual(3);- });+ it('does not let two scopes overwrite each other (both tiers)', async () => {+ const scope = { value: 's1' };+ const { provider } = buildProvider(scope);+ const map = provider();+ map.set('recents', { owner: 'A' });+ map.set('MSGS:t1', { owner: 'A' });+ await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);+ await until(() => localStorage.getItem(getScopedCacheKey('s1')) !== null);++ // switch scope and write different data+ scope.value = 's2';+ provider.reloadScope!();+ map.set('recents', { owner: 'B' });+ map.set('MSGS:t1', { owner: 'B' });+ await until(async () => (await localDataCache.entriesByScope('s2')).length > 0);+ await until(() => localStorage.getItem(getScopedCacheKey('s2')) !== null);++ const a = await localDataCache.entriesByScope('s1');+ const b = await localDataCache.entriesByScope('s2');+ expect(a.find((e) => e.key === 'MSGS:t1')?.data).toEqual({ owner: 'A' });+ expect(b.find((e) => e.key === 'MSGS:t1')?.data).toEqual({ owner: 'B' });});- describe('debounced saving', () => {- it('should debounce multiple set operations', () => {- const provider = createLocalStorageProvider({- cacheablePatterns: ['key'],- });- const map = provider();-- // Multiple rapid sets- map.set('key-1', { v: 1 });- map.set('key-2', { v: 2 });- map.set('key-3', { v: 3 });-- // Before debounce timeout, nothing should be saved- expect(localStorage.getItem('lobechat-swr-cache')).toBeNull();-- // After debounce timeout- vi.advanceTimersByTime(2500);-- expect(localStorage.getItem('lobechat-swr-cache')).not.toBeNull();- });+ it('reloadScope re-hydrates both tiers from the new scope', async () => {+ // seed s2 with idb + local data via a throwaway provider+ const seedScope = { value: 's2' };+ const { provider: seed } = buildProvider(seedScope);+ const seedMap = seed();+ seedMap.set('MSGS:tX', { from: 's2' });+ seedMap.set('recents', { from: 's2' });+ await until(async () => (await localDataCache.entriesByScope('s2')).length > 0);+ await until(() => localStorage.getItem(getScopedCacheKey('s2')) !== null);++ // a provider that starts on s1, then switches to s2+ const scope = { value: 's1' };+ const { provider } = buildProvider(scope);+ const map = provider();+ map.set('MSGS:tA', { from: 's1' });+ map.set('recents', { from: 's1' });++ scope.value = 's2';+ provider.reloadScope!();++ // local tier is synchronous on reload+ expect(map.get('recents')).toEqual({ from: 's2' });+ // s1's idb entry dropped from memory+ expect(map.has('MSGS:tA')).toBe(false);+ // s2's idb entry hydrated asynchronously+ await until(() => map.get('MSGS:tX') !== undefined);+ expect(map.get('MSGS:tX')).toEqual({ from: 's2' });});- describe('error handling', () => {- it('should handle corrupted localStorage data', () => {- localStorage.setItem('lobechat-swr-cache', 'invalid-json');-- const onError = vi.fn();- const provider = createLocalStorageProvider({ onError });- const map = provider();-- expect(map.size).toBe(0);- expect(onError).toHaveBeenCalled();- });-- it('should handle QuotaExceededError gracefully', () => {- const provider = createLocalStorageProvider({- cacheablePatterns: ['key'],- });- const map = provider();-- // Mock localStorage.setItem to throw QuotaExceededError- const quotaError = new DOMException('Quota exceeded', 'QuotaExceededError');- vi.spyOn(localStorage, 'setItem').mockImplementation(() => {- throw quotaError;- });-- map.set('key', { data: 'test' });- vi.advanceTimersByTime(2500);+ it('drops local-tier entries past TTL / version on load', async () => {+ const key = getScopedCacheKey('s1');+ localStorage.setItem(+ key,+ JSON.stringify([+ ['recents', { data: { ok: true }, timestamp: Date.now(), version: '1.0.0' }],+ ['recents-old', { data: { ok: false }, timestamp: Date.now() - 1e9, version: '1.0.0' }],+ ['recents-v', { data: { ok: false }, timestamp: Date.now(), version: '0.0.1' }],+ ]),+ );+ const scope = { value: 's1' };+ const { provider } = buildProvider(scope, { ttl: 60_000, version: '1.0.0' });+ const map = provider();++ expect(map.get('recents')).toEqual({ ok: true });+ expect(map.has('recents-old')).toBe(false);+ expect(map.has('recents-v')).toBe(false);+ });- // Should not throw- expect(true).toBe(true);+ it('handles localStorage QuotaExceededError without throwing', async () => {+ const scope = { value: 's1' };+ const { provider } = buildProvider(scope);+ const map = provider();+ vi.spyOn(localStorage, 'setItem').mockImplementation(() => {+ throw new DOMException('Quota exceeded', 'QuotaExceededError');});+ expect(() => {+ map.set('recents', { x: 1 });+ }).not.toThrow();+ await new Promise((r) => setTimeout(r, 20));});- describe('SSR compatibility', () => {- it('should return empty Map when window is undefined', () => {- // This test verifies the SSR check in the implementation- // The actual SSR scenario is tested implicitly by the guard clause- const provider = createLocalStorageProvider();- const map = provider();-- expect(map).toBeInstanceOf(Map);- });+ it('exposes the central tier config keyed by domain prefix', () => {+ expect(CACHE_TIERS.idb).toContain('message:');+ expect(CACHE_TIERS.idb).toContain('topic:');+ expect(CACHE_TIERS.local).toContain('fetchRecents');});});describe('clearSWRCache', () => {- beforeEach(() => {- localStorage.clear();- });-- it('should clear the cache from localStorage', () => {- localStorage.setItem('lobechat-swr-cache', JSON.stringify([['key', { data: 'test' }]]));+ beforeEach(() => localStorage.clear());+ it('removes the given cache key', () => {+ localStorage.setItem('lobechat-swr-cache', '[]');clearSWRCache();-expect(localStorage.getItem('lobechat-swr-cache')).toBeNull();});-- it('should use custom cache key if provided', () => {- const customKey = 'custom-cache-key';- localStorage.setItem(customKey, JSON.stringify([['key', { data: 'test' }]]));-- clearSWRCache(customKey);-- expect(localStorage.getItem(customKey)).toBeNull();- });});diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsindex 44e090d8ad2..fdf9e61c896 100644--- a/src/libs/swr/localStorageProvider.ts+++ b/src/libs/swr/localStorageProvider.ts@@ -1,16 +1,29 @@/**- * SWR localStorage Cache Provider+ * Unified tiered SWR cache provider*- * Provides localStorage persistence for selected SWR requests.- * Only keys matching the whitelist patterns will be cached to localStorage.+ * One in-memory Map backs SWR (the cache contract stays synchronous). Behind+ * it, writes are transparently routed to a persistence *tier* chosen centrally+ * by the SWR key β consumers never opt in per call:+ *+ * - `idb` β IndexedDB (see `localDataCache.ts`): large / important business+ * entities (messages, topics, tasks, documents, agents). Loaded+ * asynchronously at boot, stored as independent rows β no 5MB cap.+ * - `local` β localStorage: small, frequently-changing list shells (recents).+ * Loaded synchronously for instant first paint.+ * - none β memory only.+ *+ * Everything is partitioned by identity scope (`${userId}:${workspaceId}`) so+ * users / workspaces sharing a browser origin never collide; `reloadScope()`+ * re-hydrates in place when the scope changes (e.g. once auth resolves).** @example* ```tsx- * <SWRConfig value={{ provider: createLocalStorageProvider() }}>+ * <SWRConfig value={{ provider: swrCacheProvider(getCacheScope) }}>* <App />* </SWRConfig>* ```*/+import { buildLocalDataKey, localDataCache } from './localDataCache';interface CacheEntry<T = unknown> {/** Cached data */@@ -21,35 +34,43 @@ interface CacheEntry<T = unknown> {version: string;}-export interface LocalStorageCacheOptions {- /** Allowed SWR key patterns (whitelist) */- cacheablePatterns?: string[];- /** localStorage key name, defaults to 'lobechat-swr-cache' */- cacheKey?: string;- /** Maximum cache entries, defaults to 50 */- maxEntries?: number;+export type CacheTier = 'idb' | 'local';++export interface CacheProviderOptions {+ /** Debounce (ms) before flushing writes to either tier, defaults to 2000. */+ debounceMs?: number;+ /** Resolver for the active identity scope (`${userId}:${workspaceId}`). */+ getScope?: () => string;+ /** SWR key patterns persisted to the IndexedDB tier. */+ idbPatterns?: string[];+ /** SWR key patterns persisted to the localStorage tier. */+ localPatterns?: string[];+ /** Max localStorage-tier entries, defaults to 50. */+ maxLocalEntries?: number;/** Error callback */onError?: (error: Error) => void;- /** Cache TTL in milliseconds, defaults to 24 hours */+ /** Called after a scope's IndexedDB tier finishes hydrating. */+ onScopeHydrated?: (scope: string) => void;+ /** Cache TTL in milliseconds, defaults to 24 hours. Applies to both tiers. */ttl?: number;- /** App version, cache is cleared when version changes */+ /** App version; entries from another version are ignored on load. */version?: string;}/**- * Default cacheable SWR key patterns- * Only requests matching these patterns will be persisted+ * SWR cache provider function with an in-place scope reloader.*/-const DEFAULT_CACHEABLE_PATTERNS: string[] = [- // Add patterns as needed-];+export type ScopedSWRProvider = (() => Map<string, unknown>) & {+ /**+ * Flush pending writes, then re-hydrate the in-memory cache from the *current*+ * scope's namespaces (localStorage synchronously, IndexedDB asynchronously).+ * No-op until SWR has created the provider's Map.+ */+ reloadScope?: () => void;+};-/**- * Check if localStorage is available- */const isLocalStorageAvailable = (): boolean => {if (typeof window === 'undefined') return false;-try {const testKey = '__swr_cache_test__';localStorage.setItem(testKey, 'test');@@ -61,199 +82,266 @@ const isLocalStorageAvailable = (): boolean => {};/**- * Check if key matches whitelist patterns- *- * SWR keys can be:- * - String: 'fetchSessions'- * - Serialized array: '["fetchSessions","user-123"]'- *- * We check if the key string contains any whitelist pattern+ * Check whether a (string) SWR key contains any of the patterns. SWR keys are+ * either a plain string or a serialized array like `'["fetchSessions","u1"]'`.*/-const matchesCacheablePattern = (key: string, patterns: string[]): boolean => {- if (patterns.length === 0) return false;- return patterns.some((pattern) => key.includes(pattern));-};+const matchesPattern = (key: string, patterns: string[]): boolean =>+ patterns.some((pattern) => key.includes(pattern));/**- * Create localStorage cache provider+ * Build the scoped localStorage cache key (localStorage tier namespace).*- * Features:- * - Whitelist mechanism: only cache specified keys- * - TTL expiration: auto-cleanup expired data- * - Version control: auto-cleanup when app version changes- * - Capacity limit: prevent exceeding localStorage limit- * - SSR compatible: returns empty Map on server- * - Error recovery: fallback to memory cache on error+ * Partitioned per identity scope so different users / workspaces sharing the+ * same browser origin never read or overwrite each other's cached data.*/-export function createLocalStorageProvider(options: LocalStorageCacheOptions = {}) {+export const getScopedCacheKey = (scope: string) => `lobechat-swr-cache:${scope}`;++/**+ * Create a unified tiered cache provider.+ */+export function createCacheProvider(options: CacheProviderOptions = {}): ScopedSWRProvider {const {- cacheKey = 'lobechat-swr-cache',+ debounceMs = 2000,+ getScope = () => 'default',+ idbPatterns = [],+ localPatterns = [],ttl = 24 * 60 * 60 * 1000, // 24 hours- maxEntries = 50,+ maxLocalEntries = 50,version = '1.0.0',- cacheablePatterns = DEFAULT_CACHEABLE_PATTERNS,onError = (error) => console.error('[SWR Cache]', error),+ onScopeHydrated,} = options;- // Return memory cache when SSR or localStorage unavailable+ // SSR / no storage β plain memory cache, no persistence. Still signal+ // hydration so the boot gate never blocks.if (!isLocalStorageAvailable()) {- return () => new Map();+ return () => {+ onScopeHydrated?.(getScope());+ return new Map();+ };}- return (): Map<string, unknown> => {- /**- * Load cache from localStorage- */- const loadCache = (): Map<string, unknown> => {- try {- const stored = localStorage.getItem(cacheKey);- if (!stored) {- return new Map();- }+ /** Route a key to its persistence tier (idb wins over local). */+ const tierOf = (key: string): CacheTier | null => {+ if (matchesPattern(key, idbPatterns)) return 'idb';+ if (matchesPattern(key, localPatterns)) return 'local';+ return null;+ };- const entries: [string, CacheEntry][] = JSON.parse(stored);- const now = Date.now();+ let cacheMapInstance: TieredCacheMap | null = null;- // Filter: expired data, version mismatch- const validEntries = entries- .filter(([, entry]) => {- const isExpired = now - entry.timestamp > ttl;- const isValidVersion = entry.version === version;- return !isExpired && isValidVersion;- })- .map(([key, entry]) => [key, entry.data] as [string, unknown]);+ // --- localStorage tier (synchronous snapshot) ----------------------------+ let localTimer: ReturnType<typeof setTimeout> | null = null;- return new Map(validEntries);- } catch (error) {+ const loadLocal = (): Map<string, unknown> => {+ try {+ const stored = localStorage.getItem(getScopedCacheKey(getScope()));+ if (!stored) return new Map();+ const entries: [string, CacheEntry][] = JSON.parse(stored);+ const now = Date.now();+ return new Map(+ entries+ .filter(([, e]) => now - e.timestamp <= ttl && e.version === version)+ .map(([key, e]) => [key, e.data] as [string, unknown]),+ );+ } catch (error) {+ onError(error as Error);+ return new Map();+ }+ };++ const saveLocal = () => {+ if (!cacheMapInstance) return;+ const key = getScopedCacheKey(getScope());+ try {+ const entries = Array.from(cacheMapInstance.entries())+ .filter(([k]) => matchesPattern(k, localPatterns))+ .slice(-maxLocalEntries)+ .map(([k, data]) => [k, { data, timestamp: Date.now(), version } as CacheEntry]);++ const serialized = JSON.stringify(entries);+ const sizeInMB = new Blob([serialized]).size / (1024 * 1024);+ if (sizeInMB > 4) {+ // Drop oldest half rather than wiping everything.+ localStorage.setItem(key, JSON.stringify(entries.slice(-Math.floor(maxLocalEntries / 2))));+ console.warn(`[SWR Cache] localStorage tier too large (${sizeInMB.toFixed(2)}MB), trimmed`);+ } else {+ localStorage.setItem(key, serialized);+ }+ } catch (error) {+ if ((error as DOMException).name === 'QuotaExceededError') {+ try {+ localStorage.removeItem(key);+ } catch {+ // ignore+ }+ console.error('[SWR Cache] Quota exceeded, localStorage tier cleared');+ } else {onError(error as Error);- return new Map();}- };+ }+ };- const initialData = loadCache();+ const debouncedSaveLocal = () => {+ if (localTimer) clearTimeout(localTimer);+ localTimer = setTimeout(saveLocal, debounceMs);+ };- // Debounced save variables (outside class to avoid initialization order issues)- let saveTimer: ReturnType<typeof setTimeout> | null = null;- let cacheMapInstance: Map<string, unknown> | null = null;+ // --- IndexedDB tier (asynchronous, per-key rows) -------------------------+ let idbTimer: ReturnType<typeof setTimeout> | null = null;+ const dirtyIdb = new Set<string>();+ const deletedIdb = new Set<string>();- const saveCache = () => {- if (!cacheMapInstance) return;- try {- // Only save whitelisted keys- const entries = Array.from(cacheMapInstance.entries())- .filter(([key]) => matchesCacheablePattern(key, cacheablePatterns))- .slice(-maxEntries)- .map(([key, data]) => [key, { data, timestamp: Date.now(), version } as CacheEntry]);-- const serialized = JSON.stringify(entries);-- // Check size, cleanup half when exceeding 4MB- const sizeInMB = new Blob([serialized]).size / (1024 * 1024);- if (sizeInMB > 4) {- const reduced = entries.slice(-Math.floor(maxEntries / 2));- localStorage.setItem(cacheKey, JSON.stringify(reduced));- console.warn(`[SWR Cache] Cache too large (${sizeInMB.toFixed(2)}MB), cleaned up`);- } else {- localStorage.setItem(cacheKey, serialized);- }- } catch (error) {- if ((error as DOMException).name === 'QuotaExceededError') {- // Quota exceeded, clear cache- try {- localStorage.removeItem(cacheKey);- } catch {- // ignore- }- console.error('[SWR Cache] Quota exceeded, cache cleared');- } else {- onError(error as Error);- }- }- };+ const flushIdb = () => {+ if (!cacheMapInstance) return;+ const scope = getScope();+ const writes = [...dirtyIdb];+ const dels = [...deletedIdb];+ dirtyIdb.clear();+ deletedIdb.clear();- const debouncedSave = () => {- if (saveTimer) clearTimeout(saveTimer);- saveTimer = setTimeout(saveCache, 2000);- };+ for (const k of dels) void localDataCache.delete(buildLocalDataKey(scope, k));+ for (const k of writes) {+ const v = cacheMapInstance.get(k);+ if (v !== undefined) void localDataCache.set(buildLocalDataKey(scope, k), v, version);+ }+ };- // Save immediately on page unload- window.addEventListener('beforeunload', () => {- if (saveTimer) clearTimeout(saveTimer);- saveCache();- });+ const debouncedFlushIdb = () => {+ if (idbTimer) clearTimeout(idbTimer);+ idbTimer = setTimeout(flushIdb, debounceMs);+ };- // Multi-tab sync- window.addEventListener('storage', (event) => {- if (event.key === cacheKey && event.newValue && cacheMapInstance) {- try {- const parsedEntries: [string, CacheEntry][] = JSON.parse(event.newValue);- // Only update whitelisted keys- parsedEntries.forEach(([key, entry]) => {- if (matchesCacheablePattern(key, cacheablePatterns)) {- cacheMapInstance!.set(key, entry.data);- }- });- } catch (error) {- onError(error as Error);- }- }- });-- /**- * Create Map with interception- * Only whitelisted keys trigger persistence- */- class LocalStorageCacheMap extends Map<string, unknown> {- private initialized = false;-- constructor(entries?: readonly (readonly [string, unknown])[] | null) {- super();- // Manually add initial data to avoid triggering set in super()- if (entries) {- for (const [key, value] of entries) {- super.set(key, value);- }- }- this.initialized = true;+ const loadIdb = async () => {+ const scope = getScope();+ try {+ const entries = await localDataCache.entriesByScope(scope);+ const now = Date.now();+ const valid = entries.filter(+ (e) => (e.version === undefined || e.version === version) && now - e.updatedAt <= ttl,+ );+ // Map may have changed scope while we awaited; only apply if still current.+ if (cacheMapInstance && getScope() === scope) {+ cacheMapInstance.hydrate(valid.map((e) => [e.key, e.data]));}+ } catch (error) {+ onError(error as Error);+ } finally {+ onScopeHydrated?.(scope);+ }+ };- get(key: string): unknown {- return super.get(key);- }+ // --- write routing -------------------------------------------------------+ const onSet = (key: string) => {+ const tier = tierOf(key);+ if (tier === 'local') debouncedSaveLocal();+ else if (tier === 'idb') {+ deletedIdb.delete(key);+ dirtyIdb.add(key);+ debouncedFlushIdb();+ }+ };- set(key: string, value: unknown): this {- super.set(key, value);- // Only trigger save after initialization and for whitelisted keys- if (this.initialized && matchesCacheablePattern(key, cacheablePatterns)) {- debouncedSave();- }- return this;- }+ const onDelete = (key: string) => {+ const tier = tierOf(key);+ if (tier === 'local') debouncedSaveLocal();+ else if (tier === 'idb') {+ dirtyIdb.delete(key);+ deletedIdb.add(key);+ debouncedFlushIdb();+ }+ };- delete(key: string): boolean {- const result = super.delete(key);- if (this.initialized && matchesCacheablePattern(key, cacheablePatterns)) {- debouncedSave();- }- return result;+ /**+ * Map that routes writes to the correct persistence tier. `hydrate` /+ * `dropPersisted` mutate the map without triggering persistence.+ */+ class TieredCacheMap extends Map<string, unknown> {+ private live = false;++ set(key: string, value: unknown): this {+ super.set(key, value);+ if (this.live) onSet(key);+ return this;+ }++ delete(key: string): boolean {+ const result = super.delete(key);+ if (this.live) onDelete(key);+ return result;+ }++ /** Bulk-load entries without persisting them back. */+ hydrate(entries: readonly (readonly [string, unknown])[]): void {+ for (const [key, value] of entries) super.set(key, value);+ this.live = true;+ }++ /** Remove all persisted-tier entries from memory without persisting deletes. */+ dropPersisted(): void {+ // Snapshot keys first β we mutate the map while iterating.+ const keys = Array.from(this.keys());+ for (const key of keys) if (tierOf(key)) super.delete(key);+ }+ }++ // Flush both tiers immediately on unload.+ window.addEventListener('beforeunload', () => {+ if (localTimer) clearTimeout(localTimer);+ if (idbTimer) clearTimeout(idbTimer);+ saveLocal();+ flushIdb();+ });++ // Multi-tab sync for the localStorage tier only.+ window.addEventListener('storage', (event) => {+ if (event.key === getScopedCacheKey(getScope()) && event.newValue && cacheMapInstance) {+ try {+ const parsed: [string, CacheEntry][] = JSON.parse(event.newValue);+ parsed.forEach(([key, entry]) => {+ if (matchesPattern(key, localPatterns)) cacheMapInstance!.hydrate([[key, entry.data]]);+ });+ } catch (error) {+ onError(error as Error);}}+ });- // Create Map instance- const cacheMap = new LocalStorageCacheMap(Array.from(initialData.entries()));- cacheMapInstance = cacheMap;+ const provider: ScopedSWRProvider = () => {+ const map = new TieredCacheMap();+ cacheMapInstance = map;+ map.hydrate([...loadLocal().entries()]); // synchronous first paint+ void loadIdb(); // asynchronous local-first hydration+ return map;+ };- return cacheMap;+ provider.reloadScope = () => {+ if (!cacheMapInstance) return;+ // Drop pending writes scheduled for the previous scope.+ if (localTimer) {+ clearTimeout(localTimer);+ localTimer = null;+ }+ if (idbTimer) {+ clearTimeout(idbTimer);+ idbTimer = null;+ }+ dirtyIdb.clear();+ deletedIdb.clear();++ cacheMapInstance.dropPersisted();+ cacheMapInstance.hydrate([...loadLocal().entries()]);+ void loadIdb();};++ return provider;}/**- * Clear SWR localStorage cache- * Can be used for manual cleanup or when app version changes+ * Clear the localStorage cache tier for a scope (or the legacy key).*/export function clearSWRCache(cacheKey = 'lobechat-swr-cache'): void {if (typeof window === 'undefined') return;-try {localStorage.removeItem(cacheKey);console.info('[SWR Cache] Cache cleared');@@ -263,29 +351,52 @@ export function clearSWRCache(cacheKey = 'lobechat-swr-cache'): void {}/**- * SWR localStorage cache whitelist- * Only keys matching these patterns will be persisted to localStorage+ * Central tiering config β the single place that decides where each kind of+ * data is persisted, keyed by the `domain:` namespace of the SWR key (see the+ * key registry in `@/libs/swr/keys`). Matching is substring-based; the colon in+ * `domain:` keeps these from matching unrelated keys.*/-const SWR_CACHEABLE_PATTERNS = [- // Home page data- 'fetchAgentList', // Agent list- 'fetchGroups', // Group list- 'fetchRecentTopics', // Recent topics- 'fetchRecentResources', // Recent resources- 'fetchRecentPages', // Recent pages- 'fetchRecents', // Unified recents- // Chat page data- 'SWR_USE_FETCH_TOPIC', // Topic list (cached per agentId/groupId)- 'fetchGroupDetail', // Group detail (cached per groupId)- 'CONVERSATION_FETCH_MESSAGES', // Messages (cached per agentId/topicId)-];+export const CACHE_TIERS = {+ /** Large / important business entities β IndexedDB. */+ idb: [+ 'message:', // chat messages (conversation + legacy stores)+ 'topic:', // topic lists / agent view / search+ 'agent:', // sidebar agent list + agent documents+ 'group:detail', // group detail (group list stays in localStorage)+ 'task:', // task lists + detail+ 'document:', // editor document content+ 'page:', // page detail / list / meta+ 'notebook:', // notebook documents+ 'brief:', // briefs+ ],+ /** Small, frequently-changing list shells β localStorage (sync first paint). */+ local: [+ 'fetchRecents',+ 'fetchRecentTopics',+ 'fetchRecentResources',+ 'fetchRecentPages',+ 'fetchGroups',+ ],+} as const;/**- * Export provider factory function for SWRConfig+ * Provider factory for SWRConfig.+ *+ * @param getScope resolver for the current identity scope. Evaluated lazily so+ * persistence follows the active user/workspace; call `provider.reloadScope()`+ * after the scope changes to re-hydrate in place.+ * @param onScopeHydrated notified after a scope's IndexedDB tier finishes+ * loading (used by the boot hydration gate).*/-export const swrCacheProvider = () => {- return createLocalStorageProvider({- cacheablePatterns: SWR_CACHEABLE_PATTERNS,+export const swrCacheProvider = (+ getScope: () => string,+ onScopeHydrated?: (scope: string) => void,+): ScopedSWRProvider => {+ return createCacheProvider({+ getScope,+ idbPatterns: [...CACHE_TIERS.idb],+ localPatterns: [...CACHE_TIERS.local],+ onScopeHydrated,ttl: 12 * 60 * 60 * 1000, // 12 hours});};diff --git a/src/libs/swr/useCacheScope.ts b/src/libs/swr/useCacheScope.tsnew file mode 100644index 00000000000..fe4049ed8ee--- /dev/null+++ b/src/libs/swr/useCacheScope.ts@@ -0,0 +1,42 @@+import {+ getActiveWorkspaceId,+ useActiveWorkspaceId,+} from '@/business/client/hooks/useActiveWorkspaceId';+import { getUserStoreState, useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++const ANON = 'anon';+const PERSONAL = 'personal';++/**+ * Build a cache scope string from the current identity.+ *+ * Every client-side persistence tier (the localStorage SWR cache and the+ * IndexedDB local-first store) is partitioned by this scope so that data+ * belonging to different users / workspaces sharing the same browser origin+ * never collides or overwrites each other.+ *+ * Personal mode (no active workspace) collapses to `${userId}:personal`;+ * logged-out / SSR collapses to `anon:personal`.+ */+export const buildCacheScope = (+ userId: string | null | undefined,+ workspaceId: string | null | undefined,+): string => `${userId || ANON}:${workspaceId || PERSONAL}`;++/**+ * React hook returning the current cache scope. Recomputes when the signed-in+ * user or the active workspace changes.+ */+export const useCacheScope = (): string => {+ const userId = useUserStore(userProfileSelectors.userId);+ const workspaceId = useActiveWorkspaceId();+ return buildCacheScope(userId, workspaceId);+};++/**+ * Non-React getter for the current cache scope (for use inside services /+ * imperative code paths).+ */+export const getCacheScope = (): string =>+ buildCacheScope(userProfileSelectors.userId(getUserStoreState()), getActiveWorkspaceId());diff --git a/src/libs/swr/useClientDataSWRWithSync.ts b/src/libs/swr/useClientDataSWRWithSync.tsindex 89be72a0192..46fbf723245 100644--- a/src/libs/swr/useClientDataSWRWithSync.ts+++ b/src/libs/swr/useClientDataSWRWithSync.ts@@ -2,7 +2,11 @@* useClientDataSWR with automatic Zustand store sync** Solves the problem of SWR cached data not being immediately synced to Zustand store.- * When SWR returns data from localStorage cache, it will automatically sync to store via onData callback.+ * When SWR returns data from the persisted cache, it will automatically sync to store via onData callback.+ *+ * Persistence (localStorage vs IndexedDB) is handled transparently by the+ * tier-aware SWR cache provider (see `localStorageProvider.ts`) based on the+ * SWR key β consumers never need to opt in per call.*/import { useEffect, useRef } from 'react';diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsxindex ef47dc1bf2a..dca11d90b89 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx@@ -169,8 +169,8 @@ vi.mock('@/features/ChatInput/InputEditor/ActionTag/skillDragData', () => ({vi.mock('@/services/agentDocument', () => ({agentDocumentSWRKeys: {- documents: (agentId: string) => ['agent-documents', agentId],- documentsList: (agentId: string) => ['agent-documents-list', agentId],+ documents: (agentId: string) => ['agent:documents', agentId],+ documentsList: (agentId: string) => ['agent:documentsList', agentId],},agentDocumentService: {getDocuments: vi.fn(),diff --git a/src/services/agentDocument.test.ts b/src/services/agentDocument.test.tsindex 86f8c217f3e..aecbf9ad7a0 100644--- a/src/services/agentDocument.test.ts+++ b/src/services/agentDocument.test.ts@@ -52,7 +52,7 @@ describe('AgentDocumentService', () => {title: 'title',});- expect(mutate).toHaveBeenCalledWith(['agent-documents', 'agent-1']);+ expect(mutate).toHaveBeenCalledWith(['agent:documents', 'agent-1']);});it('should revalidate agent documents after removeDocument', async () => {@@ -63,13 +63,13 @@ describe('AgentDocumentService', () => {topicId: 'topic-1',});- expect(mutate).toHaveBeenCalledWith(['agent-documents', 'agent-1']);- expect(mutate).toHaveBeenCalledWith(['agent-documents-list', 'agent-1']);- expect(mutate).toHaveBeenCalledWith(['workspace-agent-document-editor', 'agent-1', 'doc-1']);- expect(mutate).toHaveBeenCalledWith(['page-document-meta', 'page-doc-1']);- expect(mutate).toHaveBeenCalledWith(['pageDetail', 'page-doc-1']);- expect(mutate).toHaveBeenCalledWith(['pageDocuments']);- expect(mutate).toHaveBeenCalledWith(['SWR_USE_FETCH_NOTEBOOK_DOCUMENTS', 'topic-1']);+ expect(mutate).toHaveBeenCalledWith(['agent:documents', 'agent-1']);+ expect(mutate).toHaveBeenCalledWith(['agent:documentsList', 'agent-1']);+ expect(mutate).toHaveBeenCalledWith(['agent:documentEditor', 'agent-1', 'doc-1']);+ expect(mutate).toHaveBeenCalledWith(['page:meta', 'page-doc-1']);+ expect(mutate).toHaveBeenCalledWith(['page:detail', 'page-doc-1']);+ expect(mutate).toHaveBeenCalledWith(['page:list']);+ expect(mutate).toHaveBeenCalledWith(['notebook:documents', 'topic-1']);});it('should revalidate agent documents after updateLoadRule', async () => {@@ -79,7 +79,7 @@ describe('AgentDocumentService', () => {rule: {},});- expect(mutate).toHaveBeenCalledWith(['agent-documents', 'agent-1']);+ expect(mutate).toHaveBeenCalledWith(['agent:documents', 'agent-1']);});it('should fetch target agent documents when cache is missing', async () => {diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.tsindex 5e5f9bd88b8..99f32121a33 100644--- a/src/services/document/swrKeys.ts+++ b/src/services/document/swrKeys.ts@@ -1,22 +1,22 @@-export const SWR_USE_FETCH_NOTEBOOK_DOCUMENTS = 'SWR_USE_FETCH_NOTEBOOK_DOCUMENTS';+// Domain-namespaced SWR key roots. See the central registry in `@/libs/swr/keys`.+export const SWR_USE_FETCH_NOTEBOOK_DOCUMENTS = 'notebook:documents';export const agentDocumentSWRKeys = {- documents: (agentId: string) => ['agent-documents', agentId] as const,+ documents: (agentId: string) => ['agent:documents', agentId] as const,/*** UI-side list: raw AgentDocumentWithRules (includes documentId, sourceType, createdAt).* Kept separate from `documents` because the agent store writes mapAgentDocumentsToContext(...)* under that key, which drops those fields.*/- documentsList: (agentId: string) => ['agent-documents-list', agentId] as const,- readDocument: (agentId: string, id: string) =>- ['workspace-agent-document-editor', agentId, id] as const,+ documentsList: (agentId: string) => ['agent:documentsList', agentId] as const,+ readDocument: (agentId: string, id: string) => ['agent:documentEditor', agentId, id] as const,};export const documentSWRKeys = {- editor: (documentId: string) => ['document/editor', documentId] as const,- pageDetail: (documentId: string) => ['pageDetail', documentId] as const,- pageDocuments: () => ['pageDocuments'] as const,- pageMeta: (documentId: string) => ['page-document-meta', documentId] as const,+ editor: (documentId: string) => ['document:editor', documentId] as const,+ pageDetail: (documentId: string) => ['page:detail', documentId] as const,+ pageDocuments: () => ['page:list'] as const,+ pageMeta: (documentId: string) => ['page:meta', documentId] as const,};export const notebookSWRKeys = {diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex 712af2599b1..fea6ef3b7ac 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -30,8 +30,8 @@ vi.mock('@/services/agentDocument', () => ({listDocuments: vi.fn(),},agentDocumentSWRKeys: {- documents: (agentId: string) => ['agent-documents', agentId] as const,- documentsList: (agentId: string) => ['agent-documents-list', agentId] as const,+ documents: (agentId: string) => ['agent:documents', agentId] as const,+ documentsList: (agentId: string) => ['agent:documentsList', agentId] as const,},resolveAgentDocumentsContext: vi.fn(),}));diff --git a/src/store/agentGroup/action.ts b/src/store/agentGroup/action.tsindex 23cb4323e2d..a85a60020d8 100644--- a/src/store/agentGroup/action.ts+++ b/src/store/agentGroup/action.ts@@ -5,6 +5,7 @@ import { type StateCreator } from 'zustand/vanilla';import { type ChatGroupItem } from '@/database/schemas/chatGroup';import { mutate, useClientDataSWRWithSync } from '@/libs/swr';+import { groupKeys } from '@/libs/swr/keys';import { chatGroupService } from '@/services/chatGroup';import { getAgentStoreState } from '@/store/agent';import { type ChatGroupStore } from '@/store/agentGroup/store';@@ -24,7 +25,6 @@ import { ChatGroupMemberAction } from './slices/member';const n = setNamespace('chatGroup');const FETCH_GROUPS_KEY = 'fetchGroups';-const FETCH_GROUP_DETAIL_KEY = 'fetchGroupDetail';/*** Convert ChatGroupItem to AgentGroupDetail by adding empty agents array if not present@@ -141,7 +141,7 @@ class ChatGroupInternalAction implements ResetableStore {};refreshGroupDetail = async (groupId: string) => {- await mutate([FETCH_GROUP_DETAIL_KEY, groupId]);+ await mutate(groupKeys.detail(groupId));};refreshGroups = async () => {@@ -158,7 +158,7 @@ class ChatGroupInternalAction implements ResetableStore {useFetchGroupDetail = (enabled: boolean, groupId: string) =>useClientDataSWRWithSync<AgentGroupDetail | null>(- enabled && groupId ? [FETCH_GROUP_DETAIL_KEY, groupId] : null,+ enabled && groupId ? groupKeys.detail(groupId) : null,async () => {const groupDetail = await chatGroupService.getGroupDetail(groupId);if (!groupDetail) throw new Error(`Group ${groupId} not found`);diff --git a/src/store/agentGroup/slices/curd.test.ts b/src/store/agentGroup/slices/curd.test.tsindex a03725696ee..ddad52d6edd 100644--- a/src/store/agentGroup/slices/curd.test.ts+++ b/src/store/agentGroup/slices/curd.test.ts@@ -77,7 +77,7 @@ describe('ChatGroupCurdSlice', () => {await result.current.updateGroup('group-1', { description: 'New description' });});- expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);});});@@ -125,7 +125,7 @@ describe('ChatGroupCurdSlice', () => {await result.current.updateGroupConfig({ revealDM: true });});- expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);});});@@ -171,7 +171,7 @@ describe('ChatGroupCurdSlice', () => {await result.current.updateGroupMeta({ title: 'Updated' });});- expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);});});});diff --git a/src/store/agentGroup/slices/member.test.ts b/src/store/agentGroup/slices/member.test.tsindex e3af71baf8c..22077ceeb80 100644--- a/src/store/agentGroup/slices/member.test.ts+++ b/src/store/agentGroup/slices/member.test.ts@@ -63,7 +63,7 @@ describe('ChatGroupMemberSlice', () => {await result.current.addAgentsToGroup('group-1', ['agent-1']);});- expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);});});@@ -95,7 +95,7 @@ describe('ChatGroupMemberSlice', () => {await result.current.removeAgentFromGroup('group-1', 'agent-1');});- expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);});});@@ -130,7 +130,7 @@ describe('ChatGroupMemberSlice', () => {await result.current.reorderGroupMembers('group-1', ['agent-1', 'agent-2']);});- expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);});});});diff --git a/src/store/brief/slices/list/action.ts b/src/store/brief/slices/list/action.tsindex 6308d8fd6e2..16336a99837 100644--- a/src/store/brief/slices/list/action.ts+++ b/src/store/brief/slices/list/action.ts@@ -2,6 +2,7 @@ import isEqual from 'fast-deep-equal';import { type SWRResponse } from 'swr';import { useClientDataSWRWithSync } from '@/libs/swr';+import { briefKeys } from '@/libs/swr/keys';import { briefService } from '@/services/brief';import { taskService } from '@/services/task';import { type BriefStore } from '@/store/brief/store';@@ -11,8 +12,6 @@ import { setNamespace } from '@/utils/storeDebug';const n = setNamespace('briefList');-const FETCH_BRIEFS_KEY = 'fetchBriefs';-type Setter = StoreSetter<BriefStore>;export const createBriefListSlice = (set: Setter, get: () => BriefStore, _api?: unknown) =>@@ -76,7 +75,7 @@ export class BriefListActionImpl {useFetchBriefs = (isLogin: boolean | undefined): SWRResponse<BriefItem[]> => {return useClientDataSWRWithSync<BriefItem[]>(- isLogin === true ? [FETCH_BRIEFS_KEY, isLogin] : null,+ isLogin === true ? briefKeys.list(isLogin) : null,async () => {const result = await briefService.listUnresolved();return result.data as BriefItem[];diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.tsindex bdb7be96cae..37cb9b5fa73 100644--- a/src/store/chat/slices/message/actions/query.ts+++ b/src/store/chat/slices/message/actions/query.ts@@ -4,6 +4,7 @@ import isEqual from 'fast-deep-equal';import { type SWRResponse } from 'swr';import { mutate, useClientDataSWRWithSync } from '@/libs/swr';+import { messageKeys } from '@/libs/swr/keys';import { messageService } from '@/services/message';import { type ChatStore } from '@/store/chat/store';import { type StoreSetter } from '@/store/types';@@ -136,7 +137,7 @@ export class MessageQueryActionImpl {const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;return useClientDataSWRWithSync<UIChatMessage[]>(- shouldFetch ? ['CHAT_STORE_FETCH_MESSAGES', context] : null,+ shouldFetch ? messageKeys.listLegacy(context) : null,() => messageService.getMessages(context),{onData: (data) => {diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 946423f5e52..1b6b997eb02 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -215,13 +215,11 @@ describe('topic action', () => {const containerKey = `agent_${activeAgentId}`;// Should match key with correct containerKey- expect(- matcherFn(['SWR_USE_FETCH_TOPIC', containerKey, { isInbox: false, pageSize: 20 }]),- ).toBe(true);+ expect(matcherFn(['topic:list', containerKey, { isInbox: false, pageSize: 20 }])).toBe(true);// Should not match key with different containerKey- expect(- matcherFn(['SWR_USE_FETCH_TOPIC', 'agent_other-id', { isInbox: false, pageSize: 20 }]),- ).toBe(false);+ expect(matcherFn(['topic:list', 'agent_other-id', { isInbox: false, pageSize: 20 }])).toBe(+ false,+ );// Should not match non-array keysexpect(matcherFn('some-string')).toBe(false);// Should not match keys with wrong prefixdiff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex b29209e5d94..699bf4b8f99 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -11,6 +11,7 @@ import useSWR from 'swr';import { message } from '@/components/AntdStaticMethods';import { LOADING_FLAT } from '@/const/message';import { mutate, useClientDataSWRWithSync } from '@/libs/swr';+import { topicKeys } from '@/libs/swr/keys';import { chatService } from '@/services/chat';import { messageService } from '@/services/message';import { topicService } from '@/services/topic';@@ -37,9 +38,6 @@ import { topicSelectors } from './selectors';const n = setNamespace('t');-const SWR_USE_FETCH_TOPIC = 'SWR_USE_FETCH_TOPIC';-const SWR_USE_FETCH_AGENT_TOPICS_VIEW = 'SWR_USE_FETCH_AGENT_TOPICS_VIEW';-const SWR_USE_SEARCH_TOPIC = 'SWR_USE_SEARCH_TOPIC';type CronTopicsGroupWithJobInfo = {cronJob: unknown;cronJobId: string;@@ -404,18 +402,14 @@ export class ChatTopicActionImpl {return useClientDataSWRWithSync<{ items: ChatTopic[]; total: number }>(enable && hasValidContainer- ? [- SWR_USE_FETCH_TOPIC,- containerKey,- {- isInbox,- pageSize,- ...(effectiveExcludeTriggers ? { excludeTriggers: effectiveExcludeTriggers } : {}),- ...(effectiveExcludeStatuses ? { excludeStatuses: effectiveExcludeStatuses } : {}),- ...(sortBy ? { sortBy } : {}),- ...(withDetails ? { withDetails: true } : {}),- },- ]+ ? topicKeys.list(containerKey, {+ isInbox,+ pageSize,+ ...(effectiveExcludeTriggers ? { excludeTriggers: effectiveExcludeTriggers } : {}),+ ...(effectiveExcludeStatuses ? { excludeStatuses: effectiveExcludeStatuses } : {}),+ ...(sortBy ? { sortBy } : {}),+ ...(withDetails ? { withDetails: true } : {}),+ }): null,async () => {// agentId, groupId, isInbox, pageSize come from the outer scope closure@@ -545,11 +539,10 @@ export class ChatTopicActionImpl {return useClientDataSWRWithSync<{ items: ChatTopic[]; total: number }>(enable && hasValidAgent- ? [- SWR_USE_FETCH_AGENT_TOPICS_VIEW,- containerKey,- { pageSize, ...(withDetails ? { withDetails: true } : {}) },- ]+ ? topicKeys.agentView(containerKey, {+ pageSize,+ ...(withDetails ? { withDetails: true } : {}),+ }): null,async () => {if (!agentId) return { items: [], total: 0 };@@ -689,8 +682,7 @@ export class ChatTopicActionImpl {if (!activeAgentId) return;const containerKey = topicMapKey({ agentId: activeAgentId });await mutate(- (key) =>- Array.isArray(key) && key[0] === SWR_USE_FETCH_AGENT_TOPICS_VIEW && key[1] === containerKey,+ (key) => Array.isArray(key) && key[0] === topicKeys.agentView.root && key[1] === containerKey,);};@@ -783,7 +775,7 @@ export class ChatTopicActionImpl {} = {},): SWRResponse<ChatTopic[]> => {return useSWR<ChatTopic[]>(- keywords ? [SWR_USE_SEARCH_TOPIC, keywords, agentId, groupId] : null,+ keywords ? topicKeys.search(keywords, agentId, groupId) : null,([, keywords, agentId, groupId]: [string, string, string | undefined, string | undefined]) =>topicService.searchTopics(keywords, agentId, groupId),{@@ -955,16 +947,16 @@ export class ChatTopicActionImpl {refreshTopic = async (): Promise<void> => {const { activeAgentId, activeGroupId } = this.#get();// Use topicMapKey to generate the same key used in useFetchTopics- // Key format: [SWR_USE_FETCH_TOPIC, containerKey, { isInbox, pageSize }]+ // Key format: topicKeys.list(containerKey, { isInbox, pageSize })const containerKey = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });const agentViewKey = activeAgentId ? topicMapKey({ agentId: activeAgentId }) : null;await mutate((key) =>Array.isArray(key) &&- ((key[0] === SWR_USE_FETCH_TOPIC &&+ ((key[0] === topicKeys.list.root &&typeof key[1] === 'string' &&key[1] === containerKey) ||- (key[0] === SWR_USE_FETCH_AGENT_TOPICS_VIEW &&+ (key[0] === topicKeys.agentView.root &&agentViewKey !== null &&key[1] === agentViewKey)),);diff --git a/src/store/home/slices/agentList/action.ts b/src/store/home/slices/agentList/action.tsindex cdb117a2e49..9743e928a3f 100644--- a/src/store/home/slices/agentList/action.ts+++ b/src/store/home/slices/agentList/action.ts@@ -3,6 +3,7 @@ import { type SWRResponse } from 'swr';import { type SidebarAgentItem, type SidebarAgentListResponse } from '@/database/repositories/home';import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';+import { agentKeys } from '@/libs/swr/keys';import { homeService } from '@/services/home';import { getAgentStoreState } from '@/store/agent';import { type HomeStore } from '@/store/home/store';@@ -13,7 +14,6 @@ import { mapResponseToState } from './initialState';const n = setNamespace('agentList');-const FETCH_AGENT_LIST_KEY = 'fetchAgentList';const SEARCH_AGENTS_KEY = 'searchAgents';type Setter = StoreSetter<HomeStore>;@@ -40,12 +40,12 @@ export class AgentListActionImpl {refreshAgentList = async (): Promise<void> => {getAgentStoreState().invalidateAvailableAgents();- await mutate([FETCH_AGENT_LIST_KEY, true]);+ await mutate(agentKeys.list(true));};useFetchAgentList = (isLogin: boolean | undefined): SWRResponse<SidebarAgentListResponse> => {return useClientDataSWRWithSync<SidebarAgentListResponse>(- isLogin === true ? [FETCH_AGENT_LIST_KEY, isLogin] : null,+ isLogin === true ? agentKeys.list(isLogin) : null,() => homeService.getSidebarAgentList(),{onData: (data) => {diff --git a/src/store/task/slices/config/action.test.ts b/src/store/task/slices/config/action.test.tsindex 006d5dc076d..5c5c83384fc 100644--- a/src/store/task/slices/config/action.test.ts+++ b/src/store/task/slices/config/action.test.ts@@ -55,7 +55,7 @@ describe('TaskConfigSliceAction', () => {await useTaskStore.getState().updateCheckpoint('T-1', { onAgentRequest: true });- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});});@@ -83,7 +83,7 @@ describe('TaskConfigSliceAction', () => {const result = await useTaskStore.getState().runReview('T-1', { content: 'Test output' });expect(taskService.runReview).toHaveBeenCalledWith('T-1', { content: 'Test output' });- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);expect(result).toEqual({ data: mockResult, success: true });});@@ -109,7 +109,7 @@ describe('TaskConfigSliceAction', () => {model: 'claude-sonnet-4-6',provider: 'anthropic',});- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});});@@ -121,7 +121,7 @@ describe('TaskConfigSliceAction', () => {await useTaskStore.getState().updatePeriodicInterval('T-1', 600);expect(taskService.update).toHaveBeenCalledWith('T-1', { heartbeatInterval: 600 });- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});it('should send 0 when null to disable interval (automationMode untouched)', async () => {@@ -280,7 +280,7 @@ describe('TaskConfigSliceAction', () => {expect(useTaskStore.getState().taskDetailMap['T-1'].automationMode).toBe('schedule');const refreshCalls = vi.mocked(mutate)- .mock.calls.filter((c) => Array.isArray(c[0]) && c[0][0] === 'fetchTaskDetail');+ .mock.calls.filter((c) => Array.isArray(c[0]) && c[0][0] === 'task:detail');expect(refreshCalls).toHaveLength(0);});@@ -333,7 +333,7 @@ describe('TaskConfigSliceAction', () => {// No SWR refresh β optimistic patch is the source of truth.const refreshCalls = vi.mocked(mutate)- .mock.calls.filter((c) => Array.isArray(c[0]) && c[0][0] === 'fetchTaskDetail');+ .mock.calls.filter((c) => Array.isArray(c[0]) && c[0][0] === 'task:detail');expect(refreshCalls).toHaveLength(0);});@@ -436,7 +436,7 @@ describe('TaskConfigSliceAction', () => {await useTaskStore.getState().resolveBrief('brief_1', { action: 'approve' });expect(taskService.resolveBrief).toHaveBeenCalledWith('brief_1', { action: 'approve' });- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});});@@ -448,7 +448,7 @@ describe('TaskConfigSliceAction', () => {await useTaskStore.getState().markBriefRead('brief_1');expect(taskService.markBriefRead).toHaveBeenCalledWith('brief_1');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});});});diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsindex e3fa8cf0969..91fba92a590 100644--- a/src/store/task/slices/detail/action.test.ts+++ b/src/store/task/slices/detail/action.test.ts@@ -133,7 +133,7 @@ describe('TaskDetailSliceAction', () => {);expect(useTaskStore.getState().taskSaveStatus).toBe('idle');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);expect(message.error).toHaveBeenCalled();});@@ -158,8 +158,8 @@ describe('TaskDetailSliceAction', () => {useTaskStore.getState().updateTask('T-sub', { assigneeAgentId: 'agent-x' }),).rejects.toThrow('fail');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-sub']);- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-parent']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-sub']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-parent']);});it('should not show error when update succeeds but cache refresh fails', async () => {@@ -205,9 +205,9 @@ describe('TaskDetailSliceAction', () => {expect(taskService.update).toHaveBeenCalledWith('T-sub', { parentTaskId: 'T-new-parent' });expect(useTaskStore.getState().taskDetailMap['T-sub']).not.toHaveProperty('parentTaskId');expect(refreshTaskList).toHaveBeenCalled();- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-sub']);- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-parent']);- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-new-parent']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-sub']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-parent']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-new-parent']);});it('should refresh the parent that was patched even if activeTaskId changes mid-flight', async () => {@@ -233,8 +233,8 @@ describe('TaskDetailSliceAction', () => {useTaskStore.getState().updateTask('T-sub', { assigneeAgentId: 'agent-x' }),).rejects.toThrow('fail');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-sub']);- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-parent']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-sub']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-parent']);});});@@ -302,7 +302,7 @@ describe('TaskDetailSliceAction', () => {await useTaskStore.getState().addComment('T-1', 'Nice work');expect(taskService.addComment).toHaveBeenCalledWith('T-1', 'Nice work', undefined);- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});});@@ -314,7 +314,7 @@ describe('TaskDetailSliceAction', () => {await useTaskStore.getState().addDependency('T-1', 'T-2', 'blocks');expect(taskService.addDependency).toHaveBeenCalledWith('T-1', 'T-2', 'blocks');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});it('should propagate error from service', async () => {@@ -334,7 +334,7 @@ describe('TaskDetailSliceAction', () => {await useTaskStore.getState().removeDependency('T-1', 'T-2');expect(taskService.removeDependency).toHaveBeenCalledWith('T-1', 'T-2');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});});@@ -349,8 +349,8 @@ describe('TaskDetailSliceAction', () => {await useTaskStore.getState().unpinDocument('task_child', 'doc_1');expect(taskService.unpinDocument).toHaveBeenCalledWith('task_child', 'doc_1');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'task_child']);- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'task_child']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});it('should not double-refresh when source task equals active task', async () => {@@ -362,7 +362,7 @@ describe('TaskDetailSliceAction', () => {await useTaskStore.getState().unpinDocument('T-1', 'doc_1');expect(mutate).toHaveBeenCalledTimes(1);- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});});diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex 0c4bca57414..2d855d327a7 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -4,6 +4,7 @@ import { t } from 'i18next';import { message } from '@/components/AntdStaticMethods';import { mutate, useClientDataSWR } from '@/libs/swr';+import { taskKeys } from '@/libs/swr/keys';import { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';@@ -30,7 +31,6 @@ export interface TaskUpdatePayload {priority?: number;}-const FETCH_TASK_DETAIL_KEY = 'fetchTaskDetail';const TASK_DETAIL_POLL_INTERVAL = 10_000;// Poll while the task itself or any topic activity is still in flight, so the@@ -298,7 +298,7 @@ export class TaskDetailSliceActionImpl {});return useClientDataSWR(- taskId ? [FETCH_TASK_DETAIL_KEY, taskId] : null,+ taskId ? taskKeys.detail(taskId) : null,async ([, id]: [string, string]) => this.fetchTaskDetail(id),{ refreshInterval: shouldPoll ? TASK_DETAIL_POLL_INTERVAL : 0 },);@@ -316,7 +316,7 @@ export class TaskDetailSliceActionImpl {};internal_refreshTaskDetail = async (id: string): Promise<void> => {- await mutate([FETCH_TASK_DETAIL_KEY, id]);+ await mutate(taskKeys.detail(id));};}diff --git a/src/store/task/slices/lifecycle/action.test.ts b/src/store/task/slices/lifecycle/action.test.tsindex 1fffb6036c0..c04e79fd24b 100644--- a/src/store/task/slices/lifecycle/action.test.ts+++ b/src/store/task/slices/lifecycle/action.test.ts@@ -58,7 +58,7 @@ describe('TaskLifecycleSliceAction', () => {await useTaskStore.getState().runTask('T-1');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});});@@ -113,7 +113,7 @@ describe('TaskLifecycleSliceAction', () => {await useTaskStore.getState().cancelTopic('tpc_1');expect(taskService.cancelTopic).toHaveBeenCalledWith('tpc_1');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});it('should not refresh if no activeTaskId', async () => {@@ -136,7 +136,7 @@ describe('TaskLifecycleSliceAction', () => {await useTaskStore.getState().deleteTopic('tpc_1');expect(taskService.deleteTopic).toHaveBeenCalledWith('tpc_1');- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});});});diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.tsindex 0b05d7691da..068cff2c304 100644--- a/src/store/task/slices/list/action.test.ts+++ b/src/store/task/slices/list/action.test.ts@@ -60,7 +60,7 @@ describe('TaskListSliceAction', () => {await useTaskStore.getState().refreshTaskList();- expect(mutate).toHaveBeenCalledWith(['fetchTaskList', 'agt_1']);+ expect(mutate).toHaveBeenCalledWith(['task:list', 'agt_1']);});});});diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.tsindex c75cbb3ebc3..ebdfa1a2705 100644--- a/src/store/task/slices/list/action.ts+++ b/src/store/task/slices/list/action.ts@@ -1,13 +1,11 @@import { mutate, useClientDataSWR } from '@/libs/swr';+import { taskKeys } from '@/libs/swr/keys';import { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';import type { TaskStore } from '../../store';import type { TaskGroupItem, TaskListItem, TaskViewMode } from './initialState';-const FETCH_TASK_LIST_KEY = 'fetchTaskList';-const FETCH_TASK_GROUP_LIST_KEY = 'fetchTaskGroupList';-/*** Sentinel used as `listAgentId` when the task list is showing tasks across all agents* (e.g. the `/tasks` page). Keeps the SWR cache key distinct from per-agent lists so@@ -46,7 +44,7 @@ export class TaskListSliceActionImpl {refreshTaskGroupList = async (): Promise<void> => {const { listAgentId } = this.#get();- await mutate([FETCH_TASK_GROUP_LIST_KEY, listAgentId]);+ await mutate(taskKeys.groupList(listAgentId));};fetchTaskList = async (params: Parameters<typeof taskService.list>[0]) =>@@ -55,8 +53,8 @@ export class TaskListSliceActionImpl {refreshTaskList = async (): Promise<void> => {const { listAgentId } = this.#get();await Promise.all([- mutate([FETCH_TASK_LIST_KEY, listAgentId]),- mutate([FETCH_TASK_GROUP_LIST_KEY, listAgentId]),+ mutate(taskKeys.list(listAgentId)),+ mutate(taskKeys.groupList(listAgentId)),]);};@@ -82,7 +80,7 @@ export class TaskListSliceActionImpl {}return useClientDataSWR(- enabled && effectiveKey ? [FETCH_TASK_GROUP_LIST_KEY, effectiveKey] : null,+ enabled && effectiveKey ? taskKeys.groupList(effectiveKey) : null,async () => {return taskService.groupList({assigneeAgentId: allAgents ? undefined : agentId,@@ -117,7 +115,7 @@ export class TaskListSliceActionImpl {}return useClientDataSWR(- enabled && effectiveKey ? [FETCH_TASK_LIST_KEY, effectiveKey] : null,+ enabled && effectiveKey ? taskKeys.list(effectiveKey) : null,async ([, id]: [string, string]) => {return this.fetchTaskList(allAgents ? {} : { assigneeAgentId: id });},