π€― 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(swr): remove the SWR persistence layer (#22906)
Arvin Xu3e56ad100136
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex f5eed6b3691..cb052a025ee 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -463,9 +463,9 @@ docker exec lobehub-agent-testing-postgres psql -U postgres -d postgres -tAc \"update agents set agency_config = '{\"executionTarget\":\"local\",\"heterogeneousProvider\":{\"type\":\"claude-code\",\"command\":\"claude\"}}'::jsonb where id='<agentId>';"```-Then cold-load: a plain reload keeps serving the agent config from the tiered SWR-cache, so the renderer still shows the pre-write value (generic M6). Clear-`lobechat-swr-cache*` + `lobehub-local-data` through+Then cold-load: a plain reload keeps serving the agent config from its persisted+replica, so the renderer still shows the pre-write value (generic M6). Clear+`lobehub-local-data` (and the `replica:*` localStorage rows) through`Page.addScriptToEvaluateOnNewDocument` and reload (see "Cold SWR cache" above),then assert `agentMap[id].agencyConfig` before drawing any conclusion.@@ -491,6 +491,11 @@ timestamps before suspecting the query.#### P16 Β· Cold SWR cache: clearing then reloading is undone by the outgoing page+> The tiered SWR cache this entry describes has been removed: SWR persists nothing,+> and persisted server data lives in replicas (`query-projections` in+> `lobehub-local-data`, plus `replica:*` localStorage rows). Clear those at+> document start the same way to force a cold first load.+**applies-to:** surface=web, electron Β· runtime=any Β· phase=fixture**Situation:** forcing a first-load / skeleton state for anything backed by the@@ -2019,8 +2024,9 @@ breaks the Electron renderer outright β the local database adapter registeredHTML loading screen stays up forever. The symptom reads as "the phase under test neverappears", i.e. exactly like the product defect you were looking for.-**Works:** use the stall only on the web entry, where it holds `CacheHydrationGate`-for its full `HYDRATION_TIMEOUT` (about 8s) β ample for a screenshot plus+**Works:** use the stall only on the web entry, where it held the former+`CacheHydrationGate` for its full `HYDRATION_TIMEOUT` (about 8s; the gate is removed,+so route loaders now wait at most `PRE_PAINT_HYDRATE_TIMEOUT` instead) β ample for a screenshot plus`getBoundingClientRect` / `getComputedStyle` measurements over the same CDPconnection. For desktop, do not stall storage: observe the natural boot with thein-page sampler above. Either way, disarm withdiff --git a/.agents/acceptance/references/probe-field-notes.md b/.agents/acceptance/references/probe-field-notes.mdindex 3aa0bdec99a..8449644c639 100644--- a/.agents/acceptance/references/probe-field-notes.md+++ b/.agents/acceptance/references/probe-field-notes.md@@ -279,7 +279,7 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to- **Test for it**: assert the field is `null` (not `undefined`) after the consume action; a test thatonly checks "the request was acted on" passes in both the broken and fixed versions.-### C11. Persisted SWR cache serves a STALE agent config after a direct DB write+### C11. Persisted cache serves a STALE agent config after a direct DB write- **Situation**: seeding `agents.agency_config` or `agents.model` directly in Postgres, then usingthe app to drive an assertion.diff --git a/.agents/skills/data-fetching-architecture/references/home-first-paint.md b/.agents/skills/data-fetching-architecture/references/home-first-paint.mdindex 203da5c475d..41709ef545a 100644--- a/.agents/skills/data-fetching-architecture/references/home-first-paint.md+++ b/.agents/skills/data-fetching-architecture/references/home-first-paint.md@@ -8,14 +8,15 @@ the browser.## Choose the Existing Persistence Path-- Inspect the existing store, SWR key, persistence tier, and hydration consumer before- adding storage. An in-memory SWR hit does not survive a full reload; a persisted- entry does not help if the UI's Zustand state only receives network success events.-- Reuse `src/libs/swr/localStorageProvider.ts` and its `CACHE_TIERS` for suitable- query results. Builtin agent identity/configuration and project lists use its- asynchronous IndexedDB tier; the localStorage tier restores synchronously.- Restore cached results into the state consumed by the UI, then revalidate through- the existing SWR hook.+- Inspect the existing store, replica, and hydration consumer before adding storage.+ SWR keeps request state in memory only and persists nothing, so an SWR hit does not+ survive a full reload; a persisted entry does not help if the UI's Zustand state+ only receives network success events.+- Persist query results the UI paints as a replica (`@/libs/replica`, see the+ `zustand` skill). The default IndexedDB storage hydrates asynchronously, which the+ route loader bounds before paint (`PRE_PAINT_HYDRATE_TIMEOUT`); `localStorage`+ storage restores synchronously. The replica paints its projection, then+ revalidates through its SWR sync key.- For a small subset needed before a larger response arrives, reuse`AppLocalStorage` from `src/libs/replica/storage.ts`.Keep field selection and lifecycle rules in the owning domain; do not create@@ -49,8 +50,9 @@ The authoritative user-state response still refreshes the values afterward.## Lifecycle and Verification-Reuse the SWR provider's existing user/workspace partitioning and identity trust-checks; do not implement another partition manager. Domain projections must supply+Reuse the replica scope's existing user/workspace partitioning and identity trust+checks (`cacheScope` in `src/libs/replica/index.ts`); do not implement another+partition manager. Domain projections must supplytheir explicit scope. Ensure in-memory keys and hydration consumers also respectscope, since persistence partitioning alone cannot guard late callbacks.Capture mutation scope and reject stale responses after a scope switch before theydiff --git a/src/features/AgentBuilder/SuggestionChips/projection.ts b/src/features/AgentBuilder/SuggestionChips/projection.tsindex 55e44d70a41..ce5e61fbd0f 100644--- a/src/features/AgentBuilder/SuggestionChips/projection.ts+++ b/src/features/AgentBuilder/SuggestionChips/projection.ts@@ -40,9 +40,6 @@ export const builderSuggestionKey = ({* batch on the first frame instead of paying a skeleton and an LLM generation* on every page load. Only titles, prompts and the tracing id are kept; one row* per edited target and locale, the least recently used evicted past the cap.- *- * The name deliberately matches no `CACHE_TIERS` pattern- * (`agentBuilder:suggestions`), so the batch is persisted by the replica only.*/export const builderSuggestionResource = defineReplica<BuilderSuggestionParams,diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsxindex b007f1a47bb..f4e25933ed8 100644--- a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx@@ -7,8 +7,7 @@ import { RequestTrigger } from '@lobechat/types';import { act, renderHook, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { cacheScope, replicaKeys } from '@/libs/replica';-import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';+import { cacheScope } from '@/libs/replica';import { aiChatService } from '@/services/aiChat';import { builderSuggestionResource } from './projection';@@ -84,23 +83,8 @@ describe('useBuilderSuggestions', () => {vi.restoreAllMocks();});- // The SWR tier persists every key whose serialized form contains a- // CACHE_TIERS pattern; the replica must stay the only persisted copy.- it('keeps the replica sync key out of the SWR persistence tiers', () => {- const serialized = JSON.stringify(- replicaKeys.sync(- builderSuggestionResource.name,- builderSuggestionResource.version,- scope,- 'key',- baseParams,- ),- );-+ it('persists the suggestions under the replica namespace', () => {expect(builderSuggestionResource.namespace).toBe('replica:agentBuilderSuggestions:v1');- expect(- [...CACHE_TIERS.idb, ...CACHE_TIERS.local].filter((p) => serialized.includes(p)),- ).toEqual([]);});it('tags suggestion requests with the builder suggestion trigger', async () => {diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsxindex 2de95fe8db1..b75c155d2a8 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx@@ -40,7 +40,6 @@ import { useConnectorConfigure } from '@/features/Connectors/CustomConnectorModaimport { openPluginEditDrawer } from '@/features/PluginDevModal/imperative';import { createSkillStoreModal } from '@/features/SkillStore';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';@@ -204,7 +203,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =builtinToolSelectors.fixedDisplayMetaList({ isManualMode: isManualSkillMode }),isEqual,);- const plugins = useAgentStore((s) => agentByIdSelectors.getAgentPluginsById(agentId)(s));// Memory and web browsing are runtime-managed builtin tools: `hidden` keeps them// out of `metaList`, and the shared engine rules force their enabled state from@@ -591,7 +589,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =useFetchInstalledPlugins();useFetchUninstalledBuiltinTools(true);useFetchAgentSkills(true);- useCheckPluginsIsInstalled(plugins);// Load user's Composio integrations via SWR (from database)useFetchUserComposioConnections(isComposioEnabledInEnv);diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.ts b/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.tsindex 413318c5641..efb8c7c162f 100644--- a/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.ts+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.ts@@ -157,29 +157,6 @@ describe('useRememberedFilesLocation', { timeout: 15_000 }, () => {expect(storedRows()).toEqual([]);});- it('keeps its replica keys out of the SWR persistent cache', async () => {- const { replicaKeys } = await import('local-replica');- const { unstable_serialize } = await import('swr');- const { CACHE_TIERS } = await import('@/libs/swr/localStorageProvider');- const { filesLocationResource } = await import('@/store/projectFile/projection');- const { filesLocationContextKey } = await import('../useRememberedFilesLocation');- const patterns = [...CACHE_TIERS.idb, ...CACHE_TIERS.local];-- for (const contextKey of [- filesLocationContextKey('tpc_1', 'agt_1')!,- filesLocationContextKey(undefined, 'agt_1')!,- ]) {- const { name, version } = filesLocationResource;- const storageKey = filesLocationResource.storageKey({ contextKey });- // The SWR provider persists any key containing a tier pattern, so the- // replica's hydrate read must not carry one.- const swrKey = unstable_serialize(- replicaKeys.hydrate(name, version, 'u1:personal', storageKey),- );- expect(patterns.filter((pattern) => swrKey.includes(pattern))).toEqual([]);- }- });-it('passes the resolution through when there is no context to remember', async () => {const { result } = await boot({ resolved: { directory: '' }, settled: false });diff --git a/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.tsindex b2780bb2cb6..0f09915d268 100644--- a/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts+++ b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts@@ -23,7 +23,7 @@ describe('useLocalDatabaseInspector', () => {vi.clearAllMocks();mocks.listCollections.mockResolvedValue([{ entryCount: 2, name: 'query-projections' },- { entryCount: 1, name: 'swr-cache' },+ { entryCount: 1, name: 'app-settings' },]);mocks.keyGroupsByPrefix.mockImplementation(async (collection: string) =>collection === 'query-projections'@@ -102,21 +102,21 @@ describe('useLocalDatabaseInspector', () => {const { result } = renderHook(() => useLocalDatabaseInspector());await waitFor(() => expect(result.current.isLoading).toBe(false));- await act(() => result.current.selectCollection('swr-cache'));- expect(result.current.selectedCollection).toBe('swr-cache');+ await act(() => result.current.selectCollection('app-settings'));+ expect(result.current.selectedCollection).toBe('app-settings');expect(result.current.keys).toEqual(['message:list']);await act(() => result.current.selectKey('message:list'));mocks.listCollections.mockResolvedValue([{ entryCount: 2, name: 'query-projections' },- { entryCount: 2, name: 'swr-cache' },+ { entryCount: 2, name: 'app-settings' },]);mocks.keysByPrefix.mockResolvedValueOnce({ keys: ['message:list', 'topic:list'], total: 2 });mocks.get.mockResolvedValueOnce({ data: ['fresh'] });await act(() => result.current.refresh());- expect(result.current.selectedCollection).toBe('swr-cache');+ expect(result.current.selectedCollection).toBe('app-settings');expect(result.current.keys).toHaveLength(2);expect(result.current.collections[1].entryCount).toBe(2);expect(result.current.selectedEntry).toEqual({diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsxindex fb110694bce..df6214d5df7 100644--- a/src/features/ProfileEditor/AgentTool.tsx+++ b/src/features/ProfileEditor/AgentTool.tsx@@ -23,7 +23,6 @@ import ToolItem from '@/features/ChatInput/ActionBar/Tools/ToolItem';import ToolItemDetailPopover from '@/features/ChatInput/ActionBar/Tools/ToolItemDetailPopover';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';import { createSkillStoreModal } from '@/features/SkillStore';-import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';@@ -197,7 +196,6 @@ const AgentTool = memo<AgentToolProps>(useFetchInstalledPlugins();useFetchUninstalledBuiltinTools(true);useFetchAgentSkills(true);- useCheckPluginsIsInstalled(plugins);// Load user's Composio integrations via SWR (from database)useFetchUserComposioConnections(isComposioEnabledInEnv);diff --git a/src/features/RecommendTaskTemplates/projection.ts b/src/features/RecommendTaskTemplates/projection.tsindex 7fd103875cb..23d3eb8abc1 100644--- a/src/features/RecommendTaskTemplates/projection.ts+++ b/src/features/RecommendTaskTemplates/projection.ts@@ -82,9 +82,6 @@ const DAILY_RECOMMEND_VERSION = 2;* seed + count + locale. localStorage so the home cards paint on the first* frame of a reload; every refresh mints a seed, so old rows are evicted past* the cap.- *- * The name deliberately matches no `CACHE_TIERS` pattern (`taskTemplate:`), so- * the replica's SWR sync key is never persisted a second time by the SWR tier.*/export const dailyRecommendResource = defineReplica<DailyRecommendParams, TaskTemplate[]>({key: dailyRecommendKey,diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.tsindex 44722851e75..63b50eb5edc 100644--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts@@ -11,7 +11,6 @@ import { SWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheScope } from '@/libs/replica';-import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';import { taskTemplateService } from '@/services/taskTemplate';import { dailyRecommendKey, dailyRecommendResource } from './projection';@@ -156,24 +155,9 @@ describe('resolveDailyBriefRecommendationRequest', () => {expect(dailyRecommendResource.syncKey!(ai)).toEqual(dailyRecommendResource.syncKey!(research));});- // The SWR tier persists every key whose serialized form contains a- // CACHE_TIERS pattern; the replica must stay the only persisted copy.- it('keeps the replica sync key out of the SWR persistence tiers', () => {- vi.spyOn(cacheScope, 'get').mockReturnValue('user-1:personal');- const serialized = JSON.stringify(- dailyRecommendResource.syncKey!({- count: 3,- interestKeys: ['ai'],- locale: 'zh-CN',- refreshSeed: '',- }),- );-+ it('persists the recommendations under the replica namespace', () => {expect(dailyRecommendResource.storage).toBeDefined();expect(dailyRecommendResource.namespace).toBe('replica:taskTemplateDailyRecommend:v2');- expect(- [...CACHE_TIERS.idb, ...CACHE_TIERS.local].filter((p) => serialized.includes(p)),- ).toEqual([]);});it('keeps refresh seed, count, and locale in the entry key', () => {@@ -321,9 +305,9 @@ describe('useDailyBriefRecommendationsUI', () => {});});- // Regression: the recommendations were persisted by the SWR localStorage tier- // (`taskTemplate:` in CACHE_TIERS). They are a localStorage replica now: a- // reload paints the persisted cards before the network answers.+ // Regression: the recommendations used to be persisted by the removed SWR+ // localStorage tier. They are a localStorage replica now: a reload paints the+ // persisted cards before the network answers.it('paints persisted cards on reload while the request is still pending', async () => {await seed([template]);vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);diff --git a/src/hooks/useCheckPluginsIsInstalled.ts b/src/hooks/useCheckPluginsIsInstalled.tsdeleted file mode 100644index f35e38da62b..00000000000--- a/src/hooks/useCheckPluginsIsInstalled.ts+++ /dev/null@@ -1,7 +0,0 @@-import { useToolStore } from '@/store/tool';--export const useCheckPluginsIsInstalled = (plugins: string[]) => {- const checkPluginsIsInstalled = useToolStore((s) => s.useCheckPluginsIsInstalled);-- checkPluginsIsInstalled(true, plugins);-};diff --git a/src/hooks/useToolResultPayload.test.ts b/src/hooks/useToolResultPayload.test.tsindex 34ba9d5aced..f7255c63716 100644--- a/src/hooks/useToolResultPayload.test.ts+++ b/src/hooks/useToolResultPayload.test.ts@@ -9,11 +9,10 @@ import { randomUUID } from 'node:crypto';import { act, renderHook, waitFor } from '@testing-library/react';import type { PropsWithChildren } from 'react';import { createElement, useEffect } from 'react';-import { SWRConfig, unstable_serialize, useSWRConfig } from 'swr';+import { SWRConfig, useSWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { cacheScope, replicaKeys } from '@/libs/replica';-import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';+import { cacheScope } from '@/libs/replica';import { setScopedMutate } from '@/libs/swr/mutate';import { messageService } from '@/services/message';import {@@ -168,14 +167,9 @@ describe('useToolResultPayload replica', () => {expect(await storage.get(rowKey('msg-lru-1'))).toBeDefined();});- it('is bounded, and its network read is not persisted again by the SWR cache', () => {+ it('bounds its persisted entries', () => {expect(toolResultPayloadResource.maxPersistedEntries).toBe(TOOL_RESULT_PAYLOAD_MAX_PERSISTED_ENTRIES,);- const syncKey = unstable_serialize(- replicaKeys.sync(toolResultPayloadResource.name, 1, scope, 'msg_abc', 'msg_abc'),- );- const tiers: string[] = [...CACHE_TIERS.idb, ...CACHE_TIERS.local];- expect(tiers.filter((pattern) => syncKey.includes(pattern))).toEqual([]);});});diff --git a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx b/src/layout/GlobalProvider/CacheHydrationGate.test.tsxdeleted file mode 100644index caee5294b70..00000000000--- a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx+++ /dev/null@@ -1,171 +0,0 @@-import { act, render, screen } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { cacheHydration } from '@/libs/swr/cacheHydration';-import { getAppPainted, setAppPainted, setAppReady } from '@/spa/atoms/app';--// Import after mocks are registered.-import CacheHydrationGate from './CacheHydrationGate';--// --- controllable inputs ------------------------------------------------------let mockScope = 'anon:personal';--vi.mock('@/libs/swr/useCacheScope', () => ({- useCacheScope: () => mockScope,-}));--vi.mock('@/libs/bootTiming', () => ({- bootTiming: { mark: vi.fn() },-}));--const ALL_SCOPES = ['anon:personal', 'u1:personal', 'u2:personal'];-const resetHydration = () => ALL_SCOPES.forEach((s) => cacheHydration.markPending(s));--const Child = () => <div data-testid="app">app content</div>;--const renderGate = () =>- render(- <CacheHydrationGate>- <Child />- </CacheHydrationGate>,- );--beforeEach(() => {- mockScope = 'anon:personal';- resetHydration();- setAppPainted(false);- setAppReady(true);-});--afterEach(() => {- window.history.replaceState(null, '', '/');- resetHydration();- setAppPainted(false);- setAppReady(false);- vi.useRealTimers();-});--describe('CacheHydrationGate', () => {- it('blocks first paint (renders nothing) until the active scope is hydrated', () => {- renderGate();- // not ready yet β blocked- expect(screen.queryByTestId('app')).toBeNull();- expect(getAppPainted()).toBe(false);-- act(() => {- cacheHydration.markReady('anon:personal');- });-- expect(screen.queryByTestId('app')).not.toBeNull();- // signals the boot shell to tear down once the real app has committed- expect(getAppPainted()).toBe(true);- });-- it('CORE: after first release, a scope change does NOT unmount the app (no white-screen)', () => {- renderGate();- act(() => {- cacheHydration.markReady('anon:personal');- });- expect(screen.queryByTestId('app')).not.toBeNull();-- // Simulate the session resolving a different scope whose cache is NOT yet- // hydrated. The old key={scope} remount would blank the whole tree here.- act(() => {- mockScope = 'u1:personal';- cacheHydration.markPending('u1:personal'); // new scope not ready- cacheHydration.markReady('anon:personal'); // force a re-render via the store- });-- // App stays mounted throughout the scope change.- expect(screen.queryByTestId('app')).not.toBeNull();-- act(() => {- cacheHydration.markReady('u1:personal');- });- expect(screen.queryByTestId('app')).not.toBeNull();- });-- it('releases the moment the active scope is ready β no identity round-trip wait', () => {- // The persisted activeScopeKey means the hydrated scope is already the real- // user partition, so the gate must not wait for auth/userId β only `ready`.- renderGate();- expect(screen.queryByTestId('app')).toBeNull();-- act(() => {- cacheHydration.markReady('anon:personal');- });- expect(screen.queryByTestId('app')).not.toBeNull();- });-- it('does NOT paint early while hydration is still in flight (no empty-chat + CLS)', () => {- // A heavy account's hydration outruns the former 1500ms window; painting then- // orphans any consumer that subscribes against the still-empty Map.- vi.useFakeTimers();- renderGate();- expect(screen.queryByTestId('app')).toBeNull();-- act(() => {- vi.advanceTimersByTime(2500); // well past 1500ms, still not ready- });- expect(screen.queryByTestId('app')).toBeNull();-- act(() => {- cacheHydration.markReady('anon:personal');- });- expect(screen.queryByTestId('app')).not.toBeNull();- });-- it('tears down the static loading screen for entries that mount no boot shell', () => {- // The Electron popup entry renders no `BootShell`, and `popup.html` ships an- // opaque z-index 99999 `#loading-screen`. `useBootShell` is what normally- // removes it, so the gate has to be the backstop or the popup stays covered- // forever after hydration.- const loadingScreen = document.createElement('div');- loadingScreen.id = 'loading-screen';- document.body.append(loadingScreen);-- renderGate();- expect(document.getElementById('loading-screen')).not.toBeNull();-- act(() => {- cacheHydration.markReady('anon:personal');- });-- expect(document.getElementById('loading-screen')).toBeNull();- });-- it('holds the static loading screen until the app can actually paint', () => {- // Hydration can finish before initialization. In that window `AppLayer`- // renders null and the boot shell's phase is still `hidden` (it needs BOTH- // signals, and the 200ms timer has not fired), so tearing the splash down on- // release alone leaves the window blank.- setAppReady(false);- const loadingScreen = document.createElement('div');- loadingScreen.id = 'loading-screen';- document.body.append(loadingScreen);-- renderGate();- act(() => {- cacheHydration.markReady('anon:personal');- });-- expect(document.getElementById('loading-screen')).not.toBeNull();-- act(() => {- setAppReady(true);- });-- expect(document.getElementById('loading-screen')).toBeNull();- });-- it('hung-hydration backstop still releases if ready never fires', () => {- vi.useFakeTimers();- renderGate();- expect(screen.queryByTestId('app')).toBeNull();-- act(() => {- vi.advanceTimersByTime(8000);- });- expect(screen.queryByTestId('app')).not.toBeNull();- });-});diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsxdeleted file mode 100644index 5cb95e6bbd5..00000000000--- a/src/layout/GlobalProvider/CacheHydrationGate.tsx+++ /dev/null@@ -1,116 +0,0 @@-'use client';--import type { PropsWithChildren } from 'react';-import { useEffect, useLayoutEffect, useState, useSyncExternalStore } from 'react';--import { bootTiming } from '@/libs/bootTiming';-import { cacheHydration } from '@/libs/swr/cacheHydration';-import { useCacheScope } from '@/libs/swr/useCacheScope';-import { setAppPainted, useAppReady } from '@/spa/atoms/app';-import { removeStaticLoadingScreen } from '@/spa/loadingScreen';--// first-write-wins: only the very first paint records the boot timing mark.-let firstPaintMarked = false;--// Pure hung-hydration backstop β NOT a "boot is slow, paint anyway" timer.-// `loadIdb` always signals `ready` from its `finally` (even on an IndexedDB-// error), so legitimate hydration β however large the cached partition β-// resolves `ready` on its own and releases the gate before this fires; the only-// thing it catches is IndexedDB never responding, where there is no cache to-// wait for. A short window (the former 1500ms) misfires on a heavy account whose-// hydration outruns it: the gate paints an EMPTY app before the cache is in the-// Map, and a consumer that subscribes to its key then is orphaned forever (SWR-// does not observe the later direct Map insert), so it waits for the network β-// the sustained cold-open skeleton. See `coldHydrationGate.integration.test.tsx`-// (BUGβFIX) and `libs/swr/coldHydrationRace.test.tsx`.-const HYDRATION_TIMEOUT = 8000;--/**- * Blocks the first paint until the active scope's IndexedDB cache has hydrated,- * so the app never flashes empty on cold boot β the static `loading-screen`- * overlay and then `BootShell` cover exactly this window, and releasing here is- * what signals `appPainted` to tear them down.- *- * This is a one-way latch: once released it never blanks again. A later scope- * change (anonymous β signed-in, or workspace switch) re-hydrates the SWR cache- * *in place* via `Query.tsx`'s `reloadScope()`, keeping the current tree mounted- * while the new scope's data swaps in underneath.- *- * The active scope is known synchronously at boot from the persisted- * `activeScopeKey` (the last-known `${userId}:${workspace}`), so the provider- * hydrates the *real* user partition in parallel with the session check β the- * gate only waits for that hydration (`ready`), not for the identity- * round-trip. That parallelism is what restores instant-from-cache first paint.- * Writes made before the session confirms the scope are quarantined by the- * cache provider (`isEphemeralScope`), so the optimistic window can't orphan or- * pollute a partition. The timeout is a pure hung-hydration backstop (see- * `HYDRATION_TIMEOUT`): the gate otherwise waits for real `ready`, so a heavy- * account pays a slightly longer loading-screen ONCE at boot and then every- * agent/topic it opens is served straight from the fully-hydrated in-memory- * cache β no per-topic skeleton, no layout shift.- */-const CacheHydrationGate = ({ children }: PropsWithChildren) => {- const scope = useCacheScope();- const appReady = useAppReady();-- const ready = useSyncExternalStore(- cacheHydration.subscribe,- () => cacheHydration.isReady(scope),- () => true,- );-- const [released, setReleased] = useState(false);- const [timedOut, setTimedOut] = useState(false);-- // Only the first hydration is time-boxed; after release the latch holds.- useEffect(() => {- if (released) return;- const timer = setTimeout(() => setTimedOut(true), HYDRATION_TIMEOUT);- return () => clearTimeout(timer);- }, [released]);-- useEffect(() => {- if (released) return;- // Release the moment the active scope's cache has hydrated β the persisted- // activeScopeKey means that's already the real user partition, so this paints- // straight from cache. The timeout backstop guards a hung hydration only.- if (ready || timedOut) setReleased(true);- }, [ready, timedOut, released]);-- useLayoutEffect(() => {- if (!released) return;-- if (!firstPaintMarked) {- firstPaintMarked = true;- bootTiming.mark('first-paint');- }- // Runs after `children` have committed, so the boot shell only tears down- // once the real app is already in the DOM.- setAppPainted(true);- }, [released]);-- // Backstop for entries that mount no `BootShell` (the Electron popup window,- // whose `popup.html` ships a z-index 99999 scrim with `pointer-events: auto`):- // the shell normally owns this removal, so without a backstop the popup stays- // dimmed AND swallows every click.- //- // `appReady` is part of the condition, not decoration. Hydration can finish- // before initialization, and in that window `AppLayer` still renders null while- // `resolveBootShellPhase` is `hidden` (it needs BOTH signals for `done`, and- // the 200ms timer has not fired) β so the shell is not up either. Removing the- // splash on `released` alone blanks the window until whichever lands first,- // and the shell timer has been measured arriving 1153ms late on an Electron- // cold boot. Gating on `appReady` means `AppLayer` is rendering the outlet, so- // the route's own fallback is guaranteed to be on screen.- useLayoutEffect(() => {- if (!released || !appReady) return;-- removeStaticLoadingScreen();- }, [released, appReady]);-- if (!released) return null;-- return <>{children}</>;-};--export default CacheHydrationGate;diff --git a/src/layout/GlobalProvider/Query.test.ts b/src/layout/GlobalProvider/Query.test.tsnew file mode 100644index 00000000000..78531eb4495--- /dev/null+++ b/src/layout/GlobalProvider/Query.test.ts@@ -0,0 +1,114 @@+/**+ * @vitest-environment happy-dom+ *+ * SWR keeps request state in memory only. The removed persistence layer (a+ * tiered SWR cache provider writing to the local database `swr-cache`+ * collection and `lobechat-swr-cache:*` localStorage entries) must not come+ * back: the app's provider installs no cache provider and writes nothing.+ */+import 'fake-indexeddb/auto';++import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { useSyncExternalStore } from 'react';+import useSWR, { useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { localDatabase } from '@/libs/localDatabase';++import QueryProvider from './Query';++const scopeStore = vi.hoisted(() => {+ const listeners = new Set<() => void>();+ let scope = 'u1:personal';+ return {+ get: () => scope,+ set: (next: string) => {+ scope = next;+ for (const listener of listeners) listener();+ },+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+});++vi.mock('@/libs/swr/useCacheScope', () => ({+ getCacheScope: scopeStore.get,+ isScopeTrusted: () => true,+ useCacheScope: () => useSyncExternalStore(scopeStore.subscribe, scopeStore.get),+ useIsScopeTrusted: () => true,+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaQuery: { Provider: ({ children }: PropsWithChildren) => children },+ lambdaQueryClient: {},+}));++// Keys from every domain the removed provider used to persist.+const FORMERLY_PERSISTED_KEYS = [+ ['message:list', { agentId: 'agt_1', topicId: 'tpc_1' }, 2],+ ['topic:search', 'weather'],+ ['agent:list', true],+ ['recent:topicList', 10],+ ['taskTemplate:daily', 'en-US'],+ ['modelConfig:lobehub'],+] as const;++const fetchPayload = async () => ({ rows: ['payload'] });++beforeEach(() => {+ scopeStore.set('u1:personal');+ localStorage.clear();+});++afterEach(async () => {+ vi.useRealTimers();+ await localDatabase.deleteByPrefix('swr-cache', '');+ localStorage.clear();+});++describe('QueryProvider SWR cache', () => {+ it('installs no SWR cache provider: hooks use the default in-memory cache', () => {+ const outside = renderHook(() => useSWRConfig().cache);+ const inside = renderHook(() => useSWRConfig().cache, { wrapper: QueryProvider });++ expect(inside.result.current).toBe(outside.result.current);+ });++ it('persists nothing to the local database or localStorage', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['setTimeout', 'clearTimeout'] });++ const { result } = renderHook(+ () => FORMERLY_PERSISTED_KEYS.map((key) => useSWR(key, fetchPayload).data),+ { wrapper: QueryProvider },+ );++ await waitFor(() => expect(result.current.every(Boolean)).toBe(true));+ // Well past the removed provider's 2s write debounce.+ await act(() => vi.advanceTimersByTimeAsync(10_000));++ expect(await localDatabase.entriesByPrefix('swr-cache', '')).toEqual([]);+ expect(Object.keys(localStorage).filter((key) => key.includes('swr-cache'))).toEqual([]);+ });++ it('drops cached values when the scope changes, so the previous scope never repaints', async () => {+ let resolveSecond: ((value: string) => void) | undefined;+ const fetcher = vi+ .fn<() => Promise<string>>()+ .mockResolvedValueOnce('u1 data')+ .mockImplementationOnce(() => new Promise((resolve) => (resolveSecond = resolve)));++ const { result } = renderHook(() => useSWR(['agent:scopeStable', 'agt_1'], fetcher).data, {+ wrapper: QueryProvider,+ });+ await waitFor(() => expect(result.current).toBe('u1 data'));++ act(() => scopeStore.set('u2:personal'));++ await waitFor(() => expect(result.current).toBeUndefined());+ await act(async () => resolveSecond?.('u2 data'));+ await waitFor(() => expect(result.current).toBe('u2 data'));+ });+});diff --git a/src/layout/GlobalProvider/Query.tsx b/src/layout/GlobalProvider/Query.tsxindex 1f1fad92ce7..2865e47d87f 100644--- a/src/layout/GlobalProvider/Query.tsx+++ b/src/layout/GlobalProvider/Query.tsx@@ -3,12 +3,9 @@import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { PropsWithChildren } from 'react';import React, { useLayoutEffect, useRef, useState } from 'react';-import { type Cache, SWRConfig } from 'swr';import { mutate } from '@/libs/swr';-import { cacheHydration } from '@/libs/swr/cacheHydration';-import { swrCacheProvider } from '@/libs/swr/localStorageProvider';-import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';+import { useCacheScope } from '@/libs/swr/useCacheScope';import { lambdaQuery, lambdaQueryClient } from '@/libs/trpc/client';import SWRMutateInitializer from './SWRMutateInitializer';@@ -20,46 +17,29 @@ const QueryProvider = ({ children }: PropsWithChildren) => {typeof lambdaQuery.Provider>['queryClient'];- // Keep the SWR cache provider inside SWRConfig's lifecycle. SWR registers- // global state for the returned Map during Provider render, so creating and- // hydrating that same Map from SPA bootstrap can leave hooks with an- // unregistered cache after remounts.- const [provider] = useState(() => swrCacheProvider(getCacheScope, cacheHydration.markReady));-+ // No SWR cache provider: SWR keeps request state in its default in-memory+ // cache and persists nothing (server data the UI paints lives in replicas,+ // `@/libs/replica`). Keys embed the workspace (`augmentKey`) but never the+ // user, so on a scope change (sign-in, account or workspace switch) drop+ // every cached value and revalidate the mounted consumers: none keeps+ // rendering the previous scope's data.const scope = useCacheScope();const lastScope = useRef(scope);useLayoutEffect(() => {if (lastScope.current === scope) return;lastScope.current = scope;- cacheHydration.markPending(scope);- const reloadScope = provider.reloadScope;- if (!reloadScope) return;-- // `reloadScope()` swaps the provider Map's persisted entries to the new- // scope in place, but SWR does not observe direct Map mutation. Mounted- // consumers whose key does not change across the swap (e.g. keys embedding- // only a scope-stable agent/topic id, since `augmentKey` adds workspaceId- // but never userId) would otherwise keep rendering the previous scope's- // data until an incidental revalidation. Broadcast a global revalidation- // once the swap resolves so every consumer re-reads under the new scope β- // the CacheHydrationGate latch keeps the tree mounted, so this replaces the- // correctness role the old `key={scope}` remount used to play.- void reloadScope()- .then(() => mutate(() => true, undefined, { revalidate: true }))- .catch((error) => {- console.error('[SWR Cache] failed to reload scope', error);- });- }, [scope, provider]);+ void mutate(() => true, undefined, { revalidate: true }).catch((error) => {+ console.error('[SWR] failed to reset the cache on scope change', error);+ });+ }, [scope]);return (- <SWRConfig value={{ provider: provider as unknown as (cache: Readonly<Cache>) => Cache }}>- <SWRMutateInitializer>- <lambdaQuery.Provider client={lambdaQueryClient} queryClient={providerQueryClient}>- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- </lambdaQuery.Provider>- </SWRMutateInitializer>- </SWRConfig>+ <SWRMutateInitializer>+ <lambdaQuery.Provider client={lambdaQueryClient} queryClient={providerQueryClient}>+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ </lambdaQuery.Provider>+ </SWRMutateInitializer>);};diff --git a/src/layout/GlobalProvider/StoreInitialization.tsx b/src/layout/GlobalProvider/StoreInitialization.tsxindex 35321bdcaab..df549aea3d8 100644--- a/src/layout/GlobalProvider/StoreInitialization.tsx+++ b/src/layout/GlobalProvider/StoreInitialization.tsx@@ -18,7 +18,7 @@ import { useUserStateRedirect } from './useUserStateRedirect';const DeferredStoreInitialization = lazy(() => import('./DeferredStoreInitialization'));-/** Subscribe only after the durable cache is hydrated by CacheHydrationGate. */+/** Initializes the builtin Inbox agent inside the app tree (`PrePaintSignal`). */export const BuiltinAgentInitialization = () => {const isLogin = useUserStore(authSelectors.isLogin);const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);diff --git a/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsx b/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsxdeleted file mode 100644index 981d961191f..00000000000--- a/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsx+++ /dev/null@@ -1,162 +0,0 @@-/**- * @vitest-environment happy-dom- *- * Integration: CacheHydrationGate + the real tiered provider + a consumer.- *- * The gate's whole job is to guarantee mount-after-hydrate: block first paint- * until the active scope's IndexedDB cache has hydrated, so every consumer- * mounted under it reads a populated Map. The pure-unit repro- * (`libs/swr/coldHydrationRace.test.tsx`) shows a consumer that subscribes- * before hydration is permanently orphaned β so if the gate paints early, the- * cold-open skeleton returns. This exercises that end to end.- */-import { act, render, renderHook, waitFor } from '@testing-library/react';-import type { ReactNode } from 'react';-import { createElement } from 'react';-import useSWR, { type Cache, SWRConfig, unstable_serialize } from 'swr';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { cacheHydration } from '@/libs/swr/cacheHydration';-import { localDataCache } from '@/libs/swr/localDataCache';-import { createCacheProvider, type ScopedSWRProvider } from '@/libs/swr/localStorageProvider';--import CacheHydrationGate from './CacheHydrationGate';--let mockScope = 'anon:personal';-vi.mock('@/libs/swr/useCacheScope', () => ({ useCacheScope: () => mockScope }));-vi.mock('@/libs/bootTiming', () => ({ bootTiming: { mark: vi.fn(), recordSpan: vi.fn() } }));--const SCOPE = 'u1:personal';-const KEY = ['MSGS', 'topic-cold'];-const CACHED = [{ id: 'm1', text: 'cached on disk' }];-const never = () => new Promise<never>(() => {}); // never resolves β only cache can serve--// A top-level probe so we can observe what an under-gate consumer reads.-let probed: unknown;-const Probe = () => {- const { data } = useSWR(KEY, never);- probed = data;- return null;-};--const asProvider = (p: unknown) => p as unknown as (c: Readonly<Cache>) => Cache;-const wrap =- (provider: unknown) =>- ({ children }: { children: ReactNode }) =>- createElement(SWRConfig, { value: { provider: asProvider(provider) } }, children);--const makeProvider = (): ScopedSWRProvider =>- createCacheProvider({- debounceMs: 5,- getScope: () => SCOPE,- idbPatterns: ['MSGS'],- localPatterns: [],- onScopeHydrated: cacheHydration.markReady,- });--const seedDisk = async () => {- const p = makeProvider();- const r = renderHook(() => useSWR(KEY, () => Promise.resolve(CACHED)), { wrapper: wrap(p) });- await waitFor(() => expect(r.result.current.data).toEqual(CACHED));- await waitFor(async () =>- expect((await localDataCache.entriesByScope(SCOPE)).length).toBeGreaterThan(0),- );- r.unmount();- cacheHydration.markPending(SCOPE);-};--describe('CacheHydrationGate + provider + consumer', () => {- beforeEach(() => {- mockScope = SCOPE;- probed = undefined;- cacheHydration.markPending(SCOPE);- });- afterEach(async () => {- cacheHydration.markPending(SCOPE);- await localDataCache.clearScope(SCOPE);- });-- it('a consumer under the gate reads the cache on first paint (no network)', async () => {- await seedDisk();- const provider = makeProvider();-- render(- createElement(- SWRConfig,- { value: { provider: asProvider(provider) } },- createElement(CacheHydrationGate, null, createElement(Probe)),- ),- );-- // The gate blocks the consumer until hydration completes; once it releases,- // the consumer must already see the cached data β never undefined-then-network.- await waitFor(() => expect(probed).toEqual(CACHED));- });-- it('DECISIVE: an early orphaned subscriber does NOT poison the key for a later one', async () => {- await seedDisk();- const provider = makeProvider();-- // an EARLY consumer subscribes before hydration β miss (orphaned)- const early = renderHook(() => useSWR(KEY, never), { wrapper: wrap(provider) });- expect(early.result.current.data).toBeUndefined();-- await act(async () => {- await provider.hydrateScope?.();- });- expect(early.result.current.data).toBeUndefined(); // early one stays orphaned-- // a LATER consumer subscribes AFTER hydration and reads the populated Map β it- // HITS. So the gate (which makes the real consumer a "late" subscriber by- // blocking it until `ready`) is sufficient on its own; the fix is to guarantee- // the gate releases strictly AFTER hydration.- const late = renderHook(() => useSWR(KEY, never), { wrapper: wrap(provider) });- expect(late.result.current.data).toEqual(CACHED);- });-- it('BUGβFIX: slow hydration must NOT early-release the gate (else the consumer is orphaned)', () => {- vi.useFakeTimers();- try {- // A plain Map provider whose hydration timing we drive by hand, to model a- // heavy account whose IndexedDB hydration outruns the gate's timeout.- const map = new Map<string, unknown>();-- render(- createElement(- SWRConfig,- { value: { provider: asProvider(() => map) } },- createElement(CacheHydrationGate, null, createElement(Probe)),- ),- );-- // Hydration is still in flight well past the old 1500ms window. The gate- // must keep blocking β the consumer must not have subscribed yet (subscribing- // now, against an empty Map, orphans it forever).- act(() => {- vi.advanceTimersByTime(3000);- });- expect(probed).toBeUndefined();-- // Hydration finishes: the row lands in the Map AND the scope is marked ready.- act(() => {- map.set(unstable_serialize(KEY), { data: CACHED });- cacheHydration.markReady(SCOPE);- });-- // Gate releases β the consumer mounts AFTER hydration β reads the populated- // Map. On the buggy 1500ms gate it mounted empty at 1500ms and is orphaned,- // so this stays undefined.- expect(probed).toEqual(CACHED);- } finally {- vi.useRealTimers();- }- });-- // The localβremote handoff that cache-first relies on β the consumer shows the- // cached list, then SWR's revalidation replaces it with the fresh server data β- // is standard stale-while-revalidate and is already proven end to end by- // `libs/swr/cacheProvider.integration.test.tsx` ("persists fetched data β¦ and- // serves it locally on reload", then the fresh server value flows through). The- // gate fix only changes release *timing*, not the revalidation/onData path, so- // that reconciliation is unchanged from a warm navigation.-});diff --git a/src/layout/SPAGlobalProvider/index.test.tsx b/src/layout/SPAGlobalProvider/index.test.tsxindex 5aa64dc664c..13cd1554640 100644--- a/src/layout/SPAGlobalProvider/index.test.tsx+++ b/src/layout/SPAGlobalProvider/index.test.tsx@@ -2,10 +2,10 @@* @vitest-environment happy-dom*/import { render, screen, waitFor } from '@testing-library/react';-import { type ReactNode, useEffect } from 'react';+import { type ReactNode, useEffect, useLayoutEffect } from 'react';import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';-import { setPostRenderReady } from '@/spa/atoms/app';+import { getAppPainted, setAppPainted, setPostRenderReady } from '@/spa/atoms/app';import { setDevDockUnlocked } from '@/utils/devDockUnlock';import type SPAGlobalProviderComponent from './index';@@ -13,14 +13,11 @@ import { type DevDockLayout as DevDockLayoutComponent } from './index';let SPAGlobalProvider: typeof SPAGlobalProviderComponent;let DevDockLayout: typeof DevDockLayoutComponent;-const { cacheGateReleased, canAccessDevDock, devDockRenderError, initializeBuiltin } = vi.hoisted(- () => ({- cacheGateReleased: { current: true },- canAccessDevDock: vi.fn(() => false),- devDockRenderError: { current: null as Error | null },- initializeBuiltin: vi.fn(() => null),- }),-);+const { canAccessDevDock, devDockRenderError, initializeBuiltin } = vi.hoisted(() => ({+ canAccessDevDock: vi.fn(() => false),+ devDockRenderError: { current: null as Error | null },+ initializeBuiltin: vi.fn(() => null),+}));vi.mock('@lobehub/ui', async (importOriginal) => {const React = await import('react');@@ -94,15 +91,6 @@ vi.mock('@/layout/GlobalProvider/AppTheme', async () => {};});-vi.mock('@/layout/GlobalProvider/CacheHydrationGate', async () => {- const React = await import('react');-- return {- default: ({ children }: { children?: ReactNode }) =>- cacheGateReleased.current ? React.createElement(React.Fragment, null, children) : null,- };-});-vi.mock('@/layout/GlobalProvider/DynamicFavicon', () => ({default: () => <div data-testid="dynamic-favicon" />,}));@@ -175,7 +163,7 @@ describe('SPAGlobalProvider', () => {beforeEach(() => {initializeBuiltin.mockClear();- cacheGateReleased.current = true;+ setAppPainted(false);canAccessDevDock.mockReturnValue(false);devDockRenderError.current = null;setDevDockUnlocked(false);@@ -183,23 +171,35 @@ describe('SPAGlobalProvider', () => {setPostRenderReady(false);});- it('defers builtin subscriptions until persistent cache hydration has completed', () => {- cacheGateReleased.current = false;- const { unmount } = render(+ it('renders the app and signals first paint on the first commit, with no cache hydration wait', () => {+ render(<SPAGlobalProvider>- <div />+ <div data-testid="spa-route-content" /></SPAGlobalProvider>,);- expect(initializeBuiltin).not.toHaveBeenCalled();- unmount();- cacheGateReleased.current = true;+ expect(screen.getByTestId('spa-route-content')).toBeInTheDocument();+ expect(initializeBuiltin).toHaveBeenCalled();+ expect(getAppPainted()).toBe(true);+ });++ it('reports the first paint only after the route content has committed', () => {+ let paintedWhenContentCommitted: boolean | undefined;+ const RouteContent = () => {+ useLayoutEffect(() => {+ paintedWhenContentCommitted = getAppPainted();+ }, []);+ return null;+ };+render(<SPAGlobalProvider>- <div />+ <RouteContent /></SPAGlobalProvider>,);- expect(initializeBuiltin).toHaveBeenCalled();++ expect(paintedWhenContentCommitted).toBe(false);+ expect(getAppPainted()).toBe(true);});afterEach(() => {diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsxindex 4a750003c25..762de100616 100644--- a/src/layout/SPAGlobalProvider/index.tsx+++ b/src/layout/SPAGlobalProvider/index.tsx@@ -11,7 +11,6 @@ import { useDevDockMounted } from '@/hooks/useDevDockMounted';import AuthProvider from '@/layout/AuthProvider';import { MarketAuthProvider } from '@/layout/AuthProvider/MarketAuth';import AppTheme from '@/layout/GlobalProvider/AppTheme';-import CacheHydrationGate from '@/layout/GlobalProvider/CacheHydrationGate';import { FaviconProvider } from '@/layout/GlobalProvider/FaviconProvider';import { GroupWizardProvider } from '@/layout/GlobalProvider/GroupWizardProvider';import QueryProvider from '@/layout/GlobalProvider/Query';@@ -20,6 +19,7 @@ import StoreInitialization, {BuiltinAgentInitialization,} from '@/layout/GlobalProvider/StoreInitialization';import { registerNativeContextMenuInterceptor } from '@/libs/contextMenu';+import PrePaintSignal from '@/libs/replica/PrePaintSignal';import { usePostRenderReady } from '@/spa/atoms/app';import { ServerConfigStoreProvider } from '@/store/serverConfig/Provider';import type { SPAServerConfig } from '@/types/spaServerConfig';@@ -98,10 +98,10 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {<LazyMotion features={domMax}><TooltipGroup layoutAnimation={false}><LobeAnalyticsProviderWrapper>- <CacheHydrationGate>+ <PrePaintSignal><BuiltinAgentInitialization /><DevDockLayout>{children}</DevDockLayout>- </CacheHydrationGate>+ </PrePaintSignal></LobeAnalyticsProviderWrapper></TooltipGroup><ModalHost />diff --git a/src/libs/localDatabase/ARCHITECTURE.md b/src/libs/localDatabase/ARCHITECTURE.mdindex 13abc9d2397..16a8774c3b8 100644--- a/src/libs/localDatabase/ARCHITECTURE.md+++ b/src/libs/localDatabase/ARCHITECTURE.md@@ -1,7 +1,12 @@# Local Database Architecture-The local database is a runtime-neutral persistence boundary. SWR cache persistence is its first-consumer, but the database contract and adapters do not depend on SWR.+The local database is a runtime-neutral persistence boundary. Its consumer is the replica storage+(`src/libs/replica/storage.ts`, collection `query-projections`), which persists the local copies+of server data the UI paints. The database contract and adapters do not depend on any consumer.++SWR does not persist anything: it keeps request state in memory only. The former SWR cache+collection (`swr-cache`) and its `lobechat-swr-cache:*` localStorage entries are removed once+per install by `src/spa/initialize/purgeLegacySWRCache.ts`.```textRepository / feature@@ -24,7 +29,7 @@ IndexedDB Electron IPC| Layer | Responsibility || -------------------------------- | --------------------------------------------------------------------- || `src/libs/localDatabase` | Runtime-neutral contract, adapter registration, IndexedDB adapter |-| `src/libs/swr/localDataCache.ts` | SWR-specific repository and cache-key semantics |+| `src/libs/replica/storage.ts` | Replica row storage (`query-projections`) and its key semantics || `apps/desktop/src/main/database` | SQLite client, Drizzle schema, and migration execution || `LocalDatabaseSrv` | Collection-scoped reads and writes expressed through Drizzle builders || Electron IPC | Serialization and process-boundary transport only |diff --git a/src/libs/replica/PrePaintSignal.tsx b/src/libs/replica/PrePaintSignal.tsxnew file mode 100644index 00000000000..cf768fab700--- /dev/null+++ b/src/libs/replica/PrePaintSignal.tsx@@ -0,0 +1,14 @@+'use client';++import type { PropsWithChildren } from 'react';++import { usePrePaintSignal } from './usePrePaintSignal';++/** Renders the app tree at once and reports its first paint (see `usePrePaintSignal`). */+const PrePaintSignal = ({ children }: PropsWithChildren) => {+ usePrePaintSignal();++ return <>{children}</>;+};++export default PrePaintSignal;diff --git a/src/libs/replica/usePrePaintSignal.test.ts b/src/libs/replica/usePrePaintSignal.test.tsnew file mode 100644index 00000000000..93fc7abc528--- /dev/null+++ b/src/libs/replica/usePrePaintSignal.test.ts@@ -0,0 +1,76 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getAppPainted, setAppPainted, setAppReady } from '@/spa/atoms/app';++import { usePrePaintSignal } from './usePrePaintSignal';++vi.mock('@/libs/bootTiming', () => ({+ bootTiming: { mark: vi.fn() },+}));++const mountLoadingScreen = () => {+ const loadingScreen = document.createElement('div');+ loadingScreen.id = 'loading-screen';+ document.body.append(loadingScreen);+};++beforeEach(() => {+ setAppPainted(false);+ setAppReady(true);+});++afterEach(() => {+ document.getElementById('loading-screen')?.remove();+ setAppPainted(false);+ setAppReady(false);+});++describe('usePrePaintSignal', () => {+ it('reports the first paint on the first commit, without waiting for any cache hydration', () => {+ renderHook(() => usePrePaintSignal());++ expect(getAppPainted()).toBe(true);+ });++ it('records the first-paint boot mark once per page load', async () => {+ // The mark is first-write-wins for the module, so load a fresh copy.+ vi.resetModules();+ const { bootTiming } = await import('@/libs/bootTiming');+ const { usePrePaintSignal: freshUsePrePaintSignal } = await import('./usePrePaintSignal');++ renderHook(() => freshUsePrePaintSignal()).unmount();+ renderHook(() => freshUsePrePaintSignal());++ expect(+ vi.mocked(bootTiming.mark).mock.calls.filter(([name]) => name === 'first-paint'),+ ).toEqual([['first-paint']]);+ });++ it('tears down the static loading screen for entries that mount no boot shell', () => {+ // The Electron popup renders no `BootShell`, and `popup.html` ships an+ // opaque z-index 99999 `#loading-screen` that swallows clicks.+ mountLoadingScreen();++ renderHook(() => usePrePaintSignal());++ expect(document.getElementById('loading-screen')).toBeNull();+ });++ it('holds the static loading screen until initialization is done', () => {+ // Before `appReady`, `AppLayer` renders null and the boot shell may still+ // be hidden: removing the splash then would blank the window.+ setAppReady(false);+ mountLoadingScreen();++ renderHook(() => usePrePaintSignal());+ expect(document.getElementById('loading-screen')).not.toBeNull();++ act(() => setAppReady(true));++ expect(document.getElementById('loading-screen')).toBeNull();+ });+});diff --git a/src/libs/replica/usePrePaintSignal.ts b/src/libs/replica/usePrePaintSignal.tsnew file mode 100644index 00000000000..862d006ff31--- /dev/null+++ b/src/libs/replica/usePrePaintSignal.ts@@ -0,0 +1,45 @@+import { useLayoutEffect } from 'react';++import { bootTiming } from '@/libs/bootTiming';+import { setAppPainted, useAppReady } from '@/spa/atoms/app';+import { removeStaticLoadingScreen } from '@/spa/loadingScreen';++// first-write-wins: only the very first paint records the boot timing mark.+let firstPaintMarked = false;++/**+ * Signals the app's first paint to the boot shell. Call it from the component+ * that wraps the app tree: layout effects run after the children's, so the+ * signals fire once the app is in the DOM.+ *+ * Nothing is awaited here: server data the UI paints lives in replicas, and+ * each route loader hydrates its replica before the route renders (bounded by+ * `PRE_PAINT_HYDRATE_TIMEOUT`, see `./prePaint`). By the time the tree commits,+ * the first screen is already drawn from the local projection, so this only+ * reports that commit:+ *+ * - `first-paint` boot timing mark and `appPainted`, so `BootShell` tears down+ * over a rendered app;+ * - removal of the static `loading-screen` once `appReady` is set as well.+ * Entries that mount no `BootShell` (the Electron popup, whose `popup.html`+ * ships a click-swallowing scrim) rely on this. Before `appReady`,+ * `AppLayer` still renders null and the shell may be hidden, so removing+ * the splash earlier would blank the window.+ */+export const usePrePaintSignal = (): void => {+ const appReady = useAppReady();++ useLayoutEffect(() => {+ if (!firstPaintMarked) {+ firstPaintMarked = true;+ bootTiming.mark('first-paint');+ }+ setAppPainted(true);+ }, []);++ useLayoutEffect(() => {+ if (!appReady) return;++ removeStaticLoadingScreen();+ }, [appReady]);+};diff --git a/src/libs/swr/cacheHydration.test.ts b/src/libs/swr/cacheHydration.test.tsdeleted file mode 100644index 44ff971b2f1..00000000000--- a/src/libs/swr/cacheHydration.test.ts+++ /dev/null@@ -1,78 +0,0 @@-import { afterEach, describe, expect, it, vi } from 'vitest';--import { cacheHydration, isCacheHydrationBlocked } from './cacheHydration';--describe('cacheHydration', () => {- const scopes = ['anon:personal', 'u1:personal'];-- afterEach(() => {- vi.restoreAllMocks();- scopes.forEach((scope) => cacheHydration.markPending(scope));- });-- it('marks a ready scope as pending before reload completes', () => {- const listener = vi.fn();- const unsubscribe = cacheHydration.subscribe(listener);-- cacheHydration.markReady('anon:personal');- expect(cacheHydration.isReady('anon:personal')).toBe(true);-- cacheHydration.markPending('anon:personal');-- expect(cacheHydration.isReady('anon:personal')).toBe(false);- expect(listener).toHaveBeenCalledTimes(2);-- unsubscribe();- });-- it('blocks a returned scope until it is released after the latest hydration', () => {- cacheHydration.markReady('anon:personal');- cacheHydration.markReady('u1:personal');-- cacheHydration.markPending('anon:personal');-- expect(- isCacheHydrationBlocked({- isAuthLoaded: true,- ready: cacheHydration.isReady('anon:personal'),- released: false,- scope: 'anon:personal',- timedOutScope: null,- }),- ).toBe(true);-- cacheHydration.markReady('anon:personal');-- expect(- isCacheHydrationBlocked({- isAuthLoaded: true,- ready: cacheHydration.isReady('anon:personal'),- released: true,- scope: 'anon:personal',- timedOutScope: null,- }),- ).toBe(false);- });-- it('does not let a timeout from another scope release the current scope', () => {- expect(- isCacheHydrationBlocked({- isAuthLoaded: true,- ready: false,- released: true,- scope: 'u1:personal',- timedOutScope: 'anon:personal',- }),- ).toBe(true);-- expect(- isCacheHydrationBlocked({- isAuthLoaded: true,- ready: false,- released: true,- scope: 'u1:personal',- timedOutScope: 'u1:personal',- }),- ).toBe(false);- });-});diff --git a/src/libs/swr/cacheHydration.ts b/src/libs/swr/cacheHydration.tsdeleted file mode 100644index 0eb26a20722..00000000000--- a/src/libs/swr/cacheHydration.ts+++ /dev/null@@ -1,55 +0,0 @@-/**- * Tracks which identity scopes have finished hydrating the IndexedDB SWR tier.- */-interface CacheHydrationBlockState {- isAuthLoaded: boolean;- ready: boolean;- released: boolean;- scope: string;- timedOutScope: string | null;-}--const readyScopes = new Set<string>();-const listeners = new Set<() => void>();--const emit = () => {- for (const listener of listeners) listener();-};--const markPending = (scope: string): void => {- if (!readyScopes.delete(scope)) return;-- emit();-};--export const isCacheHydrationBlocked = ({- isAuthLoaded,- ready,- released,- scope,- timedOutScope,-}: CacheHydrationBlockState) => {- if (!released) return true;-- return !(isAuthLoaded && ready) && timedOutScope !== scope;-};--export const cacheHydration = {- isReady: (scope: string): boolean => readyScopes.has(scope),-- markReady: (scope: string): void => {- if (readyScopes.has(scope)) return;-- readyScopes.add(scope);- emit();- },-- markPending,-- reset: markPending,-- 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.tsxdeleted file mode 100644index ea2e48d33ad..00000000000--- a/src/libs/swr/cacheProvider.integration.test.tsx+++ /dev/null@@ -1,124 +0,0 @@-/**- * @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 type { PropsWithChildren } from 'react';-import { createElement } from 'react';-import useSWR, { type Cache, SWRConfig, unstable_serialize } from 'swr';-import { afterEach, describe, expect, it, vi } from 'vitest';--import { LEGACY_MESSAGE_CACHE_VERSION, messageKeys } from './keys';-import { buildLocalDataKey, localDataCache } from './localDataCache';-import { createCacheProvider } from './localStorageProvider';--const SCOPE = 'integration-user:personal';--const makeProvider = (idbPatterns = ['MSGS']) => {- let resolveHydrated: () => void;- const hydrated = new Promise<void>((r) => {- resolveHydrated = r;- });- const provider = createCacheProvider({- debounceMs: 5,- getScope: () => SCOPE,- idbPatterns,- 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 SPA bootstrap: hydrate the app-level provider before the consuming- // React tree mounts. SWR then receives the already-hydrated provider Map.- const { provider: p2 } = makeProvider();- await p2.hydrateScope?.();-- // 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(p2) });-- // 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));- });-- it('hydrates a migrated v1 message row through its canonical v2 key while offline', async () => {- const legacyOriginalKey = [- messageKeys.list.root,- { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },- LEGACY_MESSAGE_CACHE_VERSION,- ];- const legacySerializedKey = unstable_serialize(legacyOriginalKey);- const cachedMessages = [{ id: 'message-1', text: 'offline history' }];- await localDataCache.set(- buildLocalDataKey(SCOPE, legacySerializedKey),- { _k: legacyOriginalKey, data: cachedMessages },- '1.0.0',- );-- const { provider } = makeProvider(['message:']);- await provider.hydrateScope?.();- const canonicalKey = messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' });- const fetcher = vi.fn(() => new Promise<never>(() => {}));- const result = renderHook(() => useSWR(canonicalKey, fetcher), {- wrapper: wrapper(provider),- });-- expect(result.result.current.data).toEqual(cachedMessages);-- const persisted = await localDataCache.entriesByScope(SCOPE);- expect(persisted.some((entry) => entry.key === legacySerializedKey)).toBe(false);- expect(persisted).toEqual([- expect.objectContaining({- data: expect.objectContaining({ _k: canonicalKey, data: cachedMessages }),- key: unstable_serialize(canonicalKey),- }),- ]);- result.unmount();- });-});diff --git a/src/libs/swr/coldHydrationRace.test.tsx b/src/libs/swr/coldHydrationRace.test.tsxdeleted file mode 100644index 42661d54e69..00000000000--- a/src/libs/swr/coldHydrationRace.test.tsx+++ /dev/null@@ -1,183 +0,0 @@-/**- * @vitest-environment happy-dom- *- * Deterministic reproduction + fix for the cold-open skeleton bug.- *- * On a cold boot the IndexedDB tier hydrates asynchronously. If a consumer- * registers its SWR key BEFORE that async hydration inserts the row into the- * provider Map, SWR records a cache miss β and because SWR does not observe a- * later *direct* Map mutation, the consumer stays empty until its own network- * revalidation resolves, ignoring the data already sitting on disk / in the Map.- * (Verified live: the message-list row is in the provider Map seconds before the- * conversation reads it, yet the conversation waits for the network.)- *- * Re-notifying after the fact does NOT work: once a consumer has subscribed to- * an empty key, the direct `map.set` during hydration replaces SWR's own state- * object and orphans the subscription β neither global nor bound `mutate` can- * revive it (see the third case). The only reliable fix is to guarantee the- * cache is hydrated BEFORE any consumer subscribes: the SPA bootstrap creates- * the provider and `await`s `hydrateScope()` before mounting the React root (the- * `FIX (bootstrap-await)` case).- */-import { act, cleanup, renderHook, waitFor } from '@testing-library/react';-import type { PropsWithChildren } from 'react';-import { createElement } from 'react';-import useSWR, { type Cache, SWRConfig, unstable_serialize, useSWRConfig } from 'swr';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';--import { buildLocalDataKey, localDataCache } from './localDataCache';-import { createCacheProvider, type ScopedSWRProvider } from './localStorageProvider';--let scope: string;-let scopeIndex = 0;-const KEY = ['MSGS', 'topic-cold'];-const CACHED = [{ id: 'm1', text: 'cached on disk' }];-const FRESH = [{ id: 'm1', text: 'from network' }];--const makeProvider = (providerScope = scope) =>- createCacheProvider({- debounceMs: 5,- getScope: () => providerScope,- idbPatterns: ['MSGS'],- localPatterns: [],- });--const wrapper =- (provider: ScopedSWRProvider) =>- ({ children }: PropsWithChildren) =>- createElement(- SWRConfig,- { value: { provider: provider as unknown as (c: Readonly<Cache>) => Cache } },- children,- );--/** Seed IndexedDB with a persisted SWR state row, as a prior session would leave it. */-const seedDisk = async () => {- // Seed the completed prior session, without a second live provider whose- // debounced writes can race with the cold-boot provider under test.- const key = buildLocalDataKey(scope, unstable_serialize(KEY));- await localDataCache.set(key, { data: CACHED }, '1.0.0');- expect(await localDataCache.get(key)).toEqual({ data: CACHED });-};--describe('cold-open hydration race (SWR + tiered provider + IndexedDB)', () => {- beforeEach(() => {- scope = `race-user-${++scopeIndex}:personal`;- });-- afterEach(async () => {- cleanup();- // Flush pending provider timers before clearing disk, so a late network- // result cannot recreate a row after teardown.- window.dispatchEvent(new Event('pagehide'));- await localDataCache.entriesByScope(scope);- await localDataCache.clearScope(scope);- });-- it('control: hydration completes BEFORE mount β cached row is served locally', async () => {- await seedDisk();- const p = makeProvider();- await p.hydrateScope?.();-- let resolveNet!: (v: unknown) => void;- const slow = new Promise((r) => {- resolveNet = r;- });- const r = renderHook(() => useSWR(KEY, () => slow), { wrapper: wrapper(p) });- expect(r.result.current.data).toEqual(CACHED);- resolveNet(FRESH);- await waitFor(() => expect(r.result.current.data).toEqual(FRESH));- });-- it('BUG: consumer mounts BEFORE hydration β never sees the cached row until the network resolves', async () => {- await seedDisk();- const p = makeProvider();-- let resolveNet!: (v: unknown) => void;- const slow = new Promise((r) => {- resolveNet = r;- });- const r = renderHook(() => useSWR(KEY, () => slow), { wrapper: wrapper(p) });- expect(r.result.current.data).toBeUndefined();-- await act(async () => {- await p.hydrateScope?.();- });- const mapEntry = [...(p() as Map<string, { data?: unknown }>).values()].find(- (v) => JSON.stringify((v as { data?: unknown })?.data) === JSON.stringify(CACHED),- );- expect(mapEntry).toBeDefined(); // cached row IS in the Map now- expect(r.result.current.data).toBeUndefined(); // β¦yet the consumer is still empty-- resolveNet(FRESH);- await waitFor(() => expect(r.result.current.data).toEqual(FRESH));- });-- it('FINDING: mutate CANNOT recover an orphaned consumer β so the fix must be mount-after-hydrate', async () => {- // Why the naive "re-notify after hydration" fix (mutate) does not work, and- // why the only reliable fix is to guarantee consumers mount after hydration.- await seedDisk();- const p = makeProvider();-- const r = renderHook(- () => {- const cfg = useSWRConfig();- const swr = useSWR(KEY, null); // no fetcher β pure cache read, no pending-fetch confound- return {- data: swr.data,- boundMutate: swr.mutate,- globalMutate: cfg.mutate,- cache: cfg.cache,- };- },- { wrapper: wrapper(p) },- );- expect(r.result.current.data).toBeUndefined(); // subscribed while Map empty β miss-- await act(async () => {- await p.hydrateScope?.();- });-- // SWR's cache Map now holds the row WITH its data β hydration workedβ¦- const cached = r.result.current.cache.get(unstable_serialize(KEY)) as { data?: unknown };- expect(cached?.data).toEqual(CACHED);-- // β¦but neither global nor key-bound mutate re-links the orphaned hook: the- // direct `map.set` during hydration replaced SWR's own state object, and the- // subscription can't be revived from outside. The consumer stays empty.- await act(async () => {- await r.result.current.globalMutate(KEY, CACHED, { revalidate: false });- });- expect(r.result.current.data).toBeUndefined();-- await act(async () => {- await r.result.current.boundMutate(CACHED, { revalidate: false });- });- expect(r.result.current.data).toBeUndefined();- });-- it('FIX (bootstrap-await): hydrate before mounting consumers β every consumer hits cache, no network', async () => {- await seedDisk();- const p = makeProvider();-- // The architectural fix: the SPA bootstrap creates the provider and AWAITS- // hydrateScope() before mounting the React root, so the Map is populated- // before ANY consumer subscribes. (Contrast the BUG case, where a consumer- // subscribes during the async hydration window and is orphaned.)- await p.hydrateScope?.();-- const never = () => new Promise<never>(() => {}); // never resolves β only cache can serve- const r = renderHook(- () => {- const first = useSWR(KEY, never);- const second = useSWR(KEY, never); // a second consumer of the same key- return { first: first.data, second: second.data };- },- { wrapper: wrapper(p) },- );-- // both read the populated Map synchronously on first render β no network- expect(r.result.current.first).toEqual(CACHED);- expect(r.result.current.second).toEqual(CACHED);- });-});diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.tsindex 08c0da40707..95472372d3a 100644--- a/src/libs/swr/keys.frozen.test.ts+++ b/src/libs/swr/keys.frozen.test.ts@@ -50,15 +50,6 @@ const LEGACY_SWR_KEYS = ['electronKeys.proxySettings','electronKeys.remoteServerConfig','electronKeys.workspaceDeviceId',- 'evalKeys.benchmarkDetail',- 'evalKeys.benchmarks',- 'evalKeys.datasetRuns',- 'evalKeys.runDetail',- 'evalKeys.runResults',- 'evalKeys.runs',- 'evalKeys.testCaseDetail',- 'evalKeys.testCases',- 'fileKeys.ttsFile','gatewayKeys.clientLlmWaits','gatewayKeys.reconnect','globalKeys.latestVersion',@@ -66,7 +57,6 @@ const LEGACY_SWR_KEYS = ['globalKeys.systemStatus','goalKeys.pendingClarifications','goalKeys.pendingForIsland',- 'groupKeys.queryAgentsForCreate','imageKeys.generationStatus','imessageKeys.bridgeStatus','inboxKeys.unreadCount',@@ -90,33 +80,17 @@ const LEGACY_SWR_KEYS = ['onboardingKeys.understandingTopic','openInAppKeys.detect','ragEvalKeys.datasetList',- 'ragEvalKeys.datasetRecords','ragEvalKeys.evaluationList','recommendationsKeys.heteroDetections',- 'resourceKeys.list',- 'scmKeys.changeRequests','scmKeys.repositories','scmKeys.wakeTarget','serverConfigKeys.get',- 'shareKeys.agentInfo',- 'shareKeys.agentShareConnectors',- 'shareKeys.agentShareEligibleWorks',- 'shareKeys.agentShareGrantableSkills',- 'shareKeys.agentShareStats',- 'shareKeys.agentShareStatus','shareKeys.artifact','shareKeys.file','shareKeys.pageDocument','shareKeys.topic',- 'shareKeys.visitorTopics','taskLabelKeys.list',- 'threadKeys.list',- 'toolKeys.agentSkillDetail',- 'toolKeys.agentSkills',- 'toolKeys.composioAppTools',- 'toolKeys.composioConnections','topicActionKeys.openNewOrSave',- 'topicKeys.list','topicKeys.scheduledRunWatch','topicKeys.search','userKeys.checkTrace',diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 1dec1abefbc..aab1c7bb3d1 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -1,24 +1,6 @@-import { replicaKeys } from 'local-replica';-import { unstable_serialize } from 'swr';import { describe, expect, it } from 'vitest';import { documentCommentKeys, isDocumentCommentKeyForEvent, workKeys } from './keys';-import { CACHE_TIERS } from './localStorageProvider';--describe('replica sync keys', () => {- it('keeps SWR orchestration entries out of the persistence tiers', () => {- for (const key of [- // Replicas persist through their own storage, never through the SWR tiers.- replicaKeys.sync('agentList', 1, 'user-1:personal', 'sidebar', {}),- replicaKeys.sync('agentConfig', 1, 'user-1:personal', 'agent-1', { agentId: 'agent-1' }),- ]) {- const serialized = unstable_serialize(key);- expect(- [...CACHE_TIERS.idb, ...CACHE_TIERS.local].some((pattern) => serialized.includes(pattern)),- ).toBe(false);- }- });-});describe('workKeys', () => {it('keeps the Resources Private and Workspace galleries in separate cache entries', () => {diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex edb583479f7..dcd9588ac7c 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -10,10 +10,13 @@* (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:')`.+ * - Consistent, discoverable naming (`swrKeys.topic.search(...)`).+ * - The `domain:` prefix lets callers refresh a whole domain at once via+ * `matchDomain('topic:')`.+ *+ * SWR keeps these entries in memory only: there is no cache provider and+ * nothing here is persisted. Data that must paint from a local copy on a cold+ * start is a replica (`@/libs/replica`), not an SWR key.** Each factory also exposes `.root` (the namespace string) for `mutate`* matchers that compare `key[0]`.@@ -93,14 +96,7 @@ export const normalizeMessageListQueryContext = (...(context.agentShareId === undefined ? {} : { agentShareId: context.agentShareId }),});-/** Previous persisted key schema, used only by the targeted v1 β v2 migration. */-export const LEGACY_MESSAGE_CACHE_VERSION = 1;--/**- * Message cache key schema version. Version 2 canonicalizes query context, so- * it requires a persisted-key migration even though `UIChatMessage[]` itself- * did not change.- */+/** Message key schema version. Version 2 canonicalizes the query context. */export const MESSAGE_CACHE_VERSION = 2;export const messageKeys = {@@ -134,11 +130,6 @@ export const isMessageListKey = (// ---- topic --------------------------------------------------------------export const topicKeys = {- list: def('topic:list', (containerKey: string, opts: Record<string, unknown>) => [- 'topic:list',- containerKey,- opts,- ]),scheduledRunWatch: def('topic:scheduledRunWatch', (topicId: string) => ['topic:scheduledRunWatch',topicId,@@ -228,17 +219,6 @@ export const isDocumentCommentKeyForEvent = (return false;};-// ---- group ---------------------------------------------------------------export const groupKeys = {- /** Agent picker for the "create group" modal. */- queryAgentsForCreate: def('group:queryAgentsForCreate', () => ['group:queryAgentsForCreate']),-};--// ---- thread --------------------------------------------------------------export const threadKeys = {- list: def('thread:list', (topicId: string) => ['thread:list', topicId]),-};-/*** Goal reads that have no local-first projection: the pending queues are live* "what needs you" feeds, and the topic link is a discovery poll.@@ -313,33 +293,12 @@ export const serverConfigKeys = {get: 'serverConfig:get' as const,};-// ---- agent eval ----------------------------------------------------------export const evalKeys = {- benchmarkDetail: def('eval:benchmarkDetail', (id: string) => ['eval:benchmarkDetail', id]),- benchmarks: def('eval:benchmarks', () => ['eval:benchmarks']),- datasetRuns: def('eval:datasetRuns', (datasetId: string) => ['eval:datasetRuns', datasetId]),- runDetail: def('eval:runDetail', (id: string) => ['eval:runDetail', id]),- runResults: def('eval:runResults', (id: string) => ['eval:runResults', id]),- runs: def('eval:runs', (benchmarkId?: string) => ['eval:runs', benchmarkId]),- testCaseDetail: def('eval:testCaseDetail', (id: string) => ['eval:testCaseDetail', id]),- testCases: def('eval:testCases', (datasetId: string, limit?: number, offset?: number) => [- 'eval:testCases',- datasetId,- limit,- offset,- ]),-};-// ---- RAG eval -----------------------------------------------------------export const ragEvalKeys = {datasetList: def('ragEval:datasetList', (knowledgeBaseId?: string) => ['ragEval:datasetList',knowledgeBaseId,]),- datasetRecords: def('ragEval:datasetRecords', (datasetId: string) => [- 'ragEval:datasetRecords',- datasetId,- ]),evaluationList: def('ragEval:evaluationList', (knowledgeBaseId?: string) => ['ragEval:evaluationList',knowledgeBaseId,@@ -451,17 +410,6 @@ export const userMemoryKeys = {tags: def('userMemory:tags', () => ['userMemory:tags']),};-// ---- tool (skills / plugins / builtin / mcp / composio stores) --------------export const toolKeys = {- agentSkillDetail: def('tool:agentSkillDetail', (id: string) => ['tool:agentSkillDetail', id]),- agentSkills: def('tool:agentSkills', () => ['tool:agentSkills']),- composioAppTools: def('tool:composioAppTools', (appSlug: string) => [- 'tool:composioAppTools',- appSlug,- ]),- composioConnections: def('tool:composioConnections', () => ['tool:composioConnections']),-};-// ---- global -------------------------------------------------------------export const globalKeys = {latestVersion: def('global:latestVersion', () => ['global:latestVersion']),@@ -469,16 +417,10 @@ export const globalKeys = {systemStatus: def('global:systemStatus', () => ['global:systemStatus']),};-// ---- file ----------------------------------------------------------------export const fileKeys = {- ttsFile: def('file:ttsFile', (messageId: string) => ['file:ttsFile', messageId]),-};-// =========================================================================-// UI-layer keys (features / routes / components). Prefixes below stay-// memory-only unless explicitly listed in `CACHE_TIERS`. Names avoid colliding-// with cached prefixes β e.g. share/topic is `share:` not `topic:`, portal-// header is `portal:` not `document:`.+// UI-layer keys (features / routes / components). Names avoid colliding with+// domain prefixes refreshed through `matchDomain` β e.g. share/topic is+// `share:` not `topic:`, portal header is `portal:` not `document:`.// =========================================================================// ---- MCP Apps (interactive tool result views) -----------------------------@@ -514,10 +456,6 @@ export const messengerKeys = {// ---- scm (GitHub App integration) --------------------------------------export const scmKeys = {- changeRequests: def('scm:changeRequests', (workspaceId: string | null | undefined) => [- 'scm:changeRequests',- workspaceId ?? null,- ]),repositories: def('scm:repositories', (workspaceId: string | null | undefined) => ['scm:repositories',workspaceId ?? null,@@ -553,35 +491,6 @@ export const inboxKeys = {// ---- share (shared agent / topic / page) ---------------------------------export const shareKeys = {- agentInfo: def('share:agentInfo', (slugOrId: string) => ['share:agentInfo', slugOrId]),- /** Connector lists the creator-side AGENT share tool picker screens, keyed by agentId. */- agentShareConnectors: def('share:agentShareConnectors', (agentId: string) => [- 'share:agentShareConnectors',- agentId,- ]),- /** Candidates for the creator-side AGENT share skill picker, keyed by agentId. */- agentShareGrantableSkills: def('share:agentShareGrantableSkills', (agentId: string) => [- 'share:agentShareGrantableSkills',- agentId,- ]),- // Creator-side share status keyed by agentId (visitor side uses `agentInfo`).- agentShareStats: def('share:agentShareStats', (agentId: string) => [- 'share:agentShareStats',- agentId,- ]),- agentShareEligibleWorks: def(- 'share:agentShareEligibleWorks',- (agentId: string, offset: number, includeWorkIds: readonly string[]) => [- 'share:agentShareEligibleWorks',- agentId,- offset,- includeWorkIds,- ],- ),- agentShareStatus: def('share:agentShareStatus', (agentId: string) => [- 'share:agentShareStatus',- agentId,- ]),artifact: def('share:artifact', (id: string) => ['share:artifact', id]),file: def('share:file', (shareId: string) => ['share:file', shareId]),pageDocument: def('share:pageDocument', (documentId: string) => [@@ -589,8 +498,6 @@ export const shareKeys = {documentId,]),topic: def('share:topic', (id: string) => ['share:topic', id]),- /** The visitor's own topics under an agent share (server-scoped by senderId). */- visitorTopics: def('share:visitorTopics', (shareId: string) => ['share:visitorTopics', shareId]),};// ---- local file ---------------------------------------------------------@@ -718,14 +625,6 @@ export const topicActionKeys = {openNewOrSave: def('topicAction:openNewOrSave', () => ['topicAction:openNewOrSave']),};-// ---- misc remaining domains ----------------------------------------------export const resourceKeys = {- list: def('resource:list', (params: unknown, workspaceId: string | null) => [- 'resource:list',- params,- workspaceId,- ]),-};export const recommendationsKeys = {heteroDetections: def('recommendations:heteroDetections', () => ['recommendations:heteroDetections',@@ -788,12 +687,9 @@ export const swrKeys = {cron: cronKeys,device: deviceKeys,electron: electronKeys,- eval: evalKeys,- file: fileKeys,gateway: gatewayKeys,goal: goalKeys,global: globalKeys,- group: groupKeys,image: imageKeys,imessage: imessageKeys,inbox: inboxKeys,@@ -806,12 +702,9 @@ export const swrKeys = {openInApp: openInAppKeys,ragEval: ragEvalKeys,recommendations: recommendationsKeys,- resource: resourceKeys,serverConfig: serverConfigKeys,share: shareKeys,taskLabel: taskLabelKeys,- thread: threadKeys,- tool: toolKeys,topic: topicKeys,acceptanceCollaboration: acceptanceCollaborationKeys,documentComment: documentCommentKeys,diff --git a/src/libs/swr/localDataCache.test.ts b/src/libs/swr/localDataCache.test.tsdeleted file mode 100644index 7d588e9194d..00000000000--- a/src/libs/swr/localDataCache.test.ts+++ /dev/null@@ -1,105 +0,0 @@-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('atomically puts replacement rows before deleting their sources', async () => {- const sourceKey = buildLocalDataKey(scope, 'source');- const targetKey = buildLocalDataKey(scope, 'target');- await localDataCache.set(sourceKey, { value: 'legacy' }, '1.0.0');-- await localDataCache.applyBatch({- deleteKeys: [sourceKey],- putEntries: [- {- data: { value: 'canonical' },- key: targetKey,- updatedAt: 123,- version: '1.0.0',- },- ],- });-- expect(await localDataCache.get(sourceKey)).toBeUndefined();- expect(await localDataCache.get(targetKey)).toEqual({ value: 'canonical' });- expect(await localDataCache.entriesByScope(scope)).toEqual([- {- data: { value: 'canonical' },- key: 'target',- updatedAt: 123,- version: '1.0.0',- },- ]);- });-- 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.tsdeleted file mode 100644index e8149f4a4b6..00000000000--- a/src/libs/swr/localDataCache.ts+++ /dev/null@@ -1,96 +0,0 @@-/**- * SWR cache repository backed by the runtime-neutral local database.- */-import { localDatabase } from '@/libs/localDatabase';--interface CacheRow {- data: unknown;- updatedAt: number;- version?: string;-}--export interface ScopeEntry extends CacheRow {- key: string;-}--export interface LocalDataCachePutEntry extends CacheRow {- /** Full composite key, including the identity scope prefix. */- key: string;-}--export interface LocalDataCacheBatch {- deleteKeys: string[];- putEntries: LocalDataCachePutEntry[];-}--const CACHE_COLLECTION = 'swr-cache';--const scopePrefix = (scope: string) => `${scope}::`;--/** Build the composite persistence key from the identity scope and SWR key. */-export const buildLocalDataKey = (scope: string, swrKey: unknown): string =>- `${scopePrefix(scope)}${typeof swrKey === 'string' ? swrKey : JSON.stringify(swrKey)}`;--export const localDataCache = {- /**- * Atomically replace persisted cache rows. Migration callers receive a- * rejection when the transaction cannot commit so source rows remain- * available for a later retry.- */- applyBatch: ({ deleteKeys, putEntries }: LocalDataCacheBatch): Promise<void> =>- localDatabase.batch([- ...putEntries.map(({ key, ...value }) => ({- collection: CACHE_COLLECTION,- key,- type: 'set' as const,- value,- })),- ...deleteKeys.map((key) => ({ collection: CACHE_COLLECTION, key, type: 'delete' as const })),- ]),-- clearScope: async (scope: string): Promise<void> => {- try {- await localDatabase.deleteByPrefix(CACHE_COLLECTION, scopePrefix(scope));- } catch {- // Cache persistence is best-effort.- }- },-- delete: async (key: string): Promise<void> => {- try {- await localDatabase.delete(CACHE_COLLECTION, key);- } catch {- // Cache persistence is best-effort.- }- },-- entriesByScope: async (scope: string): Promise<ScopeEntry[]> => {- try {- const prefix = scopePrefix(scope);- const entries = await localDatabase.entriesByPrefix<CacheRow>(CACHE_COLLECTION, prefix);- return entries.map(({ key, value }) => ({- ...value,- key: key.slice(prefix.length),- }));- } catch {- return [];- }- },-- get: async <T>(key: string): Promise<T | undefined> => {- try {- const row = await localDatabase.get<CacheRow>(CACHE_COLLECTION, key);- return row?.data as T | undefined;- } catch {- return undefined;- }- },-- set: async (key: string, data: unknown, version?: string): Promise<void> => {- try {- await localDatabase.set(CACHE_COLLECTION, key, { data, updatedAt: Date.now(), version });- } catch {- // Cache persistence is best-effort.- }- },-};diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.tsdeleted file mode 100644index e8659653dc4..00000000000--- a/src/libs/swr/localStorageProvider.test.ts+++ /dev/null@@ -1,457 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { bootTiming } from '@/libs/bootTiming';--import { buildLocalDataKey, 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('createCacheProvider β tiering', () => {- beforeEach(() => {- localStorage.clear();- });-- afterEach(async () => {- vi.restoreAllMocks();- await localDataCache.clearScope('s1');- await localDataCache.clearScope('s2');- });-- it('getScopedCacheKey namespaces by scope', () => {- expect(getScopedCacheKey('u1:personal')).toBe('lobechat-swr-cache:u1:personal');- expect(getScopedCacheKey('anon:personal')).not.toBe(getScopedCacheKey('u1:personal'));- });-- it('restores an idb-tier entry from durable storage after a reload, isolated per scope', async () => {- const scope = { value: 's1' };- const options = { idbPatterns: [...CACHE_TIERS.idb], localPatterns: [...CACHE_TIERS.local] };- const { provider } = buildProvider(scope, options);- await provider.hydrateScope?.();- const key = JSON.stringify(['task:detail', 'T-1']);- const data = { data: [{ id: 'task-1', title: 'Keep me' }] };- provider().set(key, data);- await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);-- const { provider: restored } = buildProvider(scope, options);- await restored.hydrateScope?.();- expect(restored().get(key)).toEqual(data);-- const { provider: otherUser } = buildProvider({ value: 's2' }, options);- await otherUser.hydrateScope?.();- expect(otherUser().get(key)).toBeUndefined();- });-- it('routes local-tier keys to scoped localStorage only', async () => {- const scope = { value: 's1' };- const { provider } = buildProvider(scope);- const map = provider();-- map.set('recents', { items: [1] });- map.set('MSGS:t1', { items: [2] }); // idb tier- map.set('random', { x: 1 }); // memory only-- await until(() => localStorage.getItem(getScopedCacheKey('s1')) !== null);-- 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');- });-- it('persists task-template recommendation keys in the local tier', async () => {- const scope = { value: 's1' };- const { provider } = buildProvider(scope, {- idbPatterns: [...CACHE_TIERS.idb],- localPatterns: [...CACHE_TIERS.local],- });- const map = provider();- const key = JSON.stringify(['taskTemplate:listDailyRecommend:v2', '', 3, 'zh-CN']);-- map.set(key, { data: [{ id: 1, title: 'Daily brief' }] });-- await until(() => localStorage.getItem(getScopedCacheKey('s1')) !== null);-- const stored = JSON.parse(localStorage.getItem(getScopedCacheKey('s1'))!);- expect(stored.map(([k]: [string]) => k)).toContain(key);- expect(await localDataCache.entriesByScope('s1')).toEqual([]);- });-- it('persists model config keys in the local tier', async () => {- const scope = { value: 's1' };- const { provider } = buildProvider(scope, {- idbPatterns: [...CACHE_TIERS.idb],- localPatterns: [...CACHE_TIERS.local],- });- const map = provider();- const key = 'modelConfig:lobehub';-- map.set(key, { data: { homeNewModels: [{ model: 'gpt-image-2', type: 'image' }] } });-- await until(() => localStorage.getItem(getScopedCacheKey('s1')) !== null);-- const stored = JSON.parse(localStorage.getItem(getScopedCacheKey('s1'))!);- expect(stored.map(([k]: [string]) => k)).toContain(key);- expect(await localDataCache.entriesByScope('s1')).toEqual([]);- });-- 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();-- map.set('MSGS:t1', { items: ['hello'] });- await until(async () => (await localDataCache.entriesByScope('s1')).length > 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;-- expect(map2.get('MSGS:t1')).toEqual({ items: ['hello'] });- });-- 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 });-- await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);- // not written to the localStorage tier- expect(localStorage.getItem(getScopedCacheKey('s1'))).toBeNull();- });-- 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' });- });-- 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' });- });-- 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);- });-- it('hydrates idb-tier entries regardless of age (never expires)', async () => {- // seed an idb entry via a throwaway provider- const seedScope = { value: 's1' };- const { provider: seed } = buildProvider(seedScope);- seed().set('MSGS:old', { ok: true });- await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);-- // a fresh provider with an absurdly small TTL β the row is well past it- const scope = { value: 's1' };- const { provider } = buildProvider(scope, { ttl: 1 });- const map = provider();-- // idb tier ignores TTL: the stale row still hydrates (stale-while-revalidate)- await until(() => map.get('MSGS:old') !== undefined);- expect(map.get('MSGS:old')).toEqual({ ok: true });- });-- it('drops idb-tier entries on version mismatch', async () => {- // seed an idb entry under a different app version- const seedScope = { value: 's1' };- const { provider: seed } = buildProvider(seedScope, { version: '9.9.9' });- seed().set('MSGS:stale', { ok: false });- await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);-- const scope = { value: 's1' };- const { provider } = buildProvider(scope, { version: '1.0.0' });- const map = provider();-- // give async hydration a chance, then assert it never lands- await new Promise((r) => setTimeout(r, 40));- expect(map.has('MSGS:stale')).toBe(false);- });-- it('drops legacy idb rows that carry no cache version', async () => {- // seed a row directly with no version (pre-versioning / non-conforming writer)- await localDataCache.set(buildLocalDataKey('s1', 'MSGS:legacy'), { ok: false });-- const scope = { value: 's1' };- const { provider } = buildProvider(scope, { version: '1.0.0' });- const map = provider();-- await new Promise((r) => setTimeout(r, 40));- expect(map.has('MSGS:legacy')).toBe(false);- });-- 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));- });-- 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('recent:topicList');- expect(CACHE_TIERS.local).toContain('taskTemplate:');- expect(CACHE_TIERS.local).toContain('modelConfig:');- });-});--/**- * Regression: data fetched while the scope is provisional (anonymous, before- * `userId` resolves on a slow cold boot) must not be persisted. Without the- * `isEphemeralScope` quarantine, an `anon:personal` write lands in IndexedDB- * and is orphaned the moment the real user scope resolves β surfacing as a- * stale-loading cache miss on the next boot.- */-describe('createCacheProvider β ephemeral (anonymous) scope quarantine', () => {- const isAnon = (scope: string) => scope.startsWith('anon:');-- beforeEach(() => localStorage.clear());- afterEach(async () => {- vi.restoreAllMocks();- await localDataCache.clearScope('anon:personal');- await localDataCache.clearScope('u1:ws');- });-- it('reproduces the leak: without quarantine, an anon-scope write persists and is orphaned on the scope flip', async () => {- const scope = { value: 'anon:personal' };- const { provider } = buildProvider(scope); // no isEphemeralScope β current prod behavior for web- const map = provider();-- // A message fetched during the anonymous boot window.- map.set('MSGS:t1', { items: ['hi'] });- map.set('recents', { items: [1] });-- // It leaks into the anon partitions (this is the bug).- await until(async () => (await localDataCache.entriesByScope('anon:personal')).length > 0);- expect(await localDataCache.entriesByScope('anon:personal')).toHaveLength(1);- await until(() => localStorage.getItem(getScopedCacheKey('anon:personal')) !== null);-- // userId resolves β scope flips to the real user; the fresh provider hydrates- // the user partition and never sees the orphaned anon row.- scope.value = 'u1:ws';- const { provider: userProvider } = buildProvider(scope);- const userMap = userProvider();- await new Promise((r) => setTimeout(r, 40));- expect(userMap.has('MSGS:t1')).toBe(false);- // The orphaned row is stranded in the anon partition forever.- expect(await localDataCache.entriesByScope('anon:personal')).toHaveLength(1);- });-- it('fix: with isEphemeralScope, anon-scope writes stay memory-only (no idb, no localStorage)', async () => {- const scope = { value: 'anon:personal' };- const { provider } = buildProvider(scope, { isEphemeralScope: isAnon });- const map = provider();-- map.set('MSGS:t1', { items: ['hi'] });- map.set('recents', { items: [1] });-- // In-memory cache still serves the boot fetchβ¦- expect(map.get('MSGS:t1')).toEqual({ items: ['hi'] });-- // β¦but nothing is persisted to either tier.- await new Promise((r) => setTimeout(r, 40));- expect(await localDataCache.entriesByScope('anon:personal')).toHaveLength(0);- expect(localStorage.getItem(getScopedCacheKey('anon:personal'))).toBeNull();- });-- it('fix: writes under the resolved (non-anon) scope still persist normally', async () => {- const scope = { value: 'u1:ws' };- const { provider } = buildProvider(scope, { isEphemeralScope: isAnon });- const map = provider();-- map.set('MSGS:t1', { items: ['hi'] });- map.set('recents', { items: [1] });-- await until(async () => (await localDataCache.entriesByScope('u1:ws')).length > 0);- expect(await localDataCache.entriesByScope('u1:ws')).toHaveLength(1);- await until(() => localStorage.getItem(getScopedCacheKey('u1:ws')) !== null);- });-- it('fix: the flushAll (visibility/pagehide) path also respects the quarantine', async () => {- const scope = { value: 'anon:personal' };- const { provider } = buildProvider(scope, { isEphemeralScope: isAnon, debounceMs: 100000 });- const map = provider();- map.set('MSGS:t1', { items: ['hi'] });- map.set('recents', { items: [1] });-- // Force the synchronous teardown flush that bypasses the debounce.- document.dispatchEvent(new Event('visibilitychange'));- Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });- document.dispatchEvent(new Event('visibilitychange'));- window.dispatchEvent(new Event('pagehide'));-- await new Promise((r) => setTimeout(r, 40));- expect(await localDataCache.entriesByScope('anon:personal')).toHaveLength(0);- expect(localStorage.getItem(getScopedCacheKey('anon:personal'))).toBeNull();- });-});--describe('cache-hydration span', () => {- beforeEach(() => {- localStorage.clear();- (bootTiming as unknown as { _reset: () => void })._reset();- });-- afterEach(async () => {- vi.restoreAllMocks();- await localDataCache.clearScope('span-s1');- await localDataCache.clearScope('span-s2');- });-- it('records exactly one cache-hydration span after initial hydration', async () => {- vi.spyOn(performance, 'now').mockReturnValueOnce(100).mockReturnValue(200);-- const scope = { value: 'span-s1' };- const { hydrated, provider } = buildProvider(scope);- provider();- await hydrated;-- const { spans } = bootTiming.snapshot();- const hydrationSpans = spans.filter((s) => s.name === 'cache-hydration');- expect(hydrationSpans).toHaveLength(1);- expect(hydrationSpans[0].startMs).toBe(100);- expect(hydrationSpans[0].durMs).toBe(100);- });-- it('does not record a second cache-hydration span on scope reload', async () => {- vi.spyOn(performance, 'now').mockReturnValue(50);-- const scope = { value: 'span-s1' };- const { hydrated, provider } = buildProvider(scope);- provider();- await hydrated;-- scope.value = 'span-s2';- await provider.reloadScope!();-- const { spans } = bootTiming.snapshot();- expect(spans.filter((s) => s.name === 'cache-hydration')).toHaveLength(1);- });-- it('does not record a span when hydration fails', async () => {- vi.spyOn(localDataCache, 'entriesByScope').mockRejectedValueOnce(new Error('idb error'));-- const scope = { value: 'span-s1' };- const { hydrated, provider } = buildProvider(scope);- provider();- await hydrated;-- const { spans } = bootTiming.snapshot();- expect(spans.filter((s) => s.name === 'cache-hydration')).toHaveLength(0);- });-});--describe('clearSWRCache', () => {- beforeEach(() => localStorage.clear());-- it('removes the given cache key', () => {- localStorage.setItem('lobechat-swr-cache', '[]');- clearSWRCache();- expect(localStorage.getItem('lobechat-swr-cache')).toBeNull();- });-});diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsdeleted file mode 100644index 707b09c826d..00000000000--- a/src/libs/swr/localStorageProvider.ts+++ /dev/null@@ -1,536 +0,0 @@-/**- * Unified tiered SWR cache provider- *- * 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: swrCacheProvider(getCacheScope) }}>- * <App />- * </SWRConfig>- * ```- */-import { bootTiming } from '@/libs/bootTiming';--import { buildLocalDataKey, localDataCache } from './localDataCache';-import { migrateMessageListCache } from './migrations/messageListCache';-import { isScopeTrusted } from './useCacheScope';--interface CacheEntry<T = unknown> {- /** Cached data */- data: T;- /** Cache timestamp */- timestamp: number;- /** App version */- version: string;-}--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[];- /**- * Predicate marking a scope as *provisional* β writes made while it is active- * must never be persisted. On desktop the identity round-trip can complete (or- * the CacheHydrationGate timeout backstop can fire) before `userId` resolves,- * briefly making the scope anonymous. Data fetched + flushed during that- * window lands in the `anon` partition and is orphaned the instant the real- * user scope resolves (`reloadScope`), surfacing as a stale-loading cache miss- * on the next boot. Keeping the in-memory cache but skipping persistence for- * these scopes closes that leak.- */- isEphemeralScope?: (scope: string) => boolean;- /** 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;- /** Called after a scope's IndexedDB tier finishes hydrating. */- onScopeHydrated?: (scope: string) => void;- /**- * Cache TTL in milliseconds, defaults to 7 days. Governs the localStorage- * tier only (small, frequently-changing shells like recents) β the IndexedDB- * tier never expires (stale-while-revalidate).- */- ttl?: number;- /** App version; entries from another version are ignored on load. */- version?: string;-}--/**- * SWR cache provider function with an in-place scope reloader.- */-export type ScopedSWRProvider = (() => Map<string, unknown>) & {- /**- * Ensure the provider's Map exists and hydrate the current scope's IndexedDB- * tier. This is used by the SPA bootstrap while React mounts the root tree.- */- hydrateScope?: () => Promise<void>;- /**- * 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?: () => Promise<void>;-};--const isLocalStorageAvailable = (): boolean => {- if (typeof window === 'undefined') return false;- try {- const testKey = '__swr_cache_test__';- localStorage.setItem(testKey, 'test');- localStorage.removeItem(testKey);- return true;- } catch {- return false;- }-};--/**- * 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 matchesPattern = (key: string, patterns: string[]): boolean =>- patterns.some((pattern) => key.includes(pattern));--/**- * Build the scoped localStorage cache key (localStorage tier namespace).- *- * Partitioned per identity scope so different users / workspaces sharing the- * same browser origin never read or overwrite each other's cached data.- */-export const getScopedCacheKey = (scope: string) => `lobechat-swr-cache:${scope}`;--/**- * Create a unified tiered cache provider.- */-export function createCacheProvider(options: CacheProviderOptions = {}): ScopedSWRProvider {- const {- debounceMs = 2000,- getScope = () => 'default',- idbPatterns = [],- isEphemeralScope,- localPatterns = [],- ttl = 7 * 24 * 60 * 60 * 1000, // 7 days- maxLocalEntries = 50,- version = '1.0.0',- onError = (error) => console.error('[SWR Cache]', error),- onScopeHydrated,- } = options;-- // SSR / no storage β plain memory cache, no persistence. Still signal- // hydration so boot initialization never blocks.- if (!isLocalStorageAvailable()) {- const memoryProvider = (() => {- onScopeHydrated?.(getScope());- return new Map();- }) as ScopedSWRProvider;- memoryProvider.hydrateScope = async () => {- onScopeHydrated?.(getScope());- };- memoryProvider.reloadScope = memoryProvider.hydrateScope;-- return memoryProvider;- }-- /** 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;- };-- /**- * Whether the *current* scope may be written to persistence. Provisional- * scopes (see `isEphemeralScope`) stay memory-only so their transient boot- * data never leaks into a partition that gets orphaned on the next scope flip.- */- const isPersistableScope = (): boolean => !isEphemeralScope?.(getScope());-- let cacheMapInstance: TieredCacheMap | null = null;- let hydratedScope: string | null = null;- let hydrationEpoch = 0;- let pendingHydration: { promise: Promise<void>; scope: string } | null = null;- let cacheHydrationSpanRecorded = false;-- // --- localStorage tier (synchronous snapshot) ----------------------------- let localTimer: ReturnType<typeof setTimeout> | null = null;-- 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;- if (!isPersistableScope()) 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);- }- }- };-- const debouncedSaveLocal = () => {- if (localTimer) clearTimeout(localTimer);- localTimer = setTimeout(saveLocal, debounceMs);- };-- // --- IndexedDB tier (asynchronous, per-key rows) -------------------------- let idbTimer: ReturnType<typeof setTimeout> | null = null;- const dirtyIdb = new Set<string>();- const deletedIdb = new Set<string>();-- const flushIdb = () => {- if (!cacheMapInstance) return;- const scope = getScope();- if (isEphemeralScope?.(scope)) return;- const writes = [...dirtyIdb];- const dels = [...deletedIdb];- dirtyIdb.clear();- deletedIdb.clear();-- 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);- }- };-- const debouncedFlushIdb = () => {- if (idbTimer) clearTimeout(idbTimer);- idbTimer = setTimeout(flushIdb, debounceMs);- };-- const loadIdb = async (scope: string, epoch: number, hydrationStart?: number) => {- let succeeded = false;- try {- const entries = await localDataCache.entriesByScope(scope);- const migratedEntries = await migrateMessageListCache({- entries,- onError,- providerVersion: version,- scope,- });- // The IndexedDB tier holds read-heavy / write-light business entities- // (messages, topics, β¦): once written, a row rarely changes. We never drop- // these by age β a stale row hydrates for an instant first paint and SWR's- // revalidate-on-mount refreshes it in the background (stale-while-revalidate).- // Version is the only invalidator: a row must carry the *current* version,- // so legacy/unversioned rows (which the age check used to bound) are dropped- // and a version bump still evicts everyone. TTL governs the localStorage- // tier only (see `loadLocal`).- const valid = migratedEntries.filter((e) => e.version === version);- // Map may have changed scope while we awaited; only apply if still current.- if (cacheMapInstance && getScope() === scope && hydrationEpoch === epoch) {- cacheMapInstance.hydrate(valid.map((e) => [e.key, e.data]));- hydratedScope = scope;- }- succeeded = true;- } catch (error) {- onError(error as Error);- } finally {- if (hydrationStart !== undefined && succeeded && !cacheHydrationSpanRecorded) {- cacheHydrationSpanRecorded = true;- bootTiming.recordSpan(- 'cache-hydration',- hydrationStart,- performance.now() - hydrationStart,- );- }- onScopeHydrated?.(scope);- if (pendingHydration?.scope === scope && hydrationEpoch === epoch) {- pendingHydration = null;- }- }- };-- // --- write routing -------------------------------------------------------- const onSet = (key: string) => {- // Provisional scope β memory only; never schedule a persist (see- // `isEphemeralScope`). The post-flip global revalidation re-writes keys- // under the resolved scope, so nothing is lost.- if (!isPersistableScope()) return;- const tier = tierOf(key);- if (tier === 'local') debouncedSaveLocal();- else if (tier === 'idb') {- deletedIdb.delete(key);- dirtyIdb.add(key);- debouncedFlushIdb();- }- };-- const onDelete = (key: string) => {- if (!isPersistableScope()) return;- const tier = tierOf(key);- if (tier === 'local') debouncedSaveLocal();- else if (tier === 'idb') {- dirtyIdb.delete(key);- deletedIdb.add(key);- debouncedFlushIdb();- }- };-- /**- * 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 as early as possible. IndexedDB writes are async and can't- // be awaited during teardown, so we must not wait for `beforeunload`: by then- // the browser is free to kill the page before `flushIdb()`'s writes land.- // Instead flush the moment the page is *hidden* (tab switch / minimize / app- // background) β the page is still alive there, so the async writes have time- // to complete well before any actual unload. `pagehide` is a best-effort- // backstop for the desktop close case (and is bfcache-friendly, unlike- // `beforeunload`).- const flushAll = () => {- if (localTimer) {- clearTimeout(localTimer);- localTimer = null;- }- if (idbTimer) {- clearTimeout(idbTimer);- idbTimer = null;- }- saveLocal();- flushIdb();- };-- document.addEventListener('visibilitychange', () => {- if (document.visibilityState === 'hidden') flushAll();- });- window.addEventListener('pagehide', flushAll);-- // 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);- }- }- });-- const ensureMap = (): TieredCacheMap => {- if (cacheMapInstance) return cacheMapInstance;-- const map = new TieredCacheMap();- cacheMapInstance = map;- map.hydrate([...loadLocal().entries()]); // synchronous first paint- return map;- };-- const hydrateScope = async (): Promise<void> => {- const scope = getScope();- ensureMap();- if (hydratedScope === scope) return;- if (pendingHydration?.scope === scope) return pendingHydration.promise;-- const epoch = ++hydrationEpoch;- const start = !cacheHydrationSpanRecorded ? performance.now() : undefined;- const promise = loadIdb(scope, epoch, start);- pendingHydration = { promise, scope };- return promise;- };-- const provider: ScopedSWRProvider = () => {- const map = ensureMap();- void hydrateScope();- return map;- };-- provider.hydrateScope = hydrateScope;-- provider.reloadScope = async () => {- if (!cacheMapInstance) {- await hydrateScope();- return;- }-- hydrationEpoch += 1;- hydratedScope = null;- pendingHydration = null;-- // 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()]);- await hydrateScope();- };-- return provider;-}--/**- * 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');- } catch (error) {- console.error('[SWR Cache] Failed to clear cache:', error);- }-}--/**- * 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.- */-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- '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: [- // Home's chat-mode recents still uses the SWR persistence tier. The mixed- // Recent projection is persisted by its Zustand localStorage snapshot.- 'recent:topicList',- 'fetchRecentTopics',- 'fetchRecentResources',- 'fetchRecentPages',- 'agentBuilder:suggestions', // builder opening-suggestion chips (skip LLM regen on revisit)- 'taskTemplate:', // home task-template recommendations- 'modelConfig:', // small remote model config shells used by home starter chips- ],-} as const;--/**- * 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.- */-export const swrCacheProvider = (- getScope: () => string,- onScopeHydrated?: (scope: string) => void,-): ScopedSWRProvider => {- return createCacheProvider({- getScope,- idbPatterns: [...CACHE_TIERS.idb],- // Quarantine writes until the session check resolves (`isScopeTrusted`).- // The active scope is optimistic (persisted last-known user) before the- // session confirms it, so a write made then could land in the wrong- // partition on an account switch / first-ever boot and get orphaned. Once the- // session resolves the scope is definitive and writes persist β including- // no-auth, where the check completes to "not signed in" and the anonymous- // scope is a legitimate durable context. `reloadScope` clears the dirty set- // on a real scope flip, so quarantined writes never survive a switch.- isEphemeralScope: () => !isScopeTrusted(),- localPatterns: [...CACHE_TIERS.local],- onScopeHydrated,- // Governs the localStorage tier only (recents-style shells); the IndexedDB- // tier (messages, topics, β¦) never expires. 7 days is plenty for recents.- ttl: 7 * 24 * 60 * 60 * 1000, // 7 days- });-};diff --git a/src/libs/swr/migrations/messageListCache.test.ts b/src/libs/swr/migrations/messageListCache.test.tsdeleted file mode 100644index 6222a8a153f..00000000000--- a/src/libs/swr/migrations/messageListCache.test.ts+++ /dev/null@@ -1,394 +0,0 @@-import { unstable_serialize } from 'swr';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { LEGACY_MESSAGE_CACHE_VERSION, messageKeys } from '../keys';-import { buildLocalDataKey, localDataCache, type ScopeEntry } from '../localDataCache';-import { migrateMessageListCache } from './messageListCache';--const PROVIDER_VERSION = '1.0.0';-const PERSONAL_SCOPE = 'user-1:personal';-const WORKSPACE_SCOPE = 'user-1:workspace-1';-const OTHER_SCOPE = 'user-2:personal';--const messages = [- {- agentId: 'agent-1',- content: 'hello',- createdAt: 1,- id: 'message-1',- role: 'user',- threadId: null,- topicId: 'topic-1',- updatedAt: 1,- },-];--const createEntry = (- originalKey: readonly unknown[],- data = messages,- updatedAt = 1,-): ScopeEntry => ({- data: { _k: originalKey, data },- key: unstable_serialize(originalKey),- updatedAt,- version: PROVIDER_VERSION,-});--const seedEntries = async (scope: string, entries: ScopeEntry[]) => {- await localDataCache.applyBatch({- deleteKeys: [],- putEntries: entries.map((entry) => ({- ...entry,- key: buildLocalDataKey(scope, entry.key),- })),- });-};--describe('migrateMessageListCache', () => {- beforeEach(async () => {- await Promise.all(- [PERSONAL_SCOPE, WORKSPACE_SCOPE, OTHER_SCOPE].map((scope) =>- localDataCache.clearScope(scope),- ),- );- });-- afterEach(() => {- vi.restoreAllMocks();- });-- it('moves a v1 workspace row to the canonical v2 key before hydration', async () => {- const legacyKey = [- messageKeys.list.root,- {- agentId: 'agent-1',- scope: 'main',- threadId: null,- topicId: 'topic-1',- workspaceSlug: 'workspace',- },- LEGACY_MESSAGE_CACHE_VERSION,- 'workspace-1',- ];- const legacyEntry = createEntry(legacyKey);- await seedEntries(WORKSPACE_SCOPE, [legacyEntry]);-- const result = await migrateMessageListCache({- entries: await localDataCache.entriesByScope(WORKSPACE_SCOPE),- providerVersion: PROVIDER_VERSION,- scope: WORKSPACE_SCOPE,- });- const canonicalKey = [- ...messageKeys.list({ agentId: 'agent-1', threadId: null, topicId: 'topic-1' }),- 'workspace-1',- ];- const canonicalSerializedKey = unstable_serialize(canonicalKey);-- expect(result).toEqual([- expect.objectContaining({- data: expect.objectContaining({ _k: canonicalKey, data: messages }),- key: canonicalSerializedKey,- }),- ]);-- const persisted = await localDataCache.entriesByScope(WORKSPACE_SCOPE);- expect(persisted.some((entry) => entry.key === legacyEntry.key)).toBe(false);- expect(persisted).toEqual([- expect.objectContaining({- data: expect.objectContaining({ _k: canonicalKey, data: messages }),- key: canonicalSerializedKey,- }),- ]);- });-- it('collapses equivalent legacy variants and keeps the newest snapshot', async () => {- const older = createEntry(- [- messageKeys.list.root,- { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },- LEGACY_MESSAGE_CACHE_VERSION,- ],- [{ ...messages[0], content: 'old' }],- 10,- );- const newer = createEntry(- [- messageKeys.list.root,- {- agentId: 'agent-1',- documentId: undefined,- threadId: null,- topicId: 'topic-1',- },- LEGACY_MESSAGE_CACHE_VERSION,- ],- [{ ...messages[0], content: 'new' }],- 20,- );-- const result = await migrateMessageListCache({- entries: [older, newer],- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(result).toHaveLength(1);- expect(result[0]).toEqual(- expect.objectContaining({- data: expect.objectContaining({ data: [{ ...messages[0], content: 'new' }] }),- updatedAt: 20,- }),- );- });-- it('also migrates historical versionless and message:listLegacy rows', async () => {- const versionless = createEntry([- messageKeys.list.root,- { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },- ]);- const listLegacy = createEntry(- ['message:listLegacy', { agentId: 'agent-1', topicId: 'topic-1' }],- [{ ...messages[0], content: 'newest legacy' }],- 2,- );-- const result = await migrateMessageListCache({- entries: [versionless, listLegacy],- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(result).toHaveLength(1);- expect(result[0].data).toEqual(- expect.objectContaining({ data: [{ ...messages[0], content: 'newest legacy' }] }),- );- });-- it('leaves existing v2 and non-message rows unchanged on repeated hydration', async () => {- const v2 = createEntry(messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' }));- const topicEntry: ScopeEntry = {- data: { _k: ['topic:list', 'agent-1'], data: [] },- key: unstable_serialize(['topic:list', 'agent-1']),- updatedAt: 2,- version: PROVIDER_VERSION,- };- const batchSpy = vi.spyOn(localDataCache, 'applyBatch');-- const result = await migrateMessageListCache({- entries: [v2, topicEntry],- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(result).toEqual([v2, topicEntry]);- expect(batchSpy).not.toHaveBeenCalled();- });-- it('keeps an original-key-less v2 empty snapshot written before a hook mounts', async () => {- const canonicalKey = messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' });- const v2WithoutOriginalKey: ScopeEntry = {- data: { data: [] },- key: unstable_serialize(canonicalKey),- updatedAt: 2,- version: PROVIDER_VERSION,- };- const batchSpy = vi.spyOn(localDataCache, 'applyBatch');-- const result = await migrateMessageListCache({- entries: [v2WithoutOriginalKey],- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(result).toEqual([v2WithoutOriginalKey]);- expect(batchSpy).not.toHaveBeenCalled();- });-- it('recovers an original-key-less message:listLegacy row from its message identities', async () => {- const legacyKey = ['message:listLegacy', { agentId: 'agent-1', topicId: 'topic-1' }];- const legacyWithoutOriginalKey: ScopeEntry = {- data: { data: messages },- key: unstable_serialize(legacyKey),- updatedAt: 2,- version: PROVIDER_VERSION,- };-- const result = await migrateMessageListCache({- entries: [legacyWithoutOriginalKey],- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(result).toEqual([- expect.objectContaining({- key: unstable_serialize(- messageKeys.list({ agentId: 'agent-1', threadId: null, topicId: 'topic-1' }),- ),- }),- ]);- });-- it('recovers an original-key-less workspace row only when every message identity agrees', async () => {- const legacyKey = [- messageKeys.list.root,- { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },- LEGACY_MESSAGE_CACHE_VERSION,- 'workspace-1',- ];- const legacyWithoutOriginalKey: ScopeEntry = {- data: { data: messages },- key: unstable_serialize(legacyKey),- updatedAt: 2,- version: PROVIDER_VERSION,- };-- const result = await migrateMessageListCache({- entries: [legacyWithoutOriginalKey],- providerVersion: PROVIDER_VERSION,- scope: WORKSPACE_SCOPE,- });-- expect(result).toEqual([- expect.objectContaining({- key: unstable_serialize([- ...messageKeys.list({ agentId: 'agent-1', threadId: null, topicId: 'topic-1' }),- 'workspace-1',- ]),- }),- ]);- });-- it('does not let a provider-version-mismatched v2 row block migration', async () => {- const canonicalKey = messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' });- const staleV2 = {- ...createEntry(canonicalKey, [{ ...messages[0], content: 'stale provider' }]),- version: '0.0.1',- };- const legacy = createEntry(- [- messageKeys.list.root,- { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },- LEGACY_MESSAGE_CACHE_VERSION,- ],- [{ ...messages[0], content: 'current provider' }],- );-- const result = await migrateMessageListCache({- entries: [staleV2, legacy],- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(- result.find(- (entry) =>- entry.key === unstable_serialize(canonicalKey) && entry.version === PROVIDER_VERSION,- )?.data,- ).toEqual(expect.objectContaining({ data: [{ ...messages[0], content: 'current provider' }] }));- });-- it('drops malformed or ambiguous legacy rows instead of guessing a conversation', async () => {- const malformed = createEntry([messageKeys.list.root, {}, LEGACY_MESSAGE_CACHE_VERSION]);- const ambiguousKey = [- messageKeys.list.root,- { agentId: 'agent-1', topicId: 'topic-1' },- LEGACY_MESSAGE_CACHE_VERSION,- ];- const ambiguous: ScopeEntry = {- data: {- data: messages.map(({ threadId: _, ...message }) => message),- },- key: unstable_serialize(ambiguousKey),- updatedAt: 2,- version: PROVIDER_VERSION,- };-- const result = await migrateMessageListCache({- entries: [malformed, ambiguous],- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(result).toEqual([]);- });-- it('does not derive a conversation when one row has a null identity', async () => {- const legacyKey = [- messageKeys.list.root,- { agentId: 'agent-1', topicId: 'topic-1' },- LEGACY_MESSAGE_CACHE_VERSION,- ];- const mixedIdentity: ScopeEntry = {- data: { data: [messages[0], { ...messages[0], agentId: null, id: 'message-2' }] },- key: unstable_serialize(legacyKey),- updatedAt: 2,- version: PROVIDER_VERSION,- };-- const result = await migrateMessageListCache({- entries: [mixedIdentity],- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(result).toEqual([]);- });-- it('keeps the source persisted when the atomic migration transaction fails', async () => {- const legacyEntry = createEntry([- messageKeys.list.root,- { agentId: 'agent-1', topicId: 'topic-1' },- LEGACY_MESSAGE_CACHE_VERSION,- ]);- await seedEntries(PERSONAL_SCOPE, [legacyEntry]);- const onError = vi.fn();- const batchSpy = vi- .spyOn(localDataCache, 'applyBatch')- .mockRejectedValueOnce(new Error('write failed'));-- const result = await migrateMessageListCache({- entries: await localDataCache.entriesByScope(PERSONAL_SCOPE),- onError,- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(result).toEqual([- expect.objectContaining({- key: unstable_serialize(messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' })),- }),- ]);- expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'write failed' }));- expect(await localDataCache.entriesByScope(PERSONAL_SCOPE)).toEqual([legacyEntry]);-- batchSpy.mockRestore();- const retried = await migrateMessageListCache({- entries: await localDataCache.entriesByScope(PERSONAL_SCOPE),- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });- const canonicalKey = messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' });-- expect(retried).toEqual([expect.objectContaining({ key: unstable_serialize(canonicalKey) })]);- expect(await localDataCache.entriesByScope(PERSONAL_SCOPE)).toEqual([- expect.objectContaining({ key: unstable_serialize(canonicalKey) }),- ]);- });-- it('never reads, merges, or deletes another identity scope', async () => {- const otherEntry = createEntry([- messageKeys.list.root,- { agentId: 'agent-1', topicId: 'topic-1' },- LEGACY_MESSAGE_CACHE_VERSION,- ]);- await seedEntries(OTHER_SCOPE, [otherEntry]);-- await migrateMessageListCache({- entries: [],- providerVersion: PROVIDER_VERSION,- scope: PERSONAL_SCOPE,- });-- expect(await localDataCache.entriesByScope(OTHER_SCOPE)).toEqual([otherEntry]);- });-});diff --git a/src/libs/swr/migrations/messageListCache.ts b/src/libs/swr/migrations/messageListCache.tsdeleted file mode 100644index 3c39b3fb872..00000000000--- a/src/libs/swr/migrations/messageListCache.ts+++ /dev/null@@ -1,249 +0,0 @@-import { isRecord, pickString } from '@lobechat/utils/object';-import debug from 'debug';-import { unstable_serialize } from 'swr';--import {- type CanonicalMessageListContext,- LEGACY_MESSAGE_CACHE_VERSION,- MESSAGE_CACHE_VERSION,- messageKeys,- type MessageListQueryContext,- normalizeMessageListQueryContext,-} from '../keys';-import { buildLocalDataKey, localDataCache, type ScopeEntry } from '../localDataCache';--const log = debug('lobe-client:swr-message-migration');--const LEGACY_MESSAGE_LIST_ROOT = 'message:listLegacy';-const legacyMessageListRoots = [messageKeys.list.root, LEGACY_MESSAGE_LIST_ROOT];-const serializedMessageListPrefixes = legacyMessageListRoots.map((root) =>- unstable_serialize([root]),-);--interface MigrationCandidate {- source: ScopeEntry;- target: ScopeEntry;-}--interface MigrateMessageListCacheOptions {- entries: ScopeEntry[];- onError?: (error: Error) => void;- providerVersion: string;- scope: string;-}--const nullableString = (value: unknown): string | null | undefined =>- value === null ? null : pickString(value);--const readContext = (value: unknown): MessageListQueryContext | undefined => {- if (!isRecord(value)) return;-- const context = {- agentId: nullableString(value.agentId),- groupId: nullableString(value.groupId),- threadId: nullableString(value.threadId),- topicId: nullableString(value.topicId),- topicShareId: pickString(value.topicShareId),- };-- if (!context.topicId && !context.topicShareId) return;- if (!context.agentId && !context.groupId && !context.topicShareId) return;- return context;-};--/**- * Recover only personal-conversation coordinates that are encoded consistently- * in every cached row. Group messages cannot recover the supervisor agent from- * message authors, and an empty list contains no coordinates, so both remain- * deliberately unrecoverable instead of being copied to a guessed key.- */-const deriveContextFromMessages = (state: Record<PropertyKey, unknown>) => {- if (!Array.isArray(state.data) || state.data.length === 0) return;- if (!state.data.every(isRecord)) return;-- const rows = state.data;- if (rows.some((row) => row.groupId !== undefined && row.groupId !== null)) return;- if (- !rows.every(- (row) =>- Object.hasOwn(row, 'agentId') &&- Object.hasOwn(row, 'threadId') &&- Object.hasOwn(row, 'topicId'),- )- ) {- return;- }-- const agentIds = new Set(rows.map((row) => row.agentId));- const topicIds = new Set(rows.map((row) => row.topicId));- const threadValues = new Set(rows.map((row) => row.threadId));-- if (agentIds.size !== 1 || topicIds.size !== 1 || threadValues.size !== 1) return;- const [agentId] = agentIds;- const [topicId] = topicIds;- const [threadId] = threadValues;- if (typeof agentId !== 'string' || !agentId) return;- if (typeof topicId !== 'string' || !topicId) return;- if (threadId !== null && typeof threadId !== 'string') return;-- return normalizeMessageListQueryContext({- agentId,- groupId: null,- threadId,- topicId,- });-};--const workspaceSuffixFromScope = (scope: string): string[] => {- const separatorIndex = scope.lastIndexOf(':');- if (separatorIndex < 0) return [];- const workspaceId = scope.slice(separatorIndex + 1);- return workspaceId && workspaceId !== 'personal' ? [workspaceId] : [];-};--/**- * SWR may persist data written through `mutate` before a hook mounts. Those- * states legitimately have no `_k`, so identify an already-canonical v2 row- * from its serialized version/workspace suffix before attempting legacy- * recovery. Ambiguous rows must never be destructively treated as legacy.- */-const isCanonicalSerializedMessageKey = (entry: ScopeEntry, scope: string): boolean => {- if (- !serializedMessageListPrefixes[0] ||- !entry.key.startsWith(serializedMessageListPrefixes[0])- ) {- return false;- }-- const versionSuffix = unstable_serialize([- MESSAGE_CACHE_VERSION,- ...workspaceSuffixFromScope(scope),- ]).slice(1);-- return entry.key.endsWith(versionSuffix);-};--const buildCandidate = (entry: ScopeEntry, scope: string): MigrationCandidate | undefined => {- if (!isRecord(entry.data)) return;-- const originalKey = entry.data._k;- let context: CanonicalMessageListContext | undefined;- let trailingKey: unknown[];-- if (Array.isArray(originalKey)) {- const root = originalKey[0];- const isVersionOne =- root === messageKeys.list.root && originalKey[2] === LEGACY_MESSAGE_CACHE_VERSION;- const isVersionlessList =- root === messageKeys.list.root &&- (originalKey.length === 2 || typeof originalKey[2] === 'string');- const isLegacyList = root === LEGACY_MESSAGE_LIST_ROOT;- if (!isVersionOne && !isVersionlessList && !isLegacyList) return;-- const legacyContext = readContext(originalKey[1]);- if (!legacyContext) return;- context = normalizeMessageListQueryContext(legacyContext);- trailingKey = originalKey.slice(isVersionOne ? 3 : 2);- } else {- if (!serializedMessageListPrefixes.some((prefix) => entry.key.startsWith(prefix))) return;- if (isCanonicalSerializedMessageKey(entry, scope)) return;- context = deriveContextFromMessages(entry.data);- if (!context) return;- trailingKey = workspaceSuffixFromScope(scope);- }-- const canonicalOriginalKey = [...messageKeys.list(context), ...trailingKey];- const canonicalSerializedKey = unstable_serialize(canonicalOriginalKey);-- // An original-key-less row can already serialize to v2. Never rewrite it.- if (canonicalSerializedKey === entry.key) return;-- return {- source: entry,- target: {- ...entry,- data: { ...entry.data, _k: canonicalOriginalKey },- key: canonicalSerializedKey,- },- };-};--const isUnrecoverableLegacyMessageEntry = (entry: ScopeEntry, scope: string): boolean => {- if (!serializedMessageListPrefixes.some((prefix) => entry.key.startsWith(prefix))) return false;- if (!isRecord(entry.data)) return true;-- const originalKey = entry.data._k;- if (Array.isArray(originalKey)) {- const root = originalKey[0];- const isVersionOne =- root === messageKeys.list.root && originalKey[2] === LEGACY_MESSAGE_CACHE_VERSION;- const isVersionlessList =- root === messageKeys.list.root &&- (originalKey.length === 2 || typeof originalKey[2] === 'string');- const isLegacyList = root === LEGACY_MESSAGE_LIST_ROOT;- return (isVersionOne || isVersionlessList || isLegacyList) && !readContext(originalKey[1]);- }-- if (isCanonicalSerializedMessageKey(entry, scope)) return false;- return !deriveContextFromMessages(entry.data);-};--/**- * Canonicalize persisted message-list keys before the provider hydrates them.- * The returned entries are safe to hydrate even when IndexedDB rejects the- * transaction; the untouched legacy source then remains available for a retry- * on the next boot.- */-export const migrateMessageListCache = async ({- entries,- onError,- providerVersion,- scope,-}: MigrateMessageListCacheOptions): Promise<ScopeEntry[]> => {- const currentVersionEntries = entries.filter((entry) => entry.version === providerVersion);- const candidates = currentVersionEntries- .map((entry) => buildCandidate(entry, scope))- .filter((candidate): candidate is MigrationCandidate => candidate !== undefined);- const candidateSources = new Set(candidates.map(({ source }) => source.key));- const unrecoverable = currentVersionEntries.filter(- (entry) => !candidateSources.has(entry.key) && isUnrecoverableLegacyMessageEntry(entry, scope),- );- const removedKeys = new Set([...candidateSources, ...unrecoverable.map((entry) => entry.key)]);-- const retained = entries.filter((entry) => !removedKeys.has(entry.key));- const retainedKeys = new Set(- retained.filter((entry) => entry.version === providerVersion).map((entry) => entry.key),- );- const newestByTarget = new Map<string, ScopeEntry>();-- for (const { target } of candidates) {- if (retainedKeys.has(target.key)) continue;- const current = newestByTarget.get(target.key);- if (!current || target.updatedAt > current.updatedAt) newestByTarget.set(target.key, target);- }-- const migratedEntries = [...newestByTarget.values()];- const hydratedEntries = [...retained, ...migratedEntries];-- if (removedKeys.size === 0 && migratedEntries.length === 0) return hydratedEntries;-- try {- await localDataCache.applyBatch({- deleteKeys: [...removedKeys].map((key) => buildLocalDataKey(scope, key)),- putEntries: migratedEntries.map((entry) => ({- ...entry,- key: buildLocalDataKey(scope, entry.key),- })),- });- } catch (cause) {- const error = cause instanceof Error ? cause : new Error(String(cause));- log('Message cache migration will retry after transaction failure: %O', error);- onError?.(error);- }-- if (unrecoverable.length > 0) {- log('Excluded %d unrecoverable legacy message cache rows from hydration', unrecoverable.length);- }-- return hydratedEntries;-};diff --git a/src/libs/swr/useClientDataSWRWithSync.ts b/src/libs/swr/useClientDataSWRWithSync.tsindex f41194c621d..0575d649a83 100644--- a/src/libs/swr/useClientDataSWRWithSync.ts+++ b/src/libs/swr/useClientDataSWRWithSync.ts@@ -2,11 +2,8 @@* 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 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.+ * When SWR returns data from its (in-memory) cache, it syncs it to the store via+ * the onData callback.*/import { useEffect, useLayoutEffect, useRef } from 'react';diff --git a/src/services/message/replica.ts b/src/services/message/replica.tsindex 3e9e17c1c83..2d0a8e5a887 100644--- a/src/services/message/replica.ts+++ b/src/services/message/replica.ts@@ -151,8 +151,7 @@ export const conversationMessagesResource = defineReplica<persistKey: (key) => key.startsWith('p:'),storage: 'indexedDB',// A `replica:sync` key, so `slice.revalidate` and the predicate revalidation- // below match it; a `message:` key would hit the SWR persistence tier and- // store every transcript (shared and scoped ones included) a second time.+ // below match it.// Its params are the conversation, not the full sync params: one read per// entry, so two responses never settle out of order into one transcript.syncKey: (params) => {diff --git a/src/spa/initialize/postRender.test.ts b/src/spa/initialize/postRender.test.tsindex 1adf6c6e4c7..ce120fc8e4d 100644--- a/src/spa/initialize/postRender.test.ts+++ b/src/spa/initialize/postRender.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({ensureBuiltinToolSurfaces: vi.fn().mockResolvedValue(undefined),+ purgeLegacySWRCache: vi.fn().mockResolvedValue(undefined),registerBuiltinToolExecutors: vi.fn(),setPostRenderReady: vi.fn(),shouldSkipRoutePreload: vi.fn().mockReturnValue(false),@@ -24,6 +25,10 @@ vi.mock('./connectors', () => ({startConnectorInitialization: mocks.startConnectorInitialization,}));+vi.mock('./purgeLegacySWRCache', () => ({+ purgeLegacySWRCache: mocks.purgeLegacySWRCache,+}));+vi.mock('./routePreload', () => ({shouldSkipRoutePreload: mocks.shouldSkipRoutePreload,startRoutePreload: mocks.startRoutePreload,@@ -68,9 +73,12 @@ describe('startPostRenderInitialization', () => {expect(mocks.startConnectorInitialization).not.toHaveBeenCalled();expect(mocks.ensureBuiltinToolSurfaces).not.toHaveBeenCalled();expect(mocks.setPostRenderReady).not.toHaveBeenCalled();+ expect(mocks.purgeLegacySWRCache).not.toHaveBeenCalled();await vi.runAllTimersAsync();+ expect(mocks.purgeLegacySWRCache).toHaveBeenCalledTimes(1);+expect(mocks.registerBuiltinToolExecutors).not.toHaveBeenCalled();expect(mocks.ensureBuiltinToolSurfaces).toHaveBeenCalledTimes(1);expect(mocks.setPostRenderReady).toHaveBeenCalledWith(true);diff --git a/src/spa/initialize/postRender.ts b/src/spa/initialize/postRender.tsindex 5089011ffe5..7d04d83b69b 100644--- a/src/spa/initialize/postRender.ts+++ b/src/spa/initialize/postRender.ts@@ -1,5 +1,6 @@import { setPostRenderReady } from '../atoms/app';import { startConnectorInitialization } from './connectors';+import { purgeLegacySWRCache } from './purgeLegacySWRCache';import { shouldSkipRoutePreload, startRoutePreload } from './routePreload';import { ensureBuiltinToolSurfaces } from './toolSurfaces';@@ -60,5 +61,7 @@ export const startPostRenderInitialization = () => {} catch (error) {console.error('[SPA Initialize] route preload initialization failed', error);}++ void purgeLegacySWRCache();});};diff --git a/src/spa/initialize/purgeLegacySWRCache.test.ts b/src/spa/initialize/purgeLegacySWRCache.test.tsnew file mode 100644index 00000000000..91cad3f2b44--- /dev/null+++ b/src/spa/initialize/purgeLegacySWRCache.test.ts@@ -0,0 +1,93 @@+/**+ * @vitest-environment happy-dom+ */+import 'fake-indexeddb/auto';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { localDatabase, registerLocalDatabaseAdapter } from '@/libs/localDatabase';+import { createIndexedDBLocalDatabaseAdapter } from '@/libs/localDatabase/indexedDBAdapter';++import {+ LEGACY_SWR_CACHE_COLLECTION,+ LEGACY_SWR_CACHE_PURGED_KEY,+ purgeLegacySWRCache,+} from './purgeLegacySWRCache';++const seedLegacyCache = async () => {+ // Rows the removed SWR provider wrote: `${scope}::${serializedKey}`.+ await localDatabase.set(LEGACY_SWR_CACHE_COLLECTION, 'u1:personal::["message:list",{},2]', {+ data: [],+ updatedAt: 1,+ });+ await localDatabase.set(LEGACY_SWR_CACHE_COLLECTION, 'u2:ws_1::["topic:search","q"]', {+ data: [],+ updatedAt: 1,+ });+ localStorage.setItem('lobechat-swr-cache', '[]');+ localStorage.setItem('lobechat-swr-cache:u1:personal', '[]');+ localStorage.setItem('lobechat-swr-cache:u2:ws_1', '[]');+};++const legacyRows = () => localDatabase.entriesByPrefix(LEGACY_SWR_CACHE_COLLECTION, '');+const legacyLocalStorageKeys = () =>+ Object.keys(localStorage).filter((key) => key.startsWith('lobechat-swr-cache'));++let restoreAdapter: () => void;++beforeEach(() => {+ restoreAdapter = registerLocalDatabaseAdapter(createIndexedDBLocalDatabaseAdapter());+ localStorage.clear();+});++afterEach(async () => {+ await localDatabase.deleteByPrefix(LEGACY_SWR_CACHE_COLLECTION, '');+ await localDatabase.deleteByPrefix('query-projections', '');+ restoreAdapter();+ localStorage.clear();+ vi.restoreAllMocks();+});++describe('purgeLegacySWRCache', () => {+ it('removes every scope of the legacy SWR cache from the local database and localStorage', async () => {+ await seedLegacyCache();+ await localDatabase.set('query-projections', 'replica-row', { data: 1 });+ localStorage.setItem('replica:recentList:v1:keep', '1');++ await purgeLegacySWRCache();++ expect(await legacyRows()).toEqual([]);+ expect(legacyLocalStorageKeys()).toEqual([]);+ // Replica storage is untouched.+ expect(await localDatabase.get('query-projections', 'replica-row')).toEqual({ data: 1 });+ expect(localStorage.getItem('replica:recentList:v1:keep')).toBe('1');+ });++ it('runs only once', async () => {+ await purgeLegacySWRCache();+ expect(localStorage.getItem(LEGACY_SWR_CACHE_PURGED_KEY)).toBe('1');++ // Anything under the old names after the purge is not ours to delete again.+ await seedLegacyCache();+ await purgeLegacySWRCache();++ expect(await legacyRows()).toHaveLength(2);+ });++ it('never throws and retries on the next boot when the local database fails', async () => {+ await seedLegacyCache();+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const deleteByPrefix = vi+ .spyOn(localDatabase, 'deleteByPrefix')+ .mockRejectedValueOnce(new Error('IndexedDB unavailable'));++ await expect(purgeLegacySWRCache()).resolves.toBeUndefined();+ expect(localStorage.getItem(LEGACY_SWR_CACHE_PURGED_KEY)).toBeNull();++ deleteByPrefix.mockRestore();+ await purgeLegacySWRCache();++ expect(await legacyRows()).toEqual([]);+ expect(localStorage.getItem(LEGACY_SWR_CACHE_PURGED_KEY)).toBe('1');+ });+});diff --git a/src/spa/initialize/purgeLegacySWRCache.ts b/src/spa/initialize/purgeLegacySWRCache.tsnew file mode 100644index 00000000000..70a2f18fed1--- /dev/null+++ b/src/spa/initialize/purgeLegacySWRCache.ts@@ -0,0 +1,43 @@+import { localDatabase } from '@/libs/localDatabase';++/**+ * One-time cleanup of the removed SWR persistence layer.+ *+ * SWR used to persist its cache to the local database (`swr-cache`+ * collection, IndexedDB on the web and SQLite in Electron) and to localStorage+ * (`lobechat-swr-cache` and the scoped `lobechat-swr-cache:<scope>` entries).+ * Nothing reads them anymore; server data the UI paints lives in replicas.+ */+export const LEGACY_SWR_CACHE_COLLECTION = 'swr-cache';+export const LEGACY_SWR_LOCAL_STORAGE_PREFIX = 'lobechat-swr-cache';+/** Set once the purge succeeded, so later boots skip it. */+export const LEGACY_SWR_CACHE_PURGED_KEY = 'lobechat-legacy-swr-cache-purged';++const removeLegacyLocalStorage = () => {+ const keys: string[] = [];+ for (let index = 0; index < localStorage.length; index += 1) {+ const key = localStorage.key(index);+ if (key?.startsWith(LEGACY_SWR_LOCAL_STORAGE_PREFIX)) keys.push(key);+ }+ for (const key of keys) localStorage.removeItem(key);+};++/**+ * Remove the legacy SWR cache once per browser profile / desktop install.+ *+ * Runs after first paint and never throws. On failure the marker stays unset,+ * so the next boot tries again.+ */+export const purgeLegacySWRCache = async (): Promise<void> => {+ if (typeof window === 'undefined') return;++ try {+ if (localStorage.getItem(LEGACY_SWR_CACHE_PURGED_KEY)) return;++ removeLegacyLocalStorage();+ await localDatabase.deleteByPrefix(LEGACY_SWR_CACHE_COLLECTION, '');+ localStorage.setItem(LEGACY_SWR_CACHE_PURGED_KEY, '1');+ } catch (error) {+ console.warn('[SPA Initialize] legacy SWR cache cleanup failed', error);+ }+};diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.tsindex 27aed066497..9e58e0a8cee 100644--- a/src/store/chat/slices/message/actions/query.ts+++ b/src/store/chat/slices/message/actions/query.ts@@ -84,9 +84,9 @@ export class MessageQueryActionImpl {* (every one when `predicate` is omitted). Nothing is refetched: the* conversation is gone.*- * Installs upgraded from before the replica still hold `message:list` rows- * in the SWR IndexedDB tier, which never expires them; those are purged too- * until the SWR persistence layer is removed.+ * In-memory SWR `message:list` entries are dropped too. Rows the removed SWR+ * persistence layer left behind are deleted once at boot+ * (`purgeLegacySWRCache`).*/evictConversationMessages = async (predicate?: (context: ConversationContext) => boolean,diff --git a/src/store/chat/slices/message/actions/transcript.sync.test.ts b/src/store/chat/slices/message/actions/transcript.sync.test.tsindex 60aa8d32047..8f19e833241 100644--- a/src/store/chat/slices/message/actions/transcript.sync.test.ts+++ b/src/store/chat/slices/message/actions/transcript.sync.test.ts@@ -1,11 +1,9 @@import { type UIChatMessage } from '@lobechat/types';import { act, waitFor } from '@testing-library/react';-import { unstable_serialize } from 'swr';import { beforeEach, describe, expect, it, vi } from 'vitest';import { REPLICA_INDEX_KEY } from '@/libs/replica';import { useClientDataSWR } from '@/libs/swr';-import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';import { messageService } from '@/services/message';import {clearMessageListClientCacheState,@@ -344,7 +342,7 @@ describe('useFetchMessages', () => {expect(messageService.getMessages).not.toHaveBeenCalled();});- it('keys the sync by its entry, outside the SWR persistence tier', () => {+ it('keys the sync by its conversation entry', () => {// The SWR mock runs the fetcher; an unmocked list read rejects after the test.vi.mocked(messageService.getMessages).mockResolvedValue([]);const shared = { ...context, topicShareId: 'share-1' };@@ -360,13 +358,6 @@ describe('useFetchMessages', () => {expect(first![4]).toBe(conversationMessagesKey({ ...context, threadId: 'thread-1' }));expect(second![4]).toBe(conversationMessagesKey({ ...context, threadId: 'thread-2' }));expect(third![4]).toBe(conversationMessagesKey(shared));- // The replica persists transcripts itself; a key the SWR cache provider- // persists would store each one (memory-only shares too) a second time.- const persistedPatterns = [...CACHE_TIERS.idb, ...CACHE_TIERS.local];- for (const key of keys) {- const serialized = unstable_serialize(key);- expect(persistedPatterns.filter((pattern) => serialized.includes(pattern))).toEqual([]);- }});it('skips switch-time revalidation after a successful server verification', async () => {diff --git a/src/store/chat/slices/topic/topicListCache.integration.test.ts b/src/store/chat/slices/topic/topicListCache.integration.test.tsindex 8567085e1e1..3326651831b 100644--- a/src/store/chat/slices/topic/topicListCache.integration.test.ts+++ b/src/store/chat/slices/topic/topicListCache.integration.test.ts@@ -21,8 +21,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheScope, createReplicaState } from '@/libs/replica';import { broadcastCacheScope, resetCacheScopeBroadcast } from '@/libs/replica/cacheScopeEvents';-import { localDataCache } from '@/libs/swr/localDataCache';-import { createCacheProvider } from '@/libs/swr/localStorageProvider';import { setScopedMutate } from '@/libs/swr/mutate';import { topicService } from '@/services/topic';import { topicMapKey } from '@/store/chat/utils/topicMapKey';@@ -38,14 +36,8 @@ const SCOPE_PREFIX = 'topic-cache-user:personal';const AGENT_ID = 'agent-topic-cache-test';const CONTAINER_KEY = topicMapKey({ agentId: AGENT_ID });-/** SWR provider as in the app: `topic:` (agent view, search) still persists via SWR. */-const makeProvider = (scope: string) =>- createCacheProvider({- debounceMs: 5,- getScope: () => scope,- idbPatterns: ['topic:'],- localPatterns: [],- });+/** A fresh in-memory SWR cache per session, as after a reload (SWR persists nothing). */+const makeProvider = () => () => new Map();/** Publish the scoped mutate the way `SWRProvider` does in the app. */const MutateBridge = () => {@@ -55,7 +47,7 @@ const MutateBridge = () => {};const wrapper =- (provider: ReturnType<typeof createCacheProvider>) =>+ (provider: ReturnType<typeof makeProvider>) =>({ children }: PropsWithChildren) =>createElement(SWRConfig,@@ -107,10 +99,9 @@ describe('persisted topic list across a reload', () => {afterEach(async () => {await Promise.all(- [...scopes].flatMap((scope) => [- localDataCache.clearScope(scope),+ [...scopes].map((scope) =>topicListResource.storage!.remove({ queryKey: SIDEBAR_STORAGE_KEY, scope }),- ]),+ ),);scopes.clear();vi.restoreAllMocks();@@ -123,7 +114,7 @@ describe('persisted topic list across a reload', () => {vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scope)),+ wrapper: wrapper(makeProvider()),});await waitFor(() =>@@ -148,7 +139,7 @@ describe('persisted topic list across a reload', () => {vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);const session2 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scope)),+ wrapper: wrapper(makeProvider()),});await waitFor(() =>@@ -170,7 +161,7 @@ describe('persisted topic list across a reload', () => {vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scope)),+ wrapper: wrapper(makeProvider()),});await waitFor(() =>@@ -220,7 +211,7 @@ describe('persisted topic list across a reload', () => {vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);const session2 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scope)),+ wrapper: wrapper(makeProvider()),});await waitFor(() =>@@ -233,7 +224,7 @@ describe('persisted topic list across a reload', () => {it('does not treat a cached agent-view row as server confirmation', async () => {const scope = createScope();- const provider = makeProvider(scope);+ const provider = makeProvider();const activeTopic = { ...runningTopic, status: 'active' };// Prime the management-page cache with the same status a later terminal@@ -312,7 +303,7 @@ describe('persisted topic list across a reload', () => {const topic = { ...runningTopic, id: 'tpc-unloaded-container' };vi.mocked(topicService.getTopics).mockResolvedValue({ items: [topic], total: 1 } as any);const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scope)),+ wrapper: wrapper(makeProvider()),});await waitFor(async () => expect(await persistedTopicStatus(scope, topic.id)).toBe('running'));session1.unmount();@@ -337,7 +328,7 @@ describe('persisted topic list across a reload', () => {act(() => useChatStore.setState({ activeAgentId: AGENT_ID }));vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);const visit = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scope)),+ wrapper: wrapper(makeProvider()),});await waitFor(() =>expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0]?.status).toBe('unread'),@@ -349,7 +340,7 @@ describe('persisted topic list across a reload', () => {const scopeA = createScope();vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);const sessionA = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scopeA)),+ wrapper: wrapper(makeProvider()),});// (status may carry an earlier test's pending pin β only presence matters)await waitFor(async () => expect(await persistedTopicStatus(scopeA)).toBeDefined());@@ -359,7 +350,7 @@ describe('persisted topic list across a reload', () => {const scopeB = useScope(`${SCOPE_PREFIX}:${randomUUID()}`);vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);const sessionB = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scopeB)),+ wrapper: wrapper(makeProvider()),});await waitFor(() => expect(sessionB.result.current.isHydrated).toBe(true));@@ -372,10 +363,10 @@ describe('persisted topic list across a reload', () => {/** @example A workspace switch while the "only mine" preference loads must not keep the previous workspace's topics on screen. */it('drops another scopeβs list on a scope switch while the sync is gated off', async () => {resetCacheScopeBroadcast();- const scopeA = createScope();+ createScope();vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);const sessionA = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scopeA)),+ wrapper: wrapper(makeProvider()),});await waitFor(() =>expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items).toHaveLength(1),@@ -384,7 +375,7 @@ describe('persisted topic list across a reload', () => {const scopeB = useScope(`${SCOPE_PREFIX}:${randomUUID()}`);const gated = renderHook(() => useChatStore().useFetchTopics(false, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider(scopeB)),+ wrapper: wrapper(makeProvider()),});act(() => broadcastCacheScope(scopeB));diff --git a/src/store/device/gitStatus/store.test.ts b/src/store/device/gitStatus/store.test.tsindex bfa1a22d65a..72f8e1de785 100644--- a/src/store/device/gitStatus/store.test.ts+++ b/src/store/device/gitStatus/store.test.ts@@ -14,7 +14,6 @@ import { SWRConfig, useSWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheScope } from '@/libs/replica';-import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';import { setScopedMutate } from '@/libs/swr/mutate';import { gitService } from '@/services/git';@@ -392,12 +391,4 @@ describe('git status replicas', () => {await waitFor(() => expect(result.current.data).toMatchObject({ ahead: 3 }));});-- // The persistence moved to replicas: the SWR cache tiers must not also keep it.- it('is not persisted by the SWR cache layer', () => {- const patterns = [...CACHE_TIERS.idb, ...CACHE_TIERS.local];- for (const name of ['gitBranch', 'gitAheadBehind', 'gitWorkingTreeStatus', 'gitWorktrees']) {- expect(patterns.some((pattern) => pattern.includes(name))).toBe(false);- }- });});diff --git a/src/store/discover/slices/market/projection.ts b/src/store/discover/slices/market/projection.tsindex 989b6c3a81f..51938b4d6fe 100644--- a/src/store/discover/slices/market/projection.ts+++ b/src/store/discover/slices/market/projection.ts@@ -16,9 +16,7 @@ import type {* viewer's own Market profile.** All of them are per identity (`cacheScope`), so an account or workspace- * switch never paints the previous one's rows. Resource names stay clear of- * the `CACHE_TIERS` patterns so the SWR persistence layer never stores a second- * copy of a sync response.+ * switch never paints the previous one's rows.*//** Read addressed by one Market identifier (agent, group or skill). */diff --git a/src/store/entityPreview/projection.ts b/src/store/entityPreview/projection.tsindex e876e29e78c..3df5bd3c11a 100644--- a/src/store/entityPreview/projection.ts+++ b/src/store/entityPreview/projection.ts@@ -38,9 +38,9 @@ export const MAX_PERSISTED_ENTITY_PREVIEWS = 100;export const ENTITY_PREVIEW_DESCRIPTION_LIMIT = 280;/**- * Entry key: `<type>/<id>`. The `/` keeps the SWR sync key clear of the legacy- * CACHE_TIERS prefixes (`task:`, `agent:`, `document:`), which would persist- * the response a second time.+ * Entry key: `<type>/<id>`. The `/` keeps the replica sync key clear of the+ * retired per-domain cache prefixes (`task:`, `agent:`, `document:`), which+ * would persist the response a second time.*/export const entityPreviewKey = ({ id, type }: EntityPreviewParams) => `${type}/${id}`;diff --git a/src/store/home/slices/recent/action.test.ts b/src/store/home/slices/recent/action.test.tsindex b0a4c7c8139..ff2276b0284 100644--- a/src/store/home/slices/recent/action.test.ts+++ b/src/store/home/slices/recent/action.test.ts@@ -8,14 +8,12 @@ import { randomUUID } from 'node:crypto';import type { RecentItem } from '@lobechat/types';import { act, renderHook, waitFor } from '@testing-library/react';-import { replicaKeys } from 'local-replica';import type { PropsWithChildren } from 'react';import { createElement, useEffect } from 'react';-import { SWRConfig, unstable_serialize, useSWRConfig } from 'swr';+import { SWRConfig, useSWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheScope } from '@/libs/replica';-import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';import { setScopedMutate } from '@/libs/swr/mutate';import { fileService } from '@/services/file';import { recentService } from '@/services/recent';@@ -270,25 +268,6 @@ describe('Home topic and tray recents on the recentList replica', () => {expect(SIDEBAR).toBe('limit:11');});- it('keeps the new sync keys out of the legacy SWR persistence tiers', () => {- for (const params of [HOME_TOPIC_RECENTS_PARAMS, TRAY_RECENTS_PARAMS]) {- const serialized = unstable_serialize(- replicaKeys.sync(- recentListResource.name,- recentListResource.version,- scope,- recentListResource.key(params),- params,- ),- );- expect(- [...CACHE_TIERS.idb, ...CACHE_TIERS.local].filter((pattern) =>- serialized.includes(pattern),- ),- ).toEqual([]);- }- });-it('asks the server for the same rows as before', async () => {const getAll = vi.spyOn(recentService, 'getAll').mockResolvedValue([]);diff --git a/src/store/home/slices/recent/projection.ts b/src/store/home/slices/recent/projection.tsindex 593189ef525..4e5d26c89c2 100644--- a/src/store/home/slices/recent/projection.ts+++ b/src/store/home/slices/recent/projection.ts@@ -29,8 +29,7 @@ export interface RecentListParams {/*** Entry key of one recents query (`recentListMap[...]`). Sidebar queries keep* the original `limit:N` key so their persisted rows still hydrate. The others- * use `/` separators: the key ends up in the SWR sync key, and a `topic:`- * substring would match a legacy CACHE_TIERS pattern and be persisted twice.+ * use `/` separators, which keeps their entry keys stable for persisted rows.*/export const createRecentQueryKey = (limit: number,diff --git a/src/store/library/slices/ragEval/actions/dataset.ts b/src/store/library/slices/ragEval/actions/dataset.tsindex d37fd649e77..95abc2266aa 100644--- a/src/store/library/slices/ragEval/actions/dataset.ts+++ b/src/store/library/slices/ragEval/actions/dataset.ts@@ -1,11 +1,6 @@-import {- type CreateNewEvalDatasets,- type EvalDatasetRecord,- type RAGEvalDataSetItem,-} from '@lobechat/types';-import { type SWRResponse } from 'swr';+import { type CreateNewEvalDatasets } from '@lobechat/types';-import { mutate, useClientDataSWR } from '@/libs/swr';+import { mutate } from '@/libs/swr';import { ragEvalKeys } from '@/libs/swr/keys';import { ragEvalService } from '@/services/ragEval';import { type KnowledgeBaseStore } from '@/store/library/store';@@ -20,11 +15,10 @@ export const createRagEvalDatasetSlice = (export class RAGEvalDatasetActionImpl {readonly #get: () => KnowledgeBaseStore;- readonly #set: Setter;- constructor(set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) {+ constructor(_set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) {+ void _set;void _api;- this.#set = set;this.#get = get;}@@ -41,27 +35,6 @@ export class RAGEvalDatasetActionImpl {await ragEvalService.removeDataset(id);await this.#get().refreshDatasetList();};-- useFetchDatasetRecords = (datasetId: string | null): SWRResponse<EvalDatasetRecord[]> => {- return useClientDataSWR<EvalDatasetRecord[]>(- !!datasetId ? ragEvalKeys.datasetRecords(datasetId) : null,- () => ragEvalService.getDatasetRecords(datasetId!),- );- };-- useFetchDatasets = (knowledgeBaseId: string): SWRResponse<RAGEvalDataSetItem[]> => {- return useClientDataSWR<RAGEvalDataSetItem[]>(- ragEvalKeys.datasetList(knowledgeBaseId),- () => ragEvalService.getDatasets(knowledgeBaseId),- {- fallbackData: [],- onSuccess: () => {- if (!this.#get().initDatasetList)- this.#set({ initDatasetList: true }, false, 'useFetchDatasets/init');- },- },- );- };}export type RAGEvalDatasetAction = Pick<RAGEvalDatasetActionImpl, keyof RAGEvalDatasetActionImpl>;diff --git a/src/store/library/slices/ragEval/actions/evaluation.ts b/src/store/library/slices/ragEval/actions/evaluation.tsindex f77b1cc71a7..4af70464bf2 100644--- a/src/store/library/slices/ragEval/actions/evaluation.ts+++ b/src/store/library/slices/ragEval/actions/evaluation.ts@@ -1,7 +1,6 @@-import { type CreateNewEvalEvaluation, type RAGEvalDataSetItem } from '@lobechat/types';-import { type SWRResponse } from 'swr';+import { type CreateNewEvalEvaluation } from '@lobechat/types';-import { mutate, useClientDataSWR } from '@/libs/swr';+import { mutate } from '@/libs/swr';import { ragEvalKeys } from '@/libs/swr/keys';import { ragEvalService } from '@/services/ragEval';import { type KnowledgeBaseStore } from '@/store/library/store';@@ -16,11 +15,10 @@ export const createRagEvalEvaluationSlice = (export class RAGEvalEvaluationActionImpl {readonly #get: () => KnowledgeBaseStore;- readonly #set: Setter;- constructor(set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) {+ constructor(_set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) {+ void _set;void _api;- this.#set = set;this.#get = get;}@@ -45,20 +43,6 @@ export class RAGEvalEvaluationActionImpl {runEvaluation = async (id: string): Promise<void> => {await ragEvalService.startEvaluationTask(id);};-- useFetchEvaluationList = (knowledgeBaseId: string): SWRResponse<RAGEvalDataSetItem[]> => {- return useClientDataSWR<RAGEvalDataSetItem[]>(- ragEvalKeys.evaluationList(knowledgeBaseId),- () => ragEvalService.getEvaluationList(knowledgeBaseId),- {- fallbackData: [],- onSuccess: () => {- if (!this.#get().initDatasetList)- this.#set({ initDatasetList: true }, false, 'useFetchDatasets/init');- },- },- );- };}export type RAGEvalEvaluationAction = Pick<diff --git a/src/store/tool/slices/plugin/action.test.ts b/src/store/tool/slices/plugin/action.test.tsindex 3fb3f5548a0..7e714ce4d17 100644--- a/src/store/tool/slices/plugin/action.test.ts+++ b/src/store/tool/slices/plugin/action.test.ts@@ -20,19 +20,6 @@ beforeEach(() => {});describe('useToolStore:plugin', () => {- describe('checkPluginsIsInstalled', () => {- it('should be deprecated and do nothing', async () => {- // Old plugin system has been deprecated- const { result } = renderHook(() => useToolStore());-- await act(async () => {- await result.current.checkPluginsIsInstalled(['plugin1', 'plugin2']);- });-- // Should not call any methods since old plugin system is deprecated- });- });-describe('updatePluginSettings', () => {it('should update settings for a given plugin', async () => {const pluginId = 'test-plugin';diff --git a/src/store/tool/slices/plugin/action.ts b/src/store/tool/slices/plugin/action.tsindex 58bbdff6d12..b3e137d062c 100644--- a/src/store/tool/slices/plugin/action.ts+++ b/src/store/tool/slices/plugin/action.ts@@ -98,10 +98,6 @@ export class PluginActionImpl {throw new Error('The installed plugins have not been loaded from the server');};- checkPluginsIsInstalled = async (_plugins: string[]): Promise<void> => {- // Old plugin system has been deprecated, skip auto-installation- };-/*** Fetch the installed plugins and confirm the replica with them. The painted* list stays on screen while the network answers.@@ -241,10 +237,6 @@ export class PluginActionImpl {{ revalidateOnFocus: false, revalidateOnReconnect: false },);- useCheckPluginsIsInstalled = (enable: boolean, plugins: string[]): SWRResponse => {- return useClientDataSWR(enable ? plugins : null, this.#get().checkPluginsIsInstalled);- };-validatePluginSettings = async (identifier: string): Promise<ValidationResult | undefined> => {// Validate the full record: the display projection has no settings, so it// would report every required field as missing.diff --git a/src/store/trash/action.test.ts b/src/store/trash/action.test.tsindex dd902d160ac..35157c7ac88 100644--- a/src/store/trash/action.test.ts+++ b/src/store/trash/action.test.ts@@ -117,7 +117,6 @@ describe('TrashAction', () => {expect(restored).toBeTruthy();expect(restored(['agent:list', true])).toBe(true);expect(restored(['replica:sync', 'topicList', 1, 'scope', 'agent_x', {}])).toBe(true);- expect(restored(['agentSync:list', true, 'scope'])).toBe(true);expect(restored(['message:list', { agentId: 'a', topicId: 't' }, 1])).toBe(true);expect(restored(['trash:list', 'all'])).toBe(false);expect(restored('not-an-array')).toBe(false);diff --git a/src/store/trash/action.ts b/src/store/trash/action.tsindex dd2d266cfd4..ce931905806 100644--- a/src/store/trash/action.ts+++ b/src/store/trash/action.ts@@ -29,26 +29,21 @@ const n = setNamespace('trash');type Setter = StoreSetter<TrashStore>;-/** SWR key roots whose lists can regain rows after a restore. */+/**+ * SWR key roots whose lists can regain rows after a restore. Lists painted from+ * a local copy are replicas and revalidate through their `replica:sync` keys;+ * the rest are the in-memory SWR keys still registered in `@/libs/swr/keys`.+ */const RESTORE_AFFECTED_KEY_PREFIXES = ['agent:',- // Agent sidebar sync keys (#18913) live outside `agent:` so they skip SWR persistence.- 'agentSync:',- 'document:',- 'file:',- 'group:',- 'home:','image:',- // Replicas (topic list, β¦) sync through `replica:sync` keys (`local-replica`).+ // Replicas (agent sidebar, topic list, documents, tasks, recents, β¦) sync+ // through `replica:sync` keys (`local-replica`).'replica:',// conversation transcripts β a restored message must reappear in its thread'message:','page','project',- 'recent:',- 'resource:',- 'session:',- 'task:','topic:','video:',];