🤯 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): centralize session/thread/recent/group keys into swrKeys registry (#15848)
Arvin Xuae88d7535f18
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsxindex 559517e4f26..ce7a227b680 100644--- a/src/layout/GlobalProvider/CacheHydrationGate.tsx+++ b/src/layout/GlobalProvider/CacheHydrationGate.tsx@@ -1,8 +1,10 @@'use client';+import { Center, Flexbox } from '@lobehub/ui';import { type PropsWithChildren, useEffect, useState } from 'react';import { useSyncExternalStore } from 'react';+import { ProductLogo } from '@/components/Branding';import { cacheHydration } from '@/libs/swr/cacheHydration';import { useCacheScope } from '@/libs/swr/useCacheScope';import { useUserStore } from '@/store/user';@@ -44,7 +46,17 @@ const CacheHydrationGate = ({ children }: PropsWithChildren) => {}, [ready, scope]);// Only gate once auth has resolved (so we wait on the real scope, not anon).- if (isAuthLoaded && !ready && !timedOut) return null;+ // While gating, mirror the boot loading screen (centered brand logo) rather+ // than blanking the page, so the hand-off from the static HTML loading screen+ // to the routed app stays seamless instead of flashing white.+ if (isAuthLoaded && !ready && !timedOut)+ return (+ <Flexbox height={'100%'} style={{ userSelect: 'none' }} width={'100%'}>+ <Center flex={1} gap={16} width={'100%'}>+ <ProductLogo size={48} type={'combine'} />+ </Center>+ </Flexbox>+ );return <>{children}</>;};diff --git a/src/layout/GlobalProvider/Query.tsx b/src/layout/GlobalProvider/Query.tsxindex bee827b48d9..1f99674505c 100644--- a/src/layout/GlobalProvider/Query.tsx+++ b/src/layout/GlobalProvider/Query.tsx@@ -2,7 +2,7 @@import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { type PropsWithChildren } from 'react';-import React, { useEffect, useRef, useState } from 'react';+import React, { useLayoutEffect, useRef, useState } from 'react';import { type Cache, SWRConfig } from 'swr';import { cacheHydration } from '@/libs/swr/cacheHydration';@@ -28,11 +28,20 @@ const QueryProvider = ({ children }: PropsWithChildren) => {// Re-hydrate the cache from the new scope's namespace whenever the signed-in// user or active workspace changes (e.g. once async auth resolves), so data// never leaks across scopes and the correct local data is surfaced.+ //+ // Clear the new scope's hydration readiness *before* reloading: a scope we+ // visited earlier is still marked ready, so without this the boot gate would+ // render children immediately while `reloadScope()` has just dropped the+ // persisted entries and the IndexedDB re-load is still in flight — surfacing+ // empty/stale data that then flashes. Reset → reload → `markReady` (fired by+ // the provider once IDB finishes) keeps the gate blocking through the reload.+ // Run in a layout effect so the reset lands before paint, avoiding the flash.const scope = useCacheScope();const lastScope = useRef(scope);- useEffect(() => {+ useLayoutEffect(() => {if (lastScope.current === scope) return;lastScope.current = scope;+ cacheHydration.reset(scope);provider.reloadScope?.();}, [scope, provider]);diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 8e219c68bc2..ad93dfd9392 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -33,11 +33,21 @@ const def = <A extends unknown[]>(): KeyFactory<A> => Object.assign(build, { root });// ---- message ------------------------------------------------------------+/**+ * Message cache schema version. Baked into the message list key so a bump+ * invalidates every persisted message cache entry (e.g. after a message shape+ * change), without touching other domains. Increment when the cached+ * `UIChatMessage[]` shape changes incompatibly.+ */+export const MESSAGE_CACHE_VERSION = 1;+export const messageKeys = {- /** Conversation store messages, keyed by request context. */- list: def('message:list', (context: unknown) => ['message:list', context]),- /** Legacy chat store messages, keyed by request context. */- listLegacy: def('message:listLegacy', (context: unknown) => ['message:listLegacy', context]),+ /**+ * Messages for a conversation, keyed by request context + cache version.+ * Shared by the conversation store and the chat store so a single fetch+ * serves both.+ */+ list: def('message:list', (context: unknown) => ['message:list', context, MESSAGE_CACHE_VERSION]),};// ---- topic --------------------------------------------------------------@@ -69,6 +79,26 @@ export const agentKeys = {// ---- group --------------------------------------------------------------export const groupKeys = {detail: def('group:detail', (groupId: string) => ['group:detail', groupId]),+ list: def('group:list', (isLogin: boolean) => ['group:list', isLogin]),+};++// ---- session ------------------------------------------------------------+export const sessionKeys = {+ list: def('session:list', (isLogin: boolean | undefined) => ['session:list', isLogin]),+ search: def('session:search', (keyword?: string) => ['session:search', keyword]),+};++// ---- thread -------------------------------------------------------------+export const threadKeys = {+ list: def('thread:list', (topicId: string) => ['thread:list', topicId]),+};++// ---- recent -------------------------------------------------------------+export const recentKeys = {+ /** Home "all recents" drawer list, keyed by open state. */+ allDrawer: def('recent:allDrawer', (open: boolean) => ['recent:allDrawer', open]),+ /** Home recents list, keyed by login + limit. */+ list: def('recent:list', (isLogin: boolean, limit: number) => ['recent:list', isLogin, limit]),};// ---- task ---------------------------------------------------------------@@ -83,6 +113,52 @@ export const briefKeys = {list: def('brief:list', (isLogin: boolean) => ['brief:list', isLogin]),};+// ---- agent config / available / search ----------------------------------+// (agentKeys.list defined above)+export const agentConfigKeys = {+ available: def('agent:available', () => ['agent:available']),+ config: def('agent:config', (agentId: string) => ['agent:config', agentId]),+ search: def('agent:search', (keyword?: string) => ['agent:search', keyword]),+};++// ---- aiModel ------------------------------------------------------------+export const aiModelKeys = {+ list: def('aiModel:list', (provider: string | undefined) => ['aiModel:list', provider]),+};++// ---- image generation ---------------------------------------------------+export const imageKeys = {+ generationBatches: def('image:generationBatches', (topicId: string) => [+ 'image:generationBatches',+ topicId,+ ]),+ generationStatus: def('image:generationStatus', (generationId: string, asyncTaskId?: string) => [+ 'image:generationStatus',+ generationId,+ asyncTaskId,+ ]),+ generationTopics: def('image:generationTopics', () => ['image:generationTopics']),+};++// ---- video generation ---------------------------------------------------+export const videoKeys = {+ generationBatches: def('video:generationBatches', (topicId: string) => [+ 'video:generationBatches',+ topicId,+ ]),+ generationStatus: def('video:generationStatus', (generationId: string, asyncTaskId?: string) => [+ 'video:generationStatus',+ generationId,+ asyncTaskId,+ ]),+ generationTopics: def('video:generationTopics', () => ['video:generationTopics']),+};++// ---- serverConfig -------------------------------------------------------+export const serverConfigKeys = {+ get: 'serverConfig:get' as const,+};+/*** Build a `mutate` matcher that selects every key in a `domain:` namespace.*@@ -97,13 +173,20 @@ export const matchDomain =* Aggregate registry — one entry point for every domain's keys.*/export const swrKeys = {- agent: agentKeys,+ agent: { ...agentKeys, ...agentConfigKeys },agentDocument: agentDocumentSWRKeys,+ aiModel: aiModelKeys,brief: briefKeys,document: documentSWRKeys,group: groupKeys,+ image: imageKeys,message: messageKeys,notebook: notebookSWRKeys,+ recent: recentKeys,+ serverConfig: serverConfigKeys,+ session: sessionKeys,task: taskKeys,+ thread: threadKeys,topic: topicKeys,+ video: videoKeys,};diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.tsindex 69497362428..49e0e9a0df3 100644--- a/src/libs/swr/localStorageProvider.test.ts+++ b/src/libs/swr/localStorageProvider.test.ts@@ -192,7 +192,7 @@ describe('createCacheProvider — tiering', () => {it('exposes the central tier config keyed by domain prefix', () => {expect(CACHE_TIERS.idb).toContain('message:');expect(CACHE_TIERS.idb).toContain('topic:');- expect(CACHE_TIERS.local).toContain('fetchRecents');+ expect(CACHE_TIERS.local).toContain('recent:list');});});diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsindex fdf9e61c896..3313ee13c6b 100644--- a/src/libs/swr/localStorageProvider.ts+++ b/src/libs/swr/localStorageProvider.ts@@ -285,13 +285,31 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS}}- // Flush both tiers immediately on unload.- window.addEventListener('beforeunload', () => {- if (localTimer) clearTimeout(localTimer);- if (idbTimer) clearTimeout(idbTimer);+ // 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) => {@@ -371,11 +389,11 @@ export const CACHE_TIERS = {],/** Small, frequently-changing list shells → localStorage (sync first paint). */local: [- 'fetchRecents',+ 'recent:list','fetchRecentTopics','fetchRecentResources','fetchRecentPages',- 'fetchGroups',+ 'group:list',],} as const;diff --git a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsxindex 2856c8c5ed4..65b2c863473 100644--- a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx+++ b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx@@ -10,8 +10,8 @@ import SkeletonList from '@/features/NavPanel/components/SkeletonList';import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { useClientDataSWR } from '@/libs/swr';+import { recentKeys } from '@/libs/swr/keys';import { recentService } from '@/services/recent';-import { ALL_RECENTS_DRAWER_SWR_PREFIX } from '@/store/home/slices/recent/action';import RecentListItem from './Item';@@ -25,7 +25,7 @@ const AllRecentsDrawer = memo<AllRecentsDrawerProps>(({ open, onClose }) => {const [searchKeyword, setSearchKeyword] = useState('');const { data: recents, isLoading } = useClientDataSWR(- open ? [ALL_RECENTS_DRAWER_SWR_PREFIX, open] : null,+ open ? recentKeys.allDrawer(open) : null,() => recentService.getAll(50),);diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex c00a36088fa..93fa0424421 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -9,6 +9,7 @@ import type { PartialDeep } from 'type-fest';import { MESSAGE_CANCEL_FLAT } from '@/const/message';import { mutate, useClientDataSWRWithSync } from '@/libs/swr';+import { agentConfigKeys } from '@/libs/swr/keys';import type { AvailableAgentItem, CreateAgentParams, CreateAgentResult } from '@/services/agent';import { agentService, AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT } from '@/services/agent';import {@@ -32,12 +33,6 @@ import type { AgentStore } from '../../store';import { setLocalAgentWorkingDirectory } from '../../utils/localAgentWorkingDirectoryStorage';import type { AgentSliceState, LoadingState, SaveStatus } from './initialState';-const FETCH_AGENT_CONFIG_KEY = 'FETCH_AGENT_CONFIG';-const FETCH_AVAILABLE_AGENTS_KEY = 'FETCH_AVAILABLE_AGENTS';-const FETCH_AVAILABLE_AGENTS_SWR_KEY = [- FETCH_AVAILABLE_AGENTS_KEY,- AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT,-] as const;type AgentMetaUpdate = Partial<Pick<AgentItem,@@ -291,7 +286,7 @@ export class AgentSliceActionImpl {): SWRResponse<LobeAgentConfig> => {const swrKey =isLogin === true && agentId && !isChatGroupSessionId(agentId)- ? ([FETCH_AGENT_CONFIG_KEY, agentId] as const)+ ? agentConfigKeys.config(agentId): null;return useClientDataSWRWithSync<LobeAgentConfig>(@@ -335,7 +330,9 @@ export class AgentSliceActionImpl {this.#clearAgentConfigError(id);- await mutate((key) => Array.isArray(key) && key[0] === FETCH_AGENT_CONFIG_KEY && key[1] === id);+ await mutate(+ (key) => Array.isArray(key) && key[0] === agentConfigKeys.config.root && key[1] === id,+ );};#clearAgentConfigError = (agentId: string) => {@@ -358,7 +355,7 @@ export class AgentSliceActionImpl {): SWRResponse<LobeAgentConfig> => {const swrKey =isLogin === true && agentId && !isChatGroupSessionId(agentId)- ? ([FETCH_AGENT_CONFIG_KEY, agentId] as const)+ ? agentConfigKeys.config(agentId): null;return useClientDataSWRWithSync<LobeAgentConfig>(@@ -388,7 +385,7 @@ export class AgentSliceActionImpl {useFetchAvailableAgents = (enabled: boolean): SWRResponse<AvailableAgentItem[]> => {return useClientDataSWRWithSync<AvailableAgentItem[]>(- enabled ? FETCH_AVAILABLE_AGENTS_SWR_KEY : null,+ enabled ? agentConfigKeys.available() : null,() => agentService.queryAgents({ limit: AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT }),{onData: (data) => {@@ -401,7 +398,7 @@ export class AgentSliceActionImpl {invalidateAvailableAgents = (): void => {this.#set({ availableAgents: undefined }, false, 'invalidateAvailableAgents');- void mutate(FETCH_AVAILABLE_AGENTS_SWR_KEY);+ void mutate(agentConfigKeys.available());};ensureAgentDocuments = async (@@ -509,7 +506,7 @@ export class AgentSliceActionImpl {};internal_refreshAgentConfig = async (id: string): Promise<void> => {- await mutate([FETCH_AGENT_CONFIG_KEY, id]);+ await mutate(agentConfigKeys.config(id));};internal_createAbortController = (key: keyof AgentSliceState): AbortController => {diff --git a/src/store/agentGroup/action.ts b/src/store/agentGroup/action.tsindex a85a60020d8..5b1084c36d1 100644--- a/src/store/agentGroup/action.ts+++ b/src/store/agentGroup/action.ts@@ -24,8 +24,6 @@ import { ChatGroupMemberAction } from './slices/member';const n = setNamespace('chatGroup');-const FETCH_GROUPS_KEY = 'fetchGroups';-/*** Convert ChatGroupItem to AgentGroupDetail by adding empty agents array if not present*/@@ -145,7 +143,7 @@ class ChatGroupInternalAction implements ResetableStore {};refreshGroups = async () => {- await mutate([FETCH_GROUPS_KEY, true]);+ await mutate(groupKeys.list(true));};toggleGroupSetting = (open: boolean) => {@@ -220,7 +218,7 @@ class ChatGroupInternalAction implements ResetableStore {// This is not used for now, as we are combining group in the session lambda's responseuseFetchGroups = (enabled: boolean, isLogin: boolean) =>useClientDataSWRWithSync<ChatGroupItem[]>(- enabled ? [FETCH_GROUPS_KEY, isLogin] : null,+ enabled ? groupKeys.list(isLogin) : null,async () => chatGroupService.getGroups(),{fallbackData: [],diff --git a/src/store/aiInfra/slices/aiModel/action.test.ts b/src/store/aiInfra/slices/aiModel/action.test.tsindex 103010767cd..e01018b0f5d 100644--- a/src/store/aiInfra/slices/aiModel/action.test.ts+++ b/src/store/aiInfra/slices/aiModel/action.test.ts@@ -367,7 +367,7 @@ describe('AiModelAction', () => {await result.current.refreshAiModelList();});- expect(mutate).toHaveBeenCalledWith(['FETCH_AI_PROVIDER_MODELS', 'test-provider']);+ expect(mutate).toHaveBeenCalledWith(['aiModel:list', 'test-provider']);expect(refreshRuntimeSpy).toHaveBeenCalled();});});diff --git a/src/store/aiInfra/slices/aiModel/action.ts b/src/store/aiInfra/slices/aiModel/action.tsindex 47475bb3598..9a2454c46a0 100644--- a/src/store/aiInfra/slices/aiModel/action.ts+++ b/src/store/aiInfra/slices/aiModel/action.ts@@ -8,12 +8,11 @@ import {import { type SWRResponse } from 'swr';import { mutate, useClientDataSWR } from '@/libs/swr';+import { aiModelKeys } from '@/libs/swr/keys';import { aiModelService } from '@/services/aiModel';import { type AiInfraStore } from '@/store/aiInfra/store';import { type StoreSetter } from '@/store/types';-const FETCH_AI_PROVIDER_MODEL_LIST_KEY = 'FETCH_AI_PROVIDER_MODELS';-type Setter = StoreSetter<AiInfraStore>;export const createAiModelSlice = (set: Setter, get: () => AiInfraStore, _api?: unknown) =>new AiModelActionImpl(set, get, _api);@@ -99,7 +98,7 @@ export class AiModelActionImpl {};refreshAiModelList = async (): Promise<void> => {- await mutate([FETCH_AI_PROVIDER_MODEL_LIST_KEY, this.#get().activeAiProvider]);+ await mutate(aiModelKeys.list(this.#get().activeAiProvider));// make refresh provide runtime state async, not blockthis.#get().refreshAiProviderRuntimeState();};@@ -139,7 +138,7 @@ export class AiModelActionImpl {useFetchAiProviderModels = (id: string): SWRResponse<AiProviderModelListItem[]> => {return useClientDataSWR<AiProviderModelListItem[]>(- [FETCH_AI_PROVIDER_MODEL_LIST_KEY, id],+ aiModelKeys.list(id),([, id]) => aiModelService.getAiProviderModelList(id as string),{onSuccess: (data) => {diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.tsindex a3a99a61298..008b3a2cb8b 100644--- a/src/store/chat/slices/message/action.test.ts+++ b/src/store/chat/slices/message/action.test.ts@@ -736,32 +736,30 @@ describe('chatMessage actions', () => {// 在每个测试用例开始前恢复到实际的 SWR 实现vi.resetAllMocks();});- it('should refresh messages by calling mutate for both session and group types', async () => {+ it('should refresh messages by invalidating message:list for the active agent+topic', async () => {useChatStore.setState({ refreshMessages: realRefreshMessages });const { result } = renderHook(() => useChatStore());const activeAgentId = useChatStore.getState().activeAgentId;const activeTopicId = useChatStore.getState().activeTopicId;- // 在这里,我们不需要再次模拟 mutate,因为它已经在顶部被模拟了await act(async () => {await result.current.refreshMessages();});- // 确保 mutate 调用了正确的参数(session 和 group 两次)- expect(mutate).toHaveBeenCalledWith([- 'SWR_USE_FETCH_MESSAGES',- activeAgentId,- activeTopicId,- 'session',- ]);- expect(mutate).toHaveBeenCalledWith([- 'SWR_USE_FETCH_MESSAGES',- activeAgentId,- activeTopicId,- 'group',- ]);- expect(mutate).toHaveBeenCalledTimes(2);+ // refreshMessages now mutates with a single matcher targeting the+ // accurate `message:list` key for this agent+topic.+ expect(mutate).toHaveBeenCalledTimes(1);+ const matcher = (mutate as any).mock.calls[0][0];+ expect(typeof matcher).toBe('function');+ expect(matcher(['message:list', { agentId: activeAgentId, topicId: activeTopicId }, 1])).toBe(+ true,+ );+ // other domains / other topics are not matched+ expect(matcher(['topic:list', 'container', {}])).toBe(false);+ expect(matcher(['message:list', { agentId: activeAgentId, topicId: 'other' }, 1])).toBe(+ false,+ );});it('should handle errors during refreshing messages', async () => {useChatStore.setState({ refreshMessages: realRefreshMessages });diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.tsindex 37cb9b5fa73..4574804449f 100644--- a/src/store/chat/slices/message/actions/query.ts+++ b/src/store/chat/slices/message/actions/query.ts@@ -13,8 +13,6 @@ import { type MessageMapKeyInput } from '../../../utils/messageMapKey';import { messageMapKey } from '../../../utils/messageMapKey';import { reconcileAssistantToolLinks } from '../utils/reconcileTools';-const SWR_USE_FETCH_MESSAGES = 'SWR_USE_FETCH_MESSAGES';-/*** Data query and synchronization actions* Handles fetching, refreshing, and replacing message data@@ -37,9 +35,14 @@ export class MessageQueryActionImpl {refreshMessages = async (context?: Partial<ConversationContext>): Promise<void> => {const agentId = context?.agentId ?? this.#get().activeAgentId;const topicId = context?.topicId !== undefined ? context.topicId : this.#get().activeTopicId;- // TODO: Support threadId refresh when needed- await mutate([SWR_USE_FETCH_MESSAGES, agentId, topicId, 'session']);- await mutate([SWR_USE_FETCH_MESSAGES, agentId, topicId, 'group']);+ // Invalidate every `message:list` entry for this agent+topic (any scope /+ // thread / page-size variant). The key shape is+ // `[message:list, ConversationContext, version]`, so match on key[1].+ await mutate((key) => {+ if (!Array.isArray(key) || key[0] !== messageKeys.list.root) return false;+ const ctx = key[1] as ConversationContext | undefined;+ return !!ctx && ctx.agentId === agentId && ctx.topicId === topicId;+ });};replaceMessages = (@@ -137,7 +140,7 @@ export class MessageQueryActionImpl {const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;return useClientDataSWRWithSync<UIChatMessage[]>(- shouldFetch ? messageKeys.listLegacy(context) : null,+ shouldFetch ? messageKeys.list(context) : null,() => messageService.getMessages(context),{onData: (data) => {diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.tsindex 11d5cf7e16a..e8f92a37e4c 100644--- a/src/store/chat/slices/thread/action.test.ts+++ b/src/store/chat/slices/thread/action.test.ts@@ -473,7 +473,7 @@ describe('thread action', () => {await result.current.refreshThreads();});- expect(mutate).toHaveBeenCalledWith(['SWR_USE_FETCH_THREADS', 'test-topic-id']);+ expect(mutate).toHaveBeenCalledWith(['thread:list', 'test-topic-id']);});it('should not mutate when activeTopicId is undefined', async () => {diff --git a/src/store/chat/slices/thread/action.ts b/src/store/chat/slices/thread/action.tsindex b26dd1bb7e0..854149304f6 100644--- a/src/store/chat/slices/thread/action.ts+++ b/src/store/chat/slices/thread/action.ts@@ -11,6 +11,7 @@ import isEqual from 'fast-deep-equal';import { type SWRResponse } from 'swr';import { mutate, useClientDataSWR } from '@/libs/swr';+import { threadKeys } from '@/libs/swr/keys';import { chatService } from '@/services/chat';import { threadService } from '@/services/thread';import { threadSelectors } from '@/store/chat/selectors';@@ -28,7 +29,6 @@ import { threadReducer } from './reducer';import { genParentMessages } from './selectors';const n = setNamespace('thd');-const SWR_USE_FETCH_THREADS = 'SWR_USE_FETCH_THREADS';type Setter = StoreSetter<ChatStore>;export const chatThreadMessage = (set: Setter, get: () => ChatStore, _api?: unknown) =>@@ -153,7 +153,7 @@ export class ChatThreadActionImpl {useFetchThreads = (enable: boolean, topicId?: string): SWRResponse<ThreadItem[]> => {return useClientDataSWR<ThreadItem[]>(- enable && !!topicId ? [SWR_USE_FETCH_THREADS, topicId] : null,+ enable && !!topicId ? threadKeys.list(topicId) : null,async ([, topicId]: [string, string]) => threadService.getThreads(topicId),{onSuccess: (threads) => {@@ -176,7 +176,7 @@ export class ChatThreadActionImpl {const topicId = this.#get().activeTopicId;if (!topicId) return;- return mutate([SWR_USE_FETCH_THREADS, topicId]);+ return mutate(threadKeys.list(topicId));};removeThread = async (id: string): Promise<void> => {diff --git a/src/store/home/slices/agentList/action.ts b/src/store/home/slices/agentList/action.tsindex 9743e928a3f..09c6b4c8c82 100644--- a/src/store/home/slices/agentList/action.ts+++ b/src/store/home/slices/agentList/action.ts@@ -3,7 +3,7 @@ import { type SWRResponse } from 'swr';import { type SidebarAgentItem, type SidebarAgentListResponse } from '@/database/repositories/home';import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';-import { agentKeys } from '@/libs/swr/keys';+import { agentConfigKeys, agentKeys } from '@/libs/swr/keys';import { homeService } from '@/services/home';import { getAgentStoreState } from '@/store/agent';import { type HomeStore } from '@/store/home/store';@@ -14,8 +14,6 @@ import { mapResponseToState } from './initialState';const n = setNamespace('agentList');-const SEARCH_AGENTS_KEY = 'searchAgents';-type Setter = StoreSetter<HomeStore>;export const createAgentListSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>new AgentListActionImpl(set, get, _api);@@ -76,7 +74,7 @@ export class AgentListActionImpl {};useSearchAgents = (keyword?: string): SWRResponse<SidebarAgentItem[]> => {- return useClientDataSWR<SidebarAgentItem[]>([SEARCH_AGENTS_KEY, keyword], async () => {+ return useClientDataSWR<SidebarAgentItem[]>(agentConfigKeys.search(keyword), async () => {if (!keyword) return [];return homeService.searchAgents(keyword);diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.tsindex 35eadf06d0c..71dbe1a5cdc 100644--- a/src/store/home/slices/recent/action.ts+++ b/src/store/home/slices/recent/action.ts@@ -2,6 +2,7 @@ import isEqual from 'fast-deep-equal';import { type SWRResponse } from 'swr';import { mutate, useClientDataSWRWithSync } from '@/libs/swr';+import { recentKeys } from '@/libs/swr/keys';import { type RecentItem } from '@/server/routers/lambda/recent';import { recentService } from '@/services/recent';import { type HomeStore } from '@/store/home/store';@@ -10,14 +11,11 @@ import { setNamespace } from '@/utils/storeDebug';const n = setNamespace('recent');-const FETCH_RECENTS_KEY = 'fetchRecents';// Mirror the home Daily Brief / task detail polling cadence so users see new// items, status transitions (incl. backlog/paused → running which the per-item// task.detail poll never caught) without manual refresh. SWR pauses when the// tab is backgrounded.const RECENTS_REFRESH_INTERVAL = 10_000;-/** SWR key prefix for `AllRecentsDrawer` (`['allRecents', open]`) */-export const ALL_RECENTS_DRAWER_SWR_PREFIX = 'allRecents';type Setter = StoreSetter<HomeStore>;export const createRecentSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>@@ -48,8 +46,8 @@ export class RecentActionImpl {refreshRecents = async (): Promise<void> => {await Promise.all([- mutate((key: unknown) => Array.isArray(key) && key[0] === FETCH_RECENTS_KEY),- mutate((key: unknown) => Array.isArray(key) && key[0] === ALL_RECENTS_DRAWER_SWR_PREFIX),+ mutate((key: unknown) => Array.isArray(key) && key[0] === recentKeys.list.root),+ mutate((key: unknown) => Array.isArray(key) && key[0] === recentKeys.allDrawer.root),]);};@@ -58,7 +56,7 @@ export class RecentActionImpl {limit: number = 10,): SWRResponse<RecentItem[]> => {return useClientDataSWRWithSync<RecentItem[]>(- isLogin === true ? [FETCH_RECENTS_KEY, isLogin, limit] : null,+ isLogin === true ? recentKeys.list(isLogin, limit) : null,async () => recentService.getAll(limit + 1),{onData: (data) => {diff --git a/src/store/image/slices/generationBatch/action.test.ts b/src/store/image/slices/generationBatch/action.test.tsindex 4725e02915e..b59118c2640 100644--- a/src/store/image/slices/generationBatch/action.test.ts+++ b/src/store/image/slices/generationBatch/action.test.ts@@ -404,7 +404,7 @@ describe('GenerationBatchAction', () => {await result.current.refreshGenerationBatches();});- expect(mutate).toHaveBeenCalledWith(['SWR_USE_FETCH_GENERATION_BATCHES', topicId]);+ expect(mutate).toHaveBeenCalledWith(['image:generationBatches', topicId]);});it('should not call mutate when no active topic', async () => {diff --git a/src/store/image/slices/generationBatch/action.ts b/src/store/image/slices/generationBatch/action.tsindex 5891f1781f3..e6af13b94a2 100644--- a/src/store/image/slices/generationBatch/action.ts+++ b/src/store/image/slices/generationBatch/action.ts@@ -3,6 +3,7 @@ import { useRef } from 'react';import { type SWRResponse } from 'swr';import { mutate, useClientDataSWR } from '@/libs/swr';+import { imageKeys } from '@/libs/swr/keys';import { type GetGenerationStatusResult } from '@/server/routers/lambda/generation';import { generationService } from '@/services/generation';import { generationBatchService } from '@/services/generationBatch';@@ -19,8 +20,6 @@ import { generationBatchReducer } from './reducer';const n = setNamespace('generationBatch');// ====== SWR key ====== //-const SWR_USE_FETCH_GENERATION_BATCHES = 'SWR_USE_FETCH_GENERATION_BATCHES';-const SWR_USE_CHECK_GENERATION_STATUS = 'SWR_USE_CHECK_GENERATION_STATUS';// ====== action interface ====== //@@ -159,13 +158,13 @@ export class GenerationBatchActionImpl {refreshGenerationBatches = async (): Promise<void> => {const { activeGenerationTopicId } = this.#get();if (activeGenerationTopicId) {- await mutate([SWR_USE_FETCH_GENERATION_BATCHES, activeGenerationTopicId]);+ await mutate(imageKeys.generationBatches(activeGenerationTopicId));}};useFetchGenerationBatches = (topicId?: string | null): SWRResponse<GenerationBatch[]> => {return useClientDataSWR<GenerationBatch[]>(- topicId ? [SWR_USE_FETCH_GENERATION_BATCHES, topicId] : null,+ topicId ? imageKeys.generationBatches(topicId) : null,async ([, topicId]: [string, string]) => {return generationBatchService.getGenerationBatches(topicId, 'image');},@@ -202,7 +201,7 @@ export class GenerationBatchActionImpl {return useClientDataSWR<GetGenerationStatusResult>(enable && generationId && !generationId.startsWith('temp-') && asyncTaskId- ? [SWR_USE_CHECK_GENERATION_STATUS, generationId, asyncTaskId]+ ? imageKeys.generationStatus(generationId, asyncTaskId): null,async ([, generationId, asyncTaskId]: [string, string, string]) => {// Increment request countdiff --git a/src/store/image/slices/generationTopic/action.test.ts b/src/store/image/slices/generationTopic/action.test.tsindex f15fabf0e38..b62f0a49e9b 100644--- a/src/store/image/slices/generationTopic/action.test.ts+++ b/src/store/image/slices/generationTopic/action.test.ts@@ -465,7 +465,7 @@ describe('GenerationTopicAction', () => {await result.current.refreshGenerationTopics();});- expect(mutate).toHaveBeenCalledWith(['fetchGenerationTopics']);+ expect(mutate).toHaveBeenCalledWith(['image:generationTopics']);});});diff --git a/src/store/image/slices/generationTopic/action.ts b/src/store/image/slices/generationTopic/action.tsindex 34038639bd4..6aa17ab309d 100644--- a/src/store/image/slices/generationTopic/action.ts+++ b/src/store/image/slices/generationTopic/action.ts@@ -4,6 +4,7 @@ import { type SWRResponse } from 'swr';import { LOADING_FLAT } from '@/const/message';import { mutate, useClientDataSWR } from '@/libs/swr';+import { imageKeys } from '@/libs/swr/keys';import { type UpdateTopicValue } from '@/server/routers/lambda/generationTopic';import { chatService } from '@/services/chat';import { generationTopicService } from '@/services/generationTopic';@@ -19,8 +20,6 @@ import { type GenerationTopicDispatch } from './reducer';import { generationTopicReducer } from './reducer';import { generationTopicSelectors } from './selectors';-const FETCH_GENERATION_TOPICS_KEY = 'fetchGenerationTopics';-const n = setNamespace('generationTopic');type Setter = StoreSetter<ImageStore>;@@ -209,7 +208,7 @@ export class GenerationTopicActionImpl {useFetchGenerationTopics = (enabled: boolean): SWRResponse<ImageGenerationTopic[]> => {return useClientDataSWR<ImageGenerationTopic[]>(- enabled ? [FETCH_GENERATION_TOPICS_KEY] : null,+ enabled ? imageKeys.generationTopics() : null,() => generationTopicService.getAllGenerationTopics('image'),{suspense: true,@@ -223,7 +222,7 @@ export class GenerationTopicActionImpl {};refreshGenerationTopics = async (): Promise<void> => {- await mutate([FETCH_GENERATION_TOPICS_KEY]);+ await mutate(imageKeys.generationTopics());};removeGenerationTopic = async (id: string): Promise<void> => {diff --git a/src/store/serverConfig/action.test.ts b/src/store/serverConfig/action.test.tsindex fd5300b2ac4..2e0916ace46 100644--- a/src/store/serverConfig/action.test.ts+++ b/src/store/serverConfig/action.test.ts@@ -156,7 +156,7 @@ describe('ServerConfigAction', () => {store.getState().useInitServerConfig();expect(useOnlyFetchOnceSWR).toHaveBeenCalledWith(- 'FETCH_SERVER_CONFIG',+ 'serverConfig:get',expect.any(Function),expect.objectContaining({onError: expect.any(Function),@@ -172,7 +172,7 @@ describe('ServerConfigAction', () => {store.getState().useInitServerConfig();expect(useOnlyFetchOnceSWR).toHaveBeenCalledWith(- 'FETCH_SERVER_CONFIG',+ 'serverConfig:get',expect.any(Function),expect.any(Object),);diff --git a/src/store/serverConfig/action.ts b/src/store/serverConfig/action.tsindex c2eca0a5611..5cfec253ef2 100644--- a/src/store/serverConfig/action.ts+++ b/src/store/serverConfig/action.ts@@ -1,13 +1,13 @@import { type SWRResponse } from 'swr';import { useOnlyFetchOnceSWR } from '@/libs/swr';+import { serverConfigKeys } from '@/libs/swr/keys';import { globalService } from '@/services/global';import { type StoreSetter } from '@/store/types';import { type GlobalRuntimeConfig } from '@/types/serverConfig';import { type ServerConfigStore } from './store';-const FETCH_SERVER_CONFIG_KEY = 'FETCH_SERVER_CONFIG';const CLOUD_DESKTOP_BUSINESS_FEATURES_FLAG = '__LOBECLOUD_DESKTOP_BUSINESS_FEATURES__';const setDesktopBusinessFeaturesFlag = (enableBusinessFeatures: boolean | undefined) => {@@ -34,7 +34,7 @@ export class ServerConfigActionImpl {useInitServerConfig = (): SWRResponse<GlobalRuntimeConfig> => {return useOnlyFetchOnceSWR<GlobalRuntimeConfig>(- FETCH_SERVER_CONFIG_KEY,+ serverConfigKeys.get,() => globalService.getGlobalConfig(),{onError: () => {diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.tsindex 91e031cd746..deaff4fd044 100644--- a/src/store/session/slices/session/action.ts+++ b/src/store/session/slices/session/action.ts@@ -8,6 +8,7 @@ import { type PartialDeep } from 'type-fest';import { message } from '@/components/AntdStaticMethods';import { DEFAULT_AGENT_LOBE_SESSION, INBOX_SESSION_ID } from '@/const/session';import { mutate, useClientDataSWR } from '@/libs/swr';+import { sessionKeys } from '@/libs/swr/keys';import { chatGroupService } from '@/services/chatGroup';import { sessionService } from '@/services/session';import { getChatGroupStoreState } from '@/store/agentGroup';@@ -33,9 +34,6 @@ import { sessionMetaSelectors } from './selectors/meta';const n = setNamespace('session');-const FETCH_SESSIONS_KEY = 'fetchSessions';-const SEARCH_SESSIONS_KEY = 'searchSessions';-type Setter = StoreSetter<SessionStore>;export const createSessionSlice = (set: Setter, get: () => SessionStore, _api?: unknown) =>new SessionActionImpl(set, get, _api);@@ -203,7 +201,7 @@ export class SessionActionImpl {isLogin: boolean | undefined,): SWRResponse<ChatSessionList> => {return useClientDataSWR<ChatSessionList>(- enabled ? [FETCH_SESSIONS_KEY, isLogin] : null,+ enabled ? sessionKeys.list(isLogin) : null,() => sessionService.getGroupedSessions(),{fallbackData: {@@ -270,7 +268,7 @@ export class SessionActionImpl {useSearchSessions = (keyword?: string): SWRResponse<any> => {return useSWR<LobeSessions>(- [SEARCH_SESSIONS_KEY, keyword],+ sessionKeys.search(keyword),async () => {if (!keyword) return [];@@ -320,7 +318,7 @@ export class SessionActionImpl {};refreshSessions = async (): Promise<void> => {- await mutate([FETCH_SESSIONS_KEY, true]);+ await mutate(sessionKeys.list(true));};}diff --git a/src/store/video/slices/generationBatch/action.ts b/src/store/video/slices/generationBatch/action.tsindex f0a3dbffb0c..6618195772d 100644--- a/src/store/video/slices/generationBatch/action.ts+++ b/src/store/video/slices/generationBatch/action.ts@@ -3,6 +3,7 @@ import { useRef } from 'react';import type { SWRResponse } from 'swr';import { mutate, useClientDataSWR } from '@/libs/swr';+import { videoKeys } from '@/libs/swr/keys';import { type GetGenerationStatusResult } from '@/server/routers/lambda/generation';import { generationService } from '@/services/generation';import { generationBatchService } from '@/services/generationBatch';@@ -18,8 +19,6 @@ import { type GenerationBatchDispatch, generationBatchReducer } from './reducer'const n = setNamespace('generationBatch');// ====== SWR key ====== //-const SWR_USE_FETCH_GENERATION_BATCHES = 'SWR_USE_FETCH_VIDEO_GENERATION_BATCHES';-const SWR_USE_CHECK_GENERATION_STATUS = 'SWR_USE_CHECK_VIDEO_GENERATION_STATUS';type Setter = StoreSetter<VideoStore>;@@ -101,7 +100,7 @@ export class GenerationBatchActionImpl {refreshGenerationBatches = async (): Promise<void> => {const { activeGenerationTopicId } = this.#get();if (activeGenerationTopicId) {- await mutate([SWR_USE_FETCH_GENERATION_BATCHES, activeGenerationTopicId]);+ await mutate(videoKeys.generationBatches(activeGenerationTopicId));}};@@ -155,7 +154,7 @@ export class GenerationBatchActionImpl {return useClientDataSWR<GetGenerationStatusResult>(enable && generationId && !generationId.startsWith('temp-') && asyncTaskId- ? [SWR_USE_CHECK_GENERATION_STATUS, generationId, asyncTaskId]+ ? videoKeys.generationStatus(generationId, asyncTaskId): null,async ([, generationId, asyncTaskId]: [string, string, string]) => {requestCountRef.current += 1;@@ -242,7 +241,7 @@ export class GenerationBatchActionImpl {useFetchGenerationBatches = (topicId?: string | null): SWRResponse<GenerationBatch[]> =>useClientDataSWR<GenerationBatch[]>(- topicId ? [SWR_USE_FETCH_GENERATION_BATCHES, topicId] : null,+ topicId ? videoKeys.generationBatches(topicId) : null,async ([, topicId]: [string, string]) => {return generationBatchService.getGenerationBatches(topicId, 'video');},diff --git a/src/store/video/slices/generationTopic/action.ts b/src/store/video/slices/generationTopic/action.tsindex f6e65323aba..a782c74050f 100644--- a/src/store/video/slices/generationTopic/action.ts+++ b/src/store/video/slices/generationTopic/action.ts@@ -4,6 +4,7 @@ import type { SWRResponse } from 'swr';import { LOADING_FLAT } from '@/const/message';import { mutate, useClientDataSWR } from '@/libs/swr';+import { videoKeys } from '@/libs/swr/keys';import { type UpdateTopicValue } from '@/server/routers/lambda/generationTopic';import { chatService } from '@/services/chat';import { generationTopicService } from '@/services/generationTopic';@@ -18,8 +19,6 @@ import type { VideoStore } from '../../store';import { type GenerationTopicDispatch, generationTopicReducer } from './reducer';import { generationTopicSelectors } from './selectors';-const FETCH_GENERATION_TOPICS_KEY = 'fetchVideoGenerationTopics';-const n = setNamespace('videoGenerationTopic');type Setter = StoreSetter<VideoStore>;@@ -156,7 +155,7 @@ export class GenerationTopicActionImpl {};refreshGenerationTopics = async (): Promise<void> => {- await mutate([FETCH_GENERATION_TOPICS_KEY]);+ await mutate(videoKeys.generationTopics());};removeGenerationTopic = async (id: string): Promise<void> => {@@ -268,7 +267,7 @@ export class GenerationTopicActionImpl {useFetchGenerationTopics = (enabled: boolean): SWRResponse<ImageGenerationTopic[]> =>useClientDataSWR<ImageGenerationTopic[]>(- enabled ? [FETCH_GENERATION_TOPICS_KEY] : null,+ enabled ? videoKeys.generationTopics() : null,() => generationTopicService.getAllGenerationTopics('video'),{onSuccess: (data) => {