Skip to content

🤯 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.

♻️ refactor(swr): converge remaining store-layer SWR keys into swrKeys registry (#15850)

Arvin Xud6ca16819902
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index ad93dfd9392..b705fd6ca78 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -159,6 +159,157 @@ export const serverConfigKeys = {
get: 'serverConfig:get' as const,
};
+// ---- discover (marketplace) ---------------------------------------------
+// NOTE: discover/eval/ragEval/knowledgeBase/device/userMemory/agentKnowledge/
+// agentBot/file/chatTool prefixes are deliberately kept OUT of `CACHE_TIERS`
+// (see localStorageProvider.ts) so this key-convergence introduces no new
+// persistence — they stay memory-only exactly as before.
+export const discoverKeys = {
+ assistantCategories: def('discover:assistantCategories', (locale: string, params: unknown) => [
+ 'discover:assistantCategories',
+ locale,
+ params,
+ ]),
+ assistantDetail: def('discover:assistantDetail', (locale: string, params: unknown) => [
+ 'discover:assistantDetail',
+ locale,
+ params,
+ ]),
+ assistantIdentifiers: def('discover:assistantIdentifiers', (source?: string) => [
+ 'discover:assistantIdentifiers',
+ source,
+ ]),
+ assistantList: def('discover:assistantList', (locale: string, params: unknown) => [
+ 'discover:assistantList',
+ locale,
+ params,
+ ]),
+ favoriteAgents: def('discover:favoriteAgents', (userId: number, params?: unknown) => [
+ 'discover:favoriteAgents',
+ userId,
+ params,
+ ]),
+ favoritePlugins: def('discover:favoritePlugins', (userId: number, params?: unknown) => [
+ 'discover:favoritePlugins',
+ userId,
+ params,
+ ]),
+ followCounts: def('discover:followCounts', (userId: number) => ['discover:followCounts', userId]),
+ followStatus: def('discover:followStatus', (userId: number) => ['discover:followStatus', userId]),
+ followers: def('discover:followers', (userId: number, params?: unknown) => [
+ 'discover:followers',
+ userId,
+ params,
+ ]),
+ following: def('discover:following', (userId: number, params?: unknown) => [
+ 'discover:following',
+ userId,
+ params,
+ ]),
+ modelIdentifiers: def('discover:modelIdentifiers', () => ['discover:modelIdentifiers']),
+ pluginIdentifiers: def('discover:pluginIdentifiers', () => ['discover:pluginIdentifiers']),
+ providerIdentifiers: def('discover:providerIdentifiers', () => ['discover:providerIdentifiers']),
+};
+
+// ---- agent eval ---------------------------------------------------------
+export const evalKeys = {
+ benchmarkDetail: def('eval:benchmarkDetail', (id: string) => ['eval:benchmarkDetail', id]),
+ benchmarks: def('eval:benchmarks', () => ['eval:benchmarks']),
+ datasetDetail: def('eval:datasetDetail', (id: string) => ['eval:datasetDetail', id]),
+ datasetRuns: def('eval:datasetRuns', (datasetId: string) => ['eval:datasetRuns', datasetId]),
+ datasets: def('eval:datasets', (benchmarkId: string) => ['eval:datasets', benchmarkId]),
+ 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]),
+ 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,
+ ]),
+};
+
+// ---- knowledge base -----------------------------------------------------
+export const knowledgeBaseKeys = {
+ item: def('knowledgeBase:item', (id: string) => ['knowledgeBase:item', id]),
+ list: def('knowledgeBase:list', (workspaceId?: string | null) =>
+ workspaceId ? ['knowledgeBase:list', workspaceId] : ['knowledgeBase:list'],
+ ),
+};
+
+// ---- device -------------------------------------------------------------
+export const deviceKeys = {
+ gitAheadBehind: def('device:gitAheadBehind', (deviceId: string, path: string) => [
+ 'device:gitAheadBehind',
+ deviceId,
+ path,
+ ]),
+ gitInfo: def('device:gitInfo', (deviceId: string, path: string, isGithub: boolean) => [
+ 'device:gitInfo',
+ deviceId,
+ path,
+ isGithub,
+ ]),
+ gitWorkingTreeStatus: def('device:gitWorkingTreeStatus', (deviceId: string, path: string) => [
+ 'device:gitWorkingTreeStatus',
+ deviceId,
+ path,
+ ]),
+ listDevices: def('device:listDevices', () => ['device:listDevices']),
+};
+
+// ---- user memory --------------------------------------------------------
+export const userMemoryKeys = {
+ identities: def('userMemory:identities', () => ['userMemory:identities']),
+ persona: def('userMemory:persona', () => ['userMemory:persona']),
+ tags: def('userMemory:tags', () => ['userMemory:tags']),
+ topicMemories: def('userMemory:topicMemories', (topicId: string) => [
+ 'userMemory:topicMemories',
+ topicId,
+ ]),
+};
+
+// ---- agent knowledge (kept off the `agent:` idb tier on purpose) --------
+export const agentKnowledgeKeys = {
+ list: def('agentKnowledge:list', (agentId: string | undefined) => [
+ 'agentKnowledge:list',
+ agentId,
+ ]),
+};
+
+// ---- agent bot ----------------------------------------------------------
+export const agentBotKeys = {
+ platformDefinitions: def('agentBot:platformDefinitions', () => ['agentBot:platformDefinitions']),
+ providers: def('agentBot:providers', (agentId: string) => ['agentBot:providers', agentId]),
+};
+
+// ---- file ---------------------------------------------------------------
+export const fileKeys = {
+ knowledgeItems: def('file:knowledgeItems', (params: unknown) => ['file:knowledgeItems', params]),
+ ttsFile: def('file:ttsFile', (messageId: string) => ['file:ttsFile', messageId]),
+};
+
+// ---- chat tools ---------------------------------------------------------
+export const chatToolKeys = {
+ interpreterFile: def('chat:interpreterFile', (id: string) => ['chat:interpreterFile', id]),
+};
+
/**
* Build a `mutate` matcher that selects every key in a `domain:` namespace.
*
@@ -174,19 +325,29 @@ export const matchDomain =
*/
export const swrKeys = {
agent: { ...agentKeys, ...agentConfigKeys },
+ agentBot: agentBotKeys,
agentDocument: agentDocumentSWRKeys,
+ agentKnowledge: agentKnowledgeKeys,
aiModel: aiModelKeys,
brief: briefKeys,
+ chatTool: chatToolKeys,
+ device: deviceKeys,
+ discover: discoverKeys,
document: documentSWRKeys,
+ eval: evalKeys,
+ file: fileKeys,
group: groupKeys,
image: imageKeys,
+ knowledgeBase: knowledgeBaseKeys,
message: messageKeys,
notebook: notebookSWRKeys,
+ ragEval: ragEvalKeys,
recent: recentKeys,
serverConfig: serverConfigKeys,
session: sessionKeys,
task: taskKeys,
thread: threadKeys,
topic: topicKeys,
+ userMemory: userMemoryKeys,
video: videoKeys,
};
diff --git a/src/store/agent/slices/bot/action.ts b/src/store/agent/slices/bot/action.ts
index 911037c963f..26ed4a62681 100644
--- a/src/store/agent/slices/bot/action.ts
+++ b/src/store/agent/slices/bot/action.ts
@@ -1,6 +1,7 @@
import { type SWRResponse } from 'swr';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { agentBotKeys } from '@/libs/swr/keys';
import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
import { agentBotProviderService } from '@/services/agentBotProvider';
import { type StoreSetter } from '@/store/types';
@@ -8,9 +9,6 @@ import type { BotRuntimeStatusSnapshot } from '@/types/botRuntimeStatus';
import { type AgentStore } from '../../store';
-const FETCH_BOT_PROVIDERS_KEY = 'agentBotProviders';
-const FETCH_PLATFORM_DEFINITIONS_KEY = 'platformDefinitions';
-
export interface BotProviderItem {
applicationId: string;
credentials: Record<string, string>;
@@ -100,7 +98,7 @@ export class BotSliceActionImpl {
internal_refreshBotProviders = async (agentId?: string) => {
const id = agentId || this.#get().activeAgentId;
if (!id) return;
- await mutate([FETCH_BOT_PROVIDERS_KEY, id]);
+ await mutate(agentBotKeys.providers(id));
};
updateBotProvider = async (
@@ -119,7 +117,7 @@ export class BotSliceActionImpl {
useFetchBotProviders = (agentId?: string): SWRResponse<BotProviderItem[]> => {
return useClientDataSWR<BotProviderItem[]>(
- agentId ? [FETCH_BOT_PROVIDERS_KEY, agentId] : null,
+ agentId ? agentBotKeys.providers(agentId) : null,
async ([, id]: [string, string]) => agentBotProviderService.getByAgentId(id),
{ fallbackData: [], revalidateOnFocus: false },
);
@@ -127,7 +125,7 @@ export class BotSliceActionImpl {
useFetchPlatformDefinitions = (): SWRResponse<SerializedPlatformDefinition[]> => {
return useClientDataSWR<SerializedPlatformDefinition[]>(
- FETCH_PLATFORM_DEFINITIONS_KEY,
+ agentBotKeys.platformDefinitions(),
() => agentBotProviderService.listPlatforms(),
{ dedupingInterval: 300_000, fallbackData: [], revalidateOnFocus: false },
);
diff --git a/src/store/agent/slices/knowledge/action.ts b/src/store/agent/slices/knowledge/action.ts
index d2cca56db1b..4bbcc703344 100644
--- a/src/store/agent/slices/knowledge/action.ts
+++ b/src/store/agent/slices/knowledge/action.ts
@@ -2,13 +2,12 @@ import { type KnowledgeItem } from '@lobechat/types';
import { type SWRResponse } from 'swr';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { agentKnowledgeKeys } from '@/libs/swr/keys';
import { agentService } from '@/services/agent';
import { type StoreSetter } from '@/store/types';
import { type AgentStore } from '../../store';
-const FETCH_AGENT_KNOWLEDGE_KEY = 'FETCH_AGENT_KNOWLEDGE';
-
/**
* Knowledge Slice Actions
* Handles knowledge base and file operations
@@ -49,7 +48,7 @@ export class KnowledgeSliceActionImpl {
};
internal_refreshAgentKnowledge = async (): Promise<void> => {
- await mutate([FETCH_AGENT_KNOWLEDGE_KEY, this.#get().activeAgentId]);
+ await mutate(agentKnowledgeKeys.list(this.#get().activeAgentId));
};
removeFileFromAgent = async (fileId: string): Promise<void> => {
@@ -90,7 +89,7 @@ export class KnowledgeSliceActionImpl {
useFetchFilesAndKnowledgeBases = (agentId?: string): SWRResponse<KnowledgeItem[]> => {
return useClientDataSWR<KnowledgeItem[]>(
- agentId ? [FETCH_AGENT_KNOWLEDGE_KEY, agentId] : null,
+ agentId ? agentKnowledgeKeys.list(agentId) : null,
([, id]: string[]) => agentService.getFilesAndKnowledgeBases(id),
{
fallbackData: [],
diff --git a/src/store/chat/slices/builtinTool/actions/interpreter.ts b/src/store/chat/slices/builtinTool/actions/interpreter.ts
index d0642d68ec2..b8e0f52cab2 100644
--- a/src/store/chat/slices/builtinTool/actions/interpreter.ts
+++ b/src/store/chat/slices/builtinTool/actions/interpreter.ts
@@ -10,6 +10,7 @@ import pMap from 'p-map';
import { type SWRResponse } from 'swr';
import { useClientDataSWR } from '@/libs/swr';
+import { chatToolKeys } from '@/libs/swr/keys';
import { fileService } from '@/services/file';
import { pythonService } from '@/services/python';
import { dbMessageSelectors } from '@/store/chat/selectors';
@@ -21,8 +22,6 @@ import { setNamespace } from '@/utils/storeDebug';
const n = setNamespace('codeInterpreter');
const log = debug('lobe-store:builtin-tool');
-const SWR_FETCH_INTERPRETER_FILE_KEY = 'FetchCodeInterpreterFileItem';
-
type Setter = StoreSetter<ChatStore>;
export const codeInterpreterSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>
new ChatCodeInterpreterActionImpl(set, get, _api);
@@ -189,7 +188,7 @@ export class ChatCodeInterpreterActionImpl {
};
useFetchInterpreterFileItem = (id?: string): SWRResponse => {
- return useClientDataSWR(id ? [SWR_FETCH_INTERPRETER_FILE_KEY, id] : null, async () => {
+ return useClientDataSWR(id ? chatToolKeys.interpreterFile(id) : null, async () => {
if (!id) return null;
const item = await fileService.getFile(id);
diff --git a/src/store/device/action.ts b/src/store/device/action.ts
index d93143a5856..b64c0edee8c 100644
--- a/src/store/device/action.ts
+++ b/src/store/device/action.ts
@@ -2,14 +2,13 @@ import type { DeviceListItem, WorkingDirEntry } from '@lobechat/types';
import { type SWRResponse } from 'swr';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { deviceKeys } from '@/libs/swr/keys';
import { deviceService } from '@/services/device';
import { type StoreSetter } from '@/store/types';
import { nextWorkingDirs, removeWorkingDir, WORKING_DIRS_MAX } from './deviceCwd';
import { type DeviceStore } from './store';
-const FETCH_DEVICES_KEY = 'device:listDevices';
-
type Setter = StoreSetter<DeviceStore>;
export const deviceSlice = (set: Setter, get: () => DeviceStore, _api?: unknown) =>
@@ -65,7 +64,7 @@ export class DeviceActionImpl {
});
} finally {
// Re-fetch the truth (self-corrects a failed optimistic write).
- await mutate(FETCH_DEVICES_KEY);
+ await mutate(deviceKeys.listDevices());
}
};
@@ -102,7 +101,7 @@ export class DeviceActionImpl {
try {
await deviceService.updateDevice({ deviceId, workingDirs: merged });
} finally {
- await mutate(FETCH_DEVICES_KEY);
+ await mutate(deviceKeys.listDevices());
}
};
@@ -125,13 +124,13 @@ export class DeviceActionImpl {
try {
await deviceService.updateDevice({ deviceId, workingDirs: updated });
} finally {
- await mutate(FETCH_DEVICES_KEY);
+ await mutate(deviceKeys.listDevices());
}
};
useFetchDevices = (enabled = true): SWRResponse<DeviceListItem[]> =>
useClientDataSWR<DeviceListItem[]>(
- enabled ? FETCH_DEVICES_KEY : null,
+ enabled ? deviceKeys.listDevices() : null,
() => deviceService.listDevices(),
{
fallbackData: [],
diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.ts
index 505e996a0a6..f0fb0107211 100644
--- a/src/store/device/gitHooks.ts
+++ b/src/store/device/gitHooks.ts
@@ -2,6 +2,7 @@ import { isDesktop } from '@lobechat/const';
import type { DeviceGitAheadBehind, DeviceGitWorkingTreeStatus } from '@lobechat/types';
import { useClientDataSWR } from '@/libs/swr';
+import { deviceKeys } from '@/libs/swr/keys';
import { type GitInfo, gitService } from '@/services/git';
/**
@@ -20,7 +21,7 @@ const isEnabled = (deviceId: string | undefined, path: string | undefined): path
*/
export const useFetchGitInfo = (deviceId: string | undefined, path?: string, isGithub = false) =>
useClientDataSWR<GitInfo>(
- isEnabled(deviceId, path) ? ['git-info', deviceId ?? 'local', path, isGithub] : null,
+ isEnabled(deviceId, path) ? deviceKeys.gitInfo(deviceId ?? 'local', path, isGithub) : null,
() => gitService.getGitInfo({ deviceId, isGithub, path: path! }),
{ dedupingInterval: 60 * 1000, focusThrottleInterval: 60 * 1000, shouldRetryOnError: false },
);
@@ -31,7 +32,7 @@ export const useFetchGitInfo = (deviceId: string | undefined, path?: string, isG
*/
export const useFetchGitWorkingTreeStatus = (deviceId: string | undefined, path?: string) =>
useClientDataSWR<DeviceGitWorkingTreeStatus | undefined>(
- isEnabled(deviceId, path) ? ['git-working-tree-status', deviceId ?? 'local', path] : null,
+ isEnabled(deviceId, path) ? deviceKeys.gitWorkingTreeStatus(deviceId ?? 'local', path) : null,
() => gitService.getGitWorkingTreeStatus({ deviceId, path: path! }),
{ focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },
);
@@ -42,7 +43,7 @@ export const useFetchGitWorkingTreeStatus = (deviceId: string | undefined, path?
*/
export const useFetchGitAheadBehind = (deviceId: string | undefined, path?: string) =>
useClientDataSWR<DeviceGitAheadBehind | undefined>(
- isEnabled(deviceId, path) ? ['git-ahead-behind', deviceId ?? 'local', path] : null,
+ isEnabled(deviceId, path) ? deviceKeys.gitAheadBehind(deviceId ?? 'local', path) : null,
() => gitService.getGitAheadBehind({ deviceId, path: path! }),
{ focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },
);
diff --git a/src/store/discover/slices/assistant/action.ts b/src/store/discover/slices/assistant/action.ts
index e9b228b3448..d8e98788946 100644
--- a/src/store/discover/slices/assistant/action.ts
+++ b/src/store/discover/slices/assistant/action.ts
@@ -2,6 +2,7 @@ import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
import { type SWRResponse } from 'swr';
import useSWR from 'swr';
+import { discoverKeys } from '@/libs/swr/keys';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
@@ -30,7 +31,7 @@ export class AssistantActionImpl {
): SWRResponse<CategoryItem[]> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
- ['assistant-categories', locale, ...Object.values(params)].filter(Boolean).join('-'),
+ discoverKeys.assistantCategories(locale, params),
async () => discoverService.getAssistantCategories(params),
{
revalidateOnFocus: false,
@@ -45,9 +46,7 @@ export class AssistantActionImpl {
}): SWRResponse<DiscoverAssistantDetail | undefined> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
- ['assistant-details', locale, params.identifier, params.version, params.source]
- .filter(Boolean)
- .join('-'),
+ discoverKeys.assistantDetail(locale, params),
async () => discoverService.getAssistantDetail(params),
{
revalidateOnFocus: false,
@@ -59,8 +58,7 @@ export class AssistantActionImpl {
source?: AssistantMarketSource;
}): SWRResponse<IdentifiersResponse> => {
return useSWR(
- ['assistant-identifiers', params?.source].filter(Boolean).join('-') ||
- 'assistant-identifiers',
+ discoverKeys.assistantIdentifiers(params?.source),
async () => discoverService.getAssistantIdentifiers(params),
{
revalidateOnFocus: false,
@@ -71,7 +69,7 @@ export class AssistantActionImpl {
useAssistantList = (params: AssistantQueryParams = {}): SWRResponse<AssistantListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
- ['assistant-list', locale, ...Object.values(params)].filter(Boolean).join('-'),
+ discoverKeys.assistantList(locale, params),
async () =>
discoverService.getAssistantList({
...params,
diff --git a/src/store/discover/slices/model/action.ts b/src/store/discover/slices/model/action.ts
index 11c4d28bde8..740dafc5518 100644
--- a/src/store/discover/slices/model/action.ts
+++ b/src/store/discover/slices/model/action.ts
@@ -2,6 +2,7 @@ import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
import { type SWRResponse } from 'swr';
import useSWR from 'swr';
+import { discoverKeys } from '@/libs/swr/keys';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
@@ -48,9 +49,13 @@ export class ModelActionImpl {
};
useModelIdentifiers = (): SWRResponse<IdentifiersResponse> => {
- return useSWR('model-identifiers', async () => discoverService.getModelIdentifiers(), {
- revalidateOnFocus: false,
- });
+ return useSWR(
+ discoverKeys.modelIdentifiers(),
+ async () => discoverService.getModelIdentifiers(),
+ {
+ revalidateOnFocus: false,
+ },
+ );
};
useModelList = (params: ModelQueryParams = {}): SWRResponse<ModelListResponse> => {
diff --git a/src/store/discover/slices/plugin/action.ts b/src/store/discover/slices/plugin/action.ts
index b6b95f716fa..f16bdd034e2 100644
--- a/src/store/discover/slices/plugin/action.ts
+++ b/src/store/discover/slices/plugin/action.ts
@@ -8,6 +8,7 @@ import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
import { type SWRResponse } from 'swr';
import useSWR from 'swr';
+import { discoverKeys } from '@/libs/swr/keys';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
@@ -55,9 +56,13 @@ export class PluginActionImpl {
};
usePluginIdentifiers = (): SWRResponse<IdentifiersResponse> => {
- return useSWR('plugin-identifiers', async () => discoverService.getPluginIdentifiers(), {
- revalidateOnFocus: false,
- });
+ return useSWR(
+ discoverKeys.pluginIdentifiers(),
+ async () => discoverService.getPluginIdentifiers(),
+ {
+ revalidateOnFocus: false,
+ },
+ );
};
usePluginList = (params: PluginQueryParams = {}): SWRResponse<PluginListResponse> => {
diff --git a/src/store/discover/slices/provider/action.ts b/src/store/discover/slices/provider/action.ts
index f9e8226c95a..c5115dcb572 100644
--- a/src/store/discover/slices/provider/action.ts
+++ b/src/store/discover/slices/provider/action.ts
@@ -1,6 +1,7 @@
import { type SWRResponse } from 'swr';
import useSWR from 'swr';
+import { discoverKeys } from '@/libs/swr/keys';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
@@ -38,9 +39,13 @@ export class ProviderActionImpl {
};
useProviderIdentifiers = (): SWRResponse<IdentifiersResponse> => {
- return useSWR('provider-identifiers', async () => discoverService.getProviderIdentifiers(), {
- revalidateOnFocus: false,
- });
+ return useSWR(
+ discoverKeys.providerIdentifiers(),
+ async () => discoverService.getProviderIdentifiers(),
+ {
+ revalidateOnFocus: false,
+ },
+ );
};
useProviderList = (params: ProviderQueryParams = {}): SWRResponse<ProviderListResponse> => {
diff --git a/src/store/discover/slices/social/action.test.ts b/src/store/discover/slices/social/action.test.ts
index 66fd6d46474..5e23f6ba647 100644
--- a/src/store/discover/slices/social/action.test.ts
+++ b/src/store/discover/slices/social/action.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { mutate } from '@/libs/swr';
+import { discoverKeys } from '@/libs/swr/keys';
import type { FollowCounts } from '@/services/social';
import { socialService } from '@/services/social';
@@ -30,12 +31,14 @@ describe('SocialActionImpl', () => {
expect(socialService.follow).toHaveBeenCalledWith(42);
expect(mutateMock).toHaveBeenCalledWith(
- 'follow-status-42',
+ discoverKeys.followStatus(42),
{ isFollowing: true, isMutual: false },
{ revalidate: false },
);
- const countsCall = mutateMock.mock.calls.find(([key]) => key === 'follow-counts-42');
+ const countsCall = mutateMock.mock.calls.find(
+ ([key]) => Array.isArray(key) && key[0] === discoverKeys.followCounts.root && key[1] === 42,
+ );
const updateCounts = countsCall?.[1] as
| ((current?: FollowCounts) => FollowCounts)
| undefined;
@@ -57,12 +60,14 @@ describe('SocialActionImpl', () => {
expect(socialService.unfollow).toHaveBeenCalledWith(42);
expect(mutateMock).toHaveBeenCalledWith(
- 'follow-status-42',
+ discoverKeys.followStatus(42),
{ isFollowing: false, isMutual: false },
{ revalidate: false },
);
- const countsCall = mutateMock.mock.calls.find(([key]) => key === 'follow-counts-42');
+ const countsCall = mutateMock.mock.calls.find(
+ ([key]) => Array.isArray(key) && key[0] === discoverKeys.followCounts.root && key[1] === 42,
+ );
const updateCounts = countsCall?.[1] as
| ((current?: FollowCounts) => FollowCounts)
| undefined;
diff --git a/src/store/discover/slices/social/action.ts b/src/store/discover/slices/social/action.ts
index d154660d8a4..c68edf2cbf4 100644
--- a/src/store/discover/slices/social/action.ts
+++ b/src/store/discover/slices/social/action.ts
@@ -2,6 +2,7 @@ import { type SWRResponse } from 'swr';
import useSWR from 'swr';
import { mutate } from '@/libs/swr';
+import { discoverKeys } from '@/libs/swr/keys';
import {
type FavoriteAgentItem,
type FavoritePluginItem,
@@ -19,9 +20,6 @@ type Setter = StoreSetter<DiscoverStore>;
export const createSocialSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
new SocialActionImpl(set, get, _api);
-const followStatusKey = (userId: number) => `follow-status-${userId}`;
-const followCountsKey = (userId: number) => `follow-counts-${userId}`;
-
const optimisticFollowCounts =
(isFollowing: boolean) =>
(current?: FollowCounts): FollowCounts => {
@@ -36,19 +34,20 @@ const optimisticFollowCounts =
const updateFollowCaches = async (followingId: number, isFollowing: boolean) => {
await Promise.all([
mutate(
- followStatusKey(followingId),
+ discoverKeys.followStatus(followingId),
{
isFollowing,
isMutual: false,
} satisfies FollowStatus,
{ revalidate: false },
),
- mutate(followCountsKey(followingId), optimisticFollowCounts(isFollowing), {
+ mutate(discoverKeys.followCounts(followingId), optimisticFollowCounts(isFollowing), {
revalidate: false,
}),
mutate(
(key) =>
- typeof key === 'string' && (key.startsWith('followers-') || key.startsWith('following-')),
+ Array.isArray(key) &&
+ (key[0] === discoverKeys.followers.root || key[0] === discoverKeys.following.root),
undefined,
{
revalidate: true,
@@ -67,9 +66,16 @@ export class SocialActionImpl {
addFavorite = async (targetType: SocialTargetType, targetId: number): Promise<void> => {
await socialService.addFavorite(targetType, targetId);
// Invalidate favorite-related caches
- await mutate((key) => typeof key === 'string' && key.startsWith('favorite-'), undefined, {
- revalidate: true,
- });
+ await mutate(
+ (key) =>
+ Array.isArray(key) &&
+ (key[0] === discoverKeys.favoriteAgents.root ||
+ key[0] === discoverKeys.favoritePlugins.root),
+ undefined,
+ {
+ revalidate: true,
+ },
+ );
};
follow = async (followingId: number): Promise<void> => {
@@ -80,9 +86,16 @@ export class SocialActionImpl {
removeFavorite = async (targetType: SocialTargetType, targetId: number): Promise<void> => {
await socialService.removeFavorite(targetType, targetId);
// Invalidate favorite-related caches
- await mutate((key) => typeof key === 'string' && key.startsWith('favorite-'), undefined, {
- revalidate: true,
- });
+ await mutate(
+ (key) =>
+ Array.isArray(key) &&
+ (key[0] === discoverKeys.favoriteAgents.root ||
+ key[0] === discoverKeys.favoritePlugins.root),
+ undefined,
+ {
+ revalidate: true,
+ },
+ );
};
toggleLike = async (
@@ -107,7 +120,7 @@ export class SocialActionImpl {
params?: { page?: number; pageSize?: number },
): SWRResponse<PaginatedResponse<FavoriteAgentItem>> => {
return useSWR(
- userId ? ['favorite-agents', userId, params?.page, params?.pageSize].join('-') : null,
+ userId ? discoverKeys.favoriteAgents(userId, params) : null,
async () => socialService.getUserFavoriteAgents(userId!, params),
{ revalidateOnFocus: false },
);
@@ -118,7 +131,7 @@ export class SocialActionImpl {
params?: { page?: number; pageSize?: number },
): SWRResponse<PaginatedResponse<FavoritePluginItem>> => {
return useSWR(
- userId ? ['favorite-plugins', userId, params?.page, params?.pageSize].join('-') : null,
+ userId ? discoverKeys.favoritePlugins(userId, params) : null,
async () => socialService.getUserFavoritePlugins(userId!, params),
{ revalidateOnFocus: false },
);
@@ -126,7 +139,7 @@ export class SocialActionImpl {
useFollowCounts = (userId: number | undefined): SWRResponse<FollowCounts> => {
return useSWR(
- userId ? ['follow-counts', userId].join('-') : null,
+ userId ? discoverKeys.followCounts(userId) : null,
async () => socialService.getFollowCounts(userId!),
{ revalidateOnFocus: false },
);
@@ -134,7 +147,7 @@ export class SocialActionImpl {
useFollowStatus = (userId: number | undefined): SWRResponse<FollowStatus> => {
return useSWR(
- userId ? ['follow-status', userId].join('-') : null,
+ userId ? discoverKeys.followStatus(userId) : null,
async () => socialService.checkFollowStatus(userId!),
{ revalidateOnFocus: false },
);
@@ -145,7 +158,7 @@ export class SocialActionImpl {
params?: { page?: number; pageSize?: number },
): SWRResponse<PaginatedResponse<FollowUserItem>> => {
return useSWR(
- userId ? ['followers', userId, params?.page, params?.pageSize].join('-') : null,
+ userId ? discoverKeys.followers(userId, params) : null,
async () => socialService.getFollowers(userId!, params),
{ revalidateOnFocus: false },
);
@@ -156,7 +169,7 @@ export class SocialActionImpl {
params?: { page?: number; pageSize?: number },
): SWRResponse<PaginatedResponse<FollowUserItem>> => {
return useSWR(
- userId ? ['following', userId, params?.page, params?.pageSize].join('-') : null,
+ userId ? discoverKeys.following(userId, params) : null,
async () => socialService.getFollowing(userId!, params),
{ revalidateOnFocus: false },
);
diff --git a/src/store/eval/slices/benchmark/action.ts b/src/store/eval/slices/benchmark/action.ts
index f909fc1edae..b0fc1ab16b4 100644
--- a/src/store/eval/slices/benchmark/action.ts
+++ b/src/store/eval/slices/benchmark/action.ts
@@ -2,15 +2,13 @@ import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { evalKeys } from '@/libs/swr/keys';
import { agentEvalService } from '@/services/agentEval';
import { type EvalStore } from '@/store/eval/store';
import { type StoreSetter } from '@/store/types';
import { type BenchmarkDetailDispatch, benchmarkDetailReducer } from './reducer';
-const FETCH_BENCHMARKS_KEY = 'FETCH_BENCHMARKS';
-const FETCH_BENCHMARK_DETAIL_KEY = 'FETCH_BENCHMARK_DETAIL';
-
type Setter = StoreSetter<EvalStore>;
export const createBenchmarkSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>
@@ -62,11 +60,11 @@ export class BenchmarkActionImpl {
};
refreshBenchmarkDetail = async (id: string): Promise<void> => {
- await mutate([FETCH_BENCHMARK_DETAIL_KEY, id]);
+ await mutate(evalKeys.benchmarkDetail(id));
};
refreshBenchmarks = async (): Promise<void> => {
- await mutate(FETCH_BENCHMARKS_KEY);
+ await mutate(evalKeys.benchmarks());
};
updateBenchmark = async (params: {
@@ -106,7 +104,7 @@ export class BenchmarkActionImpl {
useFetchBenchmarkDetail = (id?: string): SWRResponse =>
useClientDataSWR(
- id ? [FETCH_BENCHMARK_DETAIL_KEY, id] : null,
+ id ? evalKeys.benchmarkDetail(id) : null,
() => agentEvalService.getBenchmark(id!),
{
onSuccess: (data: any) => {
@@ -121,7 +119,7 @@ export class BenchmarkActionImpl {
);
useFetchBenchmarks = (): SWRResponse =>
- useClientDataSWR(FETCH_BENCHMARKS_KEY, () => agentEvalService.listBenchmarks(), {
+ useClientDataSWR(evalKeys.benchmarks(), () => agentEvalService.listBenchmarks(), {
onSuccess: (data: any) => {
this.#set(
{ benchmarkList: data, benchmarkListInit: true, isLoadingBenchmarkList: false },
diff --git a/src/store/eval/slices/dataset/action.ts b/src/store/eval/slices/dataset/action.ts
index 9ad12703f5d..f0b8915c85e 100644
--- a/src/store/eval/slices/dataset/action.ts
+++ b/src/store/eval/slices/dataset/action.ts
@@ -2,15 +2,13 @@ import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { evalKeys } from '@/libs/swr/keys';
import { agentEvalService } from '@/services/agentEval';
import { type EvalStore } from '@/store/eval/store';
import { type StoreSetter } from '@/store/types';
import { type DatasetDetailDispatch, datasetDetailReducer } from './reducer';
-const FETCH_DATASETS_KEY = 'FETCH_DATASETS';
-const FETCH_DATASET_DETAIL_KEY = 'FETCH_DATASET_DETAIL';
-
type Setter = StoreSetter<EvalStore>;
export const createDatasetSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>
@@ -27,16 +25,16 @@ export class DatasetActionImpl {
}
refreshDatasetDetail = async (id: string): Promise<void> => {
- await mutate([FETCH_DATASET_DETAIL_KEY, id]);
+ await mutate(evalKeys.datasetDetail(id));
};
refreshDatasets = async (benchmarkId: string): Promise<void> => {
- await mutate([FETCH_DATASETS_KEY, benchmarkId]);
+ await mutate(evalKeys.datasets(benchmarkId));
};
useFetchDatasetDetail = (id?: string): SWRResponse =>
useClientDataSWR(
- id ? [FETCH_DATASET_DETAIL_KEY, id] : null,
+ id ? evalKeys.datasetDetail(id) : null,
() => agentEvalService.getDataset(id!),
{
onSuccess: (data: any) => {
@@ -52,7 +50,7 @@ export class DatasetActionImpl {
useFetchDatasets = (benchmarkId?: string): SWRResponse =>
useClientDataSWR(
- benchmarkId ? [FETCH_DATASETS_KEY, benchmarkId] : null,
+ benchmarkId ? evalKeys.datasets(benchmarkId) : null,
() => agentEvalService.listDatasets(benchmarkId!),
{
onSuccess: (data: any) => {
diff --git a/src/store/eval/slices/run/action.ts b/src/store/eval/slices/run/action.ts
index 49a6999059e..ee63869cb04 100644
--- a/src/store/eval/slices/run/action.ts
+++ b/src/store/eval/slices/run/action.ts
@@ -3,17 +3,13 @@ import isEqual from 'fast-deep-equal';
import type { SWRResponse } from 'swr';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { evalKeys } from '@/libs/swr/keys';
import { agentEvalService } from '@/services/agentEval';
import type { EvalStore } from '@/store/eval/store';
import { type StoreSetter } from '@/store/types';
import { type RunDetailDispatch, runDetailReducer } from './reducer';
-const FETCH_RUNS_KEY = 'FETCH_EVAL_RUNS';
-const FETCH_DATASET_RUNS_KEY = 'FETCH_EVAL_DATASET_RUNS';
-const FETCH_RUN_DETAIL_KEY = 'FETCH_EVAL_RUN_DETAIL';
-const FETCH_RUN_RESULTS_KEY = 'FETCH_EVAL_RUN_RESULTS';
-
type Setter = StoreSetter<EvalStore>;
export const createRunSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>
@@ -96,18 +92,18 @@ export class RunActionImpl {
};
refreshDatasetRuns = async (datasetId: string): Promise<void> => {
- await mutate([FETCH_DATASET_RUNS_KEY, datasetId]);
+ await mutate(evalKeys.datasetRuns(datasetId));
};
refreshRunDetail = async (id: string): Promise<void> => {
- await mutate([FETCH_RUN_DETAIL_KEY, id]);
+ await mutate(evalKeys.runDetail(id));
};
refreshRuns = async (benchmarkId?: string): Promise<void> => {
if (benchmarkId) {
- await mutate([FETCH_RUNS_KEY, benchmarkId]);
+ await mutate(evalKeys.runs(benchmarkId));
} else {
- await mutate((key) => Array.isArray(key) && key[0] === FETCH_RUNS_KEY);
+ await mutate((key) => Array.isArray(key) && key[0] === evalKeys.runs.root);
}
};
@@ -116,10 +112,7 @@ export class RunActionImpl {
targets: Array<{ testCaseId: string; threadId?: string }>,
): Promise<void> => {
await agentEvalService.batchResumeRunCases(runId, targets);
- await Promise.all([
- this.#get().refreshRunDetail(runId),
- mutate([FETCH_RUN_RESULTS_KEY, runId]),
- ]);
+ await Promise.all([this.#get().refreshRunDetail(runId), mutate(evalKeys.runResults(runId))]);
};
retryRunCase = async (runId: string, testCaseId: string): Promise<void> => {
@@ -156,25 +149,21 @@ export class RunActionImpl {
};
useFetchRunDetail = (id: string, config?: { refreshInterval?: number }): SWRResponse =>
- useClientDataSWR(
- id ? [FETCH_RUN_DETAIL_KEY, id] : null,
- () => agentEvalService.getRunDetails(id),
- {
- ...config,
- onSuccess: (data: any) => {
- this.#get().internal_dispatchRunDetail({
- id,
- type: 'setRunDetail',
- value: data,
- });
- this.#get().internal_updateRunDetailLoading(id, false);
- },
+ useClientDataSWR(id ? evalKeys.runDetail(id) : null, () => agentEvalService.getRunDetails(id), {
+ ...config,
+ onSuccess: (data: any) => {
+ this.#get().internal_dispatchRunDetail({
+ id,
+ type: 'setRunDetail',
+ value: data,
+ });
+ this.#get().internal_updateRunDetailLoading(id, false);
},
- );
+ });
useFetchRunResults = (id: string, config?: { refreshInterval?: number }): SWRResponse =>
useClientDataSWR(
- id ? [FETCH_RUN_RESULTS_KEY, id] : null,
+ id ? evalKeys.runResults(id) : null,
() => agentEvalService.getRunResults(id),
{
...config,
@@ -193,7 +182,7 @@ export class RunActionImpl {
useFetchDatasetRuns = (datasetId?: string): SWRResponse =>
useClientDataSWR(
- datasetId ? [FETCH_DATASET_RUNS_KEY, datasetId] : null,
+ datasetId ? evalKeys.datasetRuns(datasetId) : null,
() => agentEvalService.listRuns({ datasetId: datasetId! }),
{
onSuccess: (data: any) => {
@@ -210,7 +199,7 @@ export class RunActionImpl {
useFetchRuns = (benchmarkId?: string): SWRResponse =>
useClientDataSWR(
- benchmarkId ? [FETCH_RUNS_KEY, benchmarkId] : null,
+ benchmarkId ? evalKeys.runs(benchmarkId) : null,
() => agentEvalService.listRuns({ benchmarkId: benchmarkId! }),
{
onSuccess: (data: any) => {
diff --git a/src/store/eval/slices/testCase/action.ts b/src/store/eval/slices/testCase/action.ts
index cc935cbbc8b..a03c7a5ed89 100644
--- a/src/store/eval/slices/testCase/action.ts
+++ b/src/store/eval/slices/testCase/action.ts
@@ -1,12 +1,11 @@
import type { SWRResponse } from 'swr';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { evalKeys } from '@/libs/swr/keys';
import { agentEvalService } from '@/services/agentEval';
import type { EvalStore } from '@/store/eval/store';
import { type StoreSetter } from '@/store/types';
-const FETCH_TEST_CASES_KEY = 'FETCH_TEST_CASES';
-
type Setter = StoreSetter<EvalStore>;
export const createTestCaseSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>
@@ -36,7 +35,7 @@ export class TestCaseActionImpl {
refreshTestCases = async (datasetId: string): Promise<void> => {
await mutate(
- (key) => Array.isArray(key) && key[0] === FETCH_TEST_CASES_KEY && key[1] === datasetId,
+ (key) => Array.isArray(key) && key[0] === evalKeys.testCases.root && key[1] === datasetId,
);
};
@@ -48,7 +47,7 @@ export class TestCaseActionImpl {
const { datasetId, limit = 10, offset = 0 } = params;
return useClientDataSWR(
- datasetId ? [FETCH_TEST_CASES_KEY, datasetId, limit, offset] : null,
+ datasetId ? evalKeys.testCases(datasetId, limit, offset) : null,
() => agentEvalService.listTestCases({ datasetId, limit, offset }),
{
onSuccess: (data: any) => {
diff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.ts
index dc591b84127..dd0eec7462b 100644
--- a/src/store/file/slices/fileManager/action.ts
+++ b/src/store/file/slices/fileManager/action.ts
@@ -11,6 +11,7 @@ import { type SWRResponse } from 'swr';
import { message } from '@/components/AntdStaticMethods';
import { FILE_UPLOAD_BLACKLIST, MAX_UPLOAD_FILE_COUNT } from '@/const/file';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { fileKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
import { FileService, fileService } from '@/services/file';
import { ragService } from '@/services/rag';
@@ -26,7 +27,6 @@ import { type FileStore } from '../../store';
import { fileManagerSelectors } from './selectors';
const serverFileService = new FileService();
-const FETCH_ALL_KNOWLEDGE_KEY = 'useFetchKnowledgeItems';
export interface FolderCrumb {
id: string;
@@ -189,7 +189,7 @@ export class FileManageActionImpl {
});
// Update SWR cache so the component sees the new items
- await mutate([FETCH_ALL_KNOWLEDGE_KEY, queryListParams], updatedFileList, {
+ await mutate(fileKeys.knowledgeItems(queryListParams), updatedFileList, {
revalidate: false,
});
} catch (error) {
@@ -200,7 +200,7 @@ export class FileManageActionImpl {
moveFileToFolder = async (fileId: string, parentId: string | null): Promise<void> => {
// Optimistically update all file list caches
await mutate(
- (key) => Array.isArray(key) && key[0] === FETCH_ALL_KNOWLEDGE_KEY,
+ (key) => Array.isArray(key) && key[0] === fileKeys.knowledgeItems.root,
async (currentData: FileListItem[] | undefined) => {
if (!currentData) return currentData;
// Update the moved file's parentId in the cache
@@ -367,12 +367,12 @@ export class FileManageActionImpl {
};
#refreshKnowledgeListCaches = async (): Promise<void> => {
- // Invalidate all queries that start with FETCH_ALL_KNOWLEDGE_KEY
+ // Invalidate all queries under the file:knowledgeItems namespace
// This ensures all file lists (explorer, tree, etc.) are refreshed
// Note: We don't pass data as undefined to avoid clearing the cache,
// which would cause isLoading to become true and show skeleton screen
await mutate(
- (key) => Array.isArray(key) && key[0] === FETCH_ALL_KNOWLEDGE_KEY,
+ (key) => Array.isArray(key) && key[0] === fileKeys.knowledgeItems.root,
async (currentData) => currentData,
{
revalidate: true,
@@ -406,7 +406,7 @@ export class FileManageActionImpl {
renameFolder = async (folderId: string, newName: string): Promise<void> => {
// Optimistically update all file list caches
await mutate(
- (key) => Array.isArray(key) && key[0] === FETCH_ALL_KNOWLEDGE_KEY,
+ (key) => Array.isArray(key) && key[0] === fileKeys.knowledgeItems.root,
async (currentData: FileListItem[] | undefined) => {
if (!currentData) return currentData;
// Update the folder's name in the cache
@@ -681,7 +681,7 @@ export class FileManageActionImpl {
};
useFetchKnowledgeItems = (params: QueryFileListParams): SWRResponse<FileListItem[]> => {
- return useClientDataSWR<FileListItem[]>([FETCH_ALL_KNOWLEDGE_KEY, params], async () => {
+ return useClientDataSWR<FileListItem[]>(fileKeys.knowledgeItems(params), async () => {
const response = await serverFileService.getKnowledgeItems({
...params,
limit: params.limit ?? 50,
diff --git a/src/store/file/slices/tts/action.ts b/src/store/file/slices/tts/action.ts
index 76d9af96e21..01ea15f5238 100644
--- a/src/store/file/slices/tts/action.ts
+++ b/src/store/file/slices/tts/action.ts
@@ -1,14 +1,13 @@
import { type SWRResponse } from 'swr';
import { useClientDataSWR } from '@/libs/swr';
+import { fileKeys } from '@/libs/swr/keys';
import { fileService } from '@/services/file';
import { type StoreSetter } from '@/store/types';
import { type FileItem } from '@/types/files';
import { type FileStore } from '../../store';
-const FETCH_TTS_FILE = 'fetchTTSFile';
-
type Setter = StoreSetter<FileStore>;
export const createTTSFileSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
new TTSFileActionImpl(set, get, _api);
@@ -45,7 +44,7 @@ export class TTSFileActionImpl {
};
useFetchTTSFile = (id: string | null): SWRResponse<FileItem> => {
- return useClientDataSWR(!!id ? [FETCH_TTS_FILE, id] : null, () => fileService.getFile(id!));
+ return useClientDataSWR(!!id ? fileKeys.ttsFile(id) : null, () => fileService.getFile(id!));
};
}
diff --git a/src/store/library/slices/crud/action.test.ts b/src/store/library/slices/crud/action.test.ts
index f71fd47a70d..9c3456f9971 100644
--- a/src/store/library/slices/crud/action.test.ts
+++ b/src/store/library/slices/crud/action.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { mutate } from '@/libs/swr';
+import { knowledgeBaseKeys } from '@/libs/swr/keys';
import { knowledgeBaseService } from '@/services/knowledgeBase';
import type { CreateKnowledgeBaseParams, KnowledgeBaseItem } from '@/types/knowledgeBase';
import { withSWR } from '~test-utils';
@@ -153,7 +154,7 @@ describe('KnowledgeBaseCrudAction', () => {
}),
).resolves.not.toThrow();
- expect(mutate).toHaveBeenCalledWith('FETCH_KNOWLEDGE_BASE');
+ expect(mutate).toHaveBeenCalledWith(knowledgeBaseKeys.list());
});
it('should refresh the active workspace-scoped cache key', async () => {
@@ -164,7 +165,7 @@ describe('KnowledgeBaseCrudAction', () => {
await result.current.refreshKnowledgeBaseList();
});
- expect(mutate).toHaveBeenCalledWith(['FETCH_KNOWLEDGE_BASE', 'workspace-1']);
+ expect(mutate).toHaveBeenCalledWith(knowledgeBaseKeys.list('workspace-1'));
expect(getActiveWorkspaceId).toHaveBeenCalled();
});
});
diff --git a/src/store/library/slices/crud/action.ts b/src/store/library/slices/crud/action.ts
index 151c6cb4dce..e81233e9dc7 100644
--- a/src/store/library/slices/crud/action.ts
+++ b/src/store/library/slices/crud/action.ts
@@ -2,14 +2,12 @@ import type { SWRResponse } from 'swr';
import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { knowledgeBaseKeys } from '@/libs/swr/keys';
import { knowledgeBaseService } from '@/services/knowledgeBase';
import type { KnowledgeBaseStore } from '@/store/library/store';
import type { StoreSetter } from '@/store/types';
import type { CreateKnowledgeBaseParams, KnowledgeBaseItem } from '@/types/knowledgeBase';
-const FETCH_KNOWLEDGE_BASE_LIST_KEY = 'FETCH_KNOWLEDGE_BASE';
-const FETCH_KNOWLEDGE_BASE_ITEM_KEY = 'FETCH_KNOWLEDGE_BASE_ITEM';
-
type Setter = StoreSetter<KnowledgeBaseStore>;
export const createCrudSlice = (set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) =>
new KnowledgeBaseCrudActionImpl(set, get, _api);
@@ -46,9 +44,7 @@ export class KnowledgeBaseCrudActionImpl {
refreshKnowledgeBaseList = async (): Promise<void> => {
const workspaceId = getActiveWorkspaceId();
- await mutate(
- workspaceId ? [FETCH_KNOWLEDGE_BASE_LIST_KEY, workspaceId] : FETCH_KNOWLEDGE_BASE_LIST_KEY,
- );
+ await mutate(knowledgeBaseKeys.list(workspaceId));
};
removeKnowledgeBase = async (id: string): Promise<void> => {
@@ -66,7 +62,7 @@ export class KnowledgeBaseCrudActionImpl {
useFetchKnowledgeBaseItem = (id: string): SWRResponse<KnowledgeBaseItem | undefined> => {
return useClientDataSWR<KnowledgeBaseItem | undefined>(
- [FETCH_KNOWLEDGE_BASE_ITEM_KEY, id],
+ knowledgeBaseKeys.item(id),
() => knowledgeBaseService.getKnowledgeBaseById(id),
{
onSuccess: (item) => {
@@ -88,7 +84,7 @@ export class KnowledgeBaseCrudActionImpl {
params: { suspense?: boolean } = {},
): SWRResponse<KnowledgeBaseItem[]> => {
return useClientDataSWR<KnowledgeBaseItem[]>(
- FETCH_KNOWLEDGE_BASE_LIST_KEY,
+ knowledgeBaseKeys.list(),
() => knowledgeBaseService.getKnowledgeBaseList(),
{
fallbackData: [],
diff --git a/src/store/library/slices/ragEval/actions/dataset.ts b/src/store/library/slices/ragEval/actions/dataset.ts
index e94edfd6bb5..297df8d1173 100644
--- a/src/store/library/slices/ragEval/actions/dataset.ts
+++ b/src/store/library/slices/ragEval/actions/dataset.ts
@@ -9,13 +9,11 @@ import { type SWRResponse } from 'swr';
import { notification } from '@/components/AntdStaticMethods';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { ragEvalKeys } from '@/libs/swr/keys';
import { ragEvalService } from '@/services/ragEval';
import { type KnowledgeBaseStore } from '@/store/library/store';
import { type StoreSetter } from '@/store/types';
-const FETCH_DATASET_LIST_KEY = 'FETCH_DATASET_LIST';
-const FETCH_DATASET_RECORD_KEY = 'FETCH_DATASET_RECORD_KEY';
-
type Setter = StoreSetter<KnowledgeBaseStore>;
export const createRagEvalDatasetSlice = (
set: Setter,
@@ -67,7 +65,7 @@ export class RAGEvalDatasetActionImpl {
};
refreshDatasetList = async (): Promise<void> => {
- await mutate(FETCH_DATASET_LIST_KEY);
+ await mutate(ragEvalKeys.datasetList());
};
removeDataset = async (id: string): Promise<void> => {
@@ -77,14 +75,14 @@ export class RAGEvalDatasetActionImpl {
useFetchDatasetRecords = (datasetId: string | null): SWRResponse<EvalDatasetRecord[]> => {
return useClientDataSWR<EvalDatasetRecord[]>(
- !!datasetId ? [FETCH_DATASET_RECORD_KEY, datasetId] : null,
+ !!datasetId ? ragEvalKeys.datasetRecords(datasetId) : null,
() => ragEvalService.getDatasetRecords(datasetId!),
);
};
useFetchDatasets = (knowledgeBaseId: string): SWRResponse<RAGEvalDataSetItem[]> => {
return useClientDataSWR<RAGEvalDataSetItem[]>(
- [FETCH_DATASET_LIST_KEY, knowledgeBaseId],
+ ragEvalKeys.datasetList(knowledgeBaseId),
() => ragEvalService.getDatasets(knowledgeBaseId),
{
fallbackData: [],
diff --git a/src/store/library/slices/ragEval/actions/evaluation.ts b/src/store/library/slices/ragEval/actions/evaluation.ts
index fcc45a79592..f77b1cc71a7 100644
--- a/src/store/library/slices/ragEval/actions/evaluation.ts
+++ b/src/store/library/slices/ragEval/actions/evaluation.ts
@@ -2,12 +2,11 @@ import { type CreateNewEvalEvaluation, type RAGEvalDataSetItem } from '@lobechat
import { type SWRResponse } from 'swr';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { ragEvalKeys } from '@/libs/swr/keys';
import { ragEvalService } from '@/services/ragEval';
import { type KnowledgeBaseStore } from '@/store/library/store';
import { type StoreSetter } from '@/store/types';
-const FETCH_EVALUATION_LIST_KEY = 'FETCH_EVALUATION_LIST_KEY';
-
type Setter = StoreSetter<KnowledgeBaseStore>;
export const createRagEvalEvaluationSlice = (
set: Setter,
@@ -35,7 +34,7 @@ export class RAGEvalEvaluationActionImpl {
};
refreshEvaluationList = async (): Promise<void> => {
- await mutate(FETCH_EVALUATION_LIST_KEY);
+ await mutate(ragEvalKeys.evaluationList());
};
removeEvaluation = async (id: string): Promise<void> => {
@@ -49,7 +48,7 @@ export class RAGEvalEvaluationActionImpl {
useFetchEvaluationList = (knowledgeBaseId: string): SWRResponse<RAGEvalDataSetItem[]> => {
return useClientDataSWR<RAGEvalDataSetItem[]>(
- [FETCH_EVALUATION_LIST_KEY, knowledgeBaseId],
+ ragEvalKeys.evaluationList(knowledgeBaseId),
() => ragEvalService.getEvaluationList(knowledgeBaseId),
{
fallbackData: [],
diff --git a/src/store/userMemory/slices/agent/action.ts b/src/store/userMemory/slices/agent/action.ts
index 0d9553644e7..d74f5efa262 100644
--- a/src/store/userMemory/slices/agent/action.ts
+++ b/src/store/userMemory/slices/agent/action.ts
@@ -2,6 +2,7 @@ import { omit } from 'es-toolkit';
import { type SWRResponse } from 'swr';
import { useClientDataSWRWithSync } from '@/libs/swr';
+import { userMemoryKeys } from '@/libs/swr/keys';
import { userMemoryService } from '@/services/userMemory';
import { type StoreSetter } from '@/store/types';
import { type RetrieveMemoryResult } from '@/types/userMemory';
@@ -35,7 +36,7 @@ export class AgentMemoryActionImpl {
useFetchMemoriesForTopic = (topicId?: string | null): SWRResponse<RetrieveMemoryResult> => {
return useClientDataSWRWithSync<RetrieveMemoryResult>(
- topicId ? ['useFetchMemoriesForTopic', topicId] : null,
+ topicId ? userMemoryKeys.topicMemories(topicId) : null,
async () => {
// Retrieve memories using topic's context
// The backend will use topic info to build the query
diff --git a/src/store/userMemory/slices/base/action.ts b/src/store/userMemory/slices/base/action.ts
index d70c3a419bf..2ead81c42f2 100644
--- a/src/store/userMemory/slices/base/action.ts
+++ b/src/store/userMemory/slices/base/action.ts
@@ -4,6 +4,7 @@ import { type SWRResponse } from 'swr';
import useSWR from 'swr';
import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';
+import { userMemoryKeys } from '@/libs/swr/keys';
import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
import { type StoreSetter } from '@/store/types';
import { type RetrieveMemoryParams, type RetrieveMemoryResult } from '@/types/userMemory';
@@ -103,9 +104,9 @@ export class BaseActionImpl {
mutate((key) => Array.isArray(key) && key[0] === SWR_FETCH_USER_MEMORY, undefined, {
revalidate: true,
}),
- mutate('useFetchPersona', null, { revalidate: false }),
+ mutate(userMemoryKeys.persona(), null, { revalidate: false }),
mutate(
- 'useFetchTags',
+ userMemoryKeys.tags(),
{
roles: [],
tags: [],
@@ -346,7 +347,7 @@ export class BaseActionImpl {
useInitIdentities = (isLogin: boolean): SWRResponse<any> => {
return useClientDataSWRWithSync<IdentityForInjection[]>(
- isLogin ? 'useInitIdentities' : null,
+ isLogin ? userMemoryKeys.identities() : null,
// Use dedicated API that filters for self identities only
() => userMemoryService.queryIdentitiesForInjection({ limit: 25 }),
{
diff --git a/src/store/userMemory/slices/home/action.ts b/src/store/userMemory/slices/home/action.ts
index dd210b74821..b3b65fbdedc 100644
--- a/src/store/userMemory/slices/home/action.ts
+++ b/src/store/userMemory/slices/home/action.ts
@@ -2,14 +2,13 @@ import { type SWRResponse } from 'swr';
import { type QueryIdentityRolesResult } from '@/database/models/userMemory';
import { useClientDataSWR } from '@/libs/swr';
+import { userMemoryKeys } from '@/libs/swr/keys';
import { userMemoryService } from '@/services/userMemory';
import { type StoreSetter } from '@/store/types';
import { type PersonaData } from '../../initialState';
import { type UserMemoryStore } from '../../store';
-const FETCH_TAGS_KEY = 'useFetchTags';
-const FETCH_PERSONA_KEY = 'useFetchPersona';
const n = (namespace: string) => namespace;
type Setter = StoreSetter<UserMemoryStore>;
@@ -27,7 +26,7 @@ export class HomeActionImpl {
useFetchPersona = (isLogin = true): SWRResponse<PersonaData | null> => {
return useClientDataSWR(
- isLogin ? FETCH_PERSONA_KEY : null,
+ isLogin ? userMemoryKeys.persona() : null,
() => userMemoryService.getPersona(),
{
onSuccess: (data: PersonaData | null | undefined) => {
@@ -46,7 +45,7 @@ export class HomeActionImpl {
useFetchTags = (): SWRResponse<QueryIdentityRolesResult> => {
return useClientDataSWR(
- FETCH_TAGS_KEY,
+ userMemoryKeys.tags(),
() =>
userMemoryService.queryIdentityRoles({
page: 1,