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 the last straggler SWR keys + fix stale prefetch key (#15863)

Arvin Xu3f7f50edef5d
diff --git a/src/features/OpenInAppButton/useOpenInApp.ts b/src/features/OpenInAppButton/useOpenInApp.ts
index 985e15a19b9..8ae57bc5009 100644
--- a/src/features/OpenInAppButton/useOpenInApp.ts
+++ b/src/features/OpenInAppButton/useOpenInApp.ts
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
import { message } from '@/components/AntdStaticMethods';
+import { openInAppKeys } from '@/libs/swr/keys';
import { electronOpenInAppService } from '@/services/electron/openInApp';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
@@ -23,7 +24,7 @@ export const useOpenInApp = (workingDirectory: string): UseOpenInAppResult => {
// SWR fetch detection once per session; main caches anyway.
const { data } = useSWR(
- isDesktop ? 'open-in-app/detect' : null,
+ isDesktop ? openInAppKeys.detect() : null,
() => electronOpenInAppService.detectApps(),
{ revalidateOnFocus: false, revalidateOnReconnect: false },
);
diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts
index ddf35a40f9d..dd8f0fbf552 100644
--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts
+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts
@@ -7,6 +7,7 @@ import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
+import { taskTemplateKeys } from '@/libs/swr/keys';
import { taskTemplateService } from '@/services/taskTemplate';
import { useBriefStore } from '@/store/brief';
import { briefListSelectors } from '@/store/brief/selectors';
@@ -56,7 +57,7 @@ export function useDailyBriefRecommendationsUI(
const { data, isLoading, mutate } = useSWR(
swrEnabled
- ? ['taskTemplate.listDailyRecommend', swrKey, refreshSeed, recommendationCount]
+ ? taskTemplateKeys.listDailyRecommend(swrKey, refreshSeed, recommendationCount)
: null,
async () =>
taskTemplateService.listDailyRecommend(interestKeys ?? [], {
diff --git a/src/features/Recommendations/hooks/useHeteroDetections.ts b/src/features/Recommendations/hooks/useHeteroDetections.ts
index 84e3b9cd8fb..7b1ad53fda7 100644
--- a/src/features/Recommendations/hooks/useHeteroDetections.ts
+++ b/src/features/Recommendations/hooks/useHeteroDetections.ts
@@ -3,12 +3,11 @@ import type { ToolStatus } from '@lobechat/electron-client-ipc';
import { HETEROGENEOUS_AGENT_CLIENT_CONFIGS } from '@lobechat/heterogeneous-agents/client';
import useSWR from 'swr';
+import { recommendationsKeys } from '@/libs/swr/keys';
import { toolDetectorService } from '@/services/electron/toolDetector';
import type { HeteroDetectionMap } from '../actions/types';
-const SWR_KEY = 'recommendations.heteroDetections';
-
/**
* Probe local Claude Code / Codex CLIs in parallel and cache the result.
*
@@ -18,7 +17,7 @@ const SWR_KEY = 'recommendations.heteroDetections';
*/
export const useHeteroDetections = (): HeteroDetectionMap => {
const { data } = useSWR(
- isDesktop ? SWR_KEY : null,
+ isDesktop ? recommendationsKeys.heteroDetections() : null,
async () => {
const entries = await Promise.all(
HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map(async (config) => {
diff --git a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
index ea48e1ad318..12b79ab762d 100644
--- a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
+++ b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
@@ -10,6 +10,7 @@ import { Virtuoso } from 'react-virtuoso';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useClientDataSWR } from '@/libs/swr';
+import { resourceKeys } from '@/libs/swr/keys';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { resourceService } from '@/services/resource';
import { useGlobalStore } from '@/store/global';
@@ -21,8 +22,6 @@ import FileListItemComponent from './ListView/ListItem';
import MasonryItemWrapper from './MasonryView/MasonryItem/MasonryItemWrapper';
import { useMasonryColumnCount } from './useMasonryColumnCount';
-const SWR_RESOURCE_SEARCH = 'SWR_RESOURCE_SEARCH';
-
const SearchResultsOverlay = memo(() => {
const { t } = useTranslation('components');
const [searchQuery, libraryId, category, viewMode] = useResourceManagerStore((s) => [
@@ -43,10 +42,11 @@ const SearchResultsOverlay = memo(() => {
const { data: rawData, isLoading } = useClientDataSWR(
isActive
- ? [
- SWR_RESOURCE_SEARCH,
- { category: libraryId ? undefined : category, libraryId, q: searchQuery },
- ]
+ ? resourceKeys.search({
+ category: libraryId ? undefined : category,
+ libraryId,
+ q: searchQuery,
+ })
: null,
async ([, params]: [string, { category?: string; libraryId?: string; q: string }]) => {
const response = await resourceService.queryResources({
diff --git a/src/hooks/useGatewayReconnect.ts b/src/hooks/useGatewayReconnect.ts
index e028189f3dd..d23fbeb27bc 100644
--- a/src/hooks/useGatewayReconnect.ts
+++ b/src/hooks/useGatewayReconnect.ts
@@ -1,5 +1,6 @@
import useSWR from 'swr';
+import { gatewayKeys } from '@/libs/swr/keys';
import { useChatStore } from '@/store/chat';
import { useServerConfigStore } from '@/store/serverConfig';
@@ -32,7 +33,7 @@ export const useGatewayReconnect = (
useSWR(
runningOperation && topicId && agentGatewayUrl
- ? ['reconnectGateway', runningOperation.operationId]
+ ? gatewayKeys.reconnect(runningOperation.operationId)
: null,
async () => {
if (!runningOperation || !topicId) return;
diff --git a/src/hooks/useHomeDailyBrief.ts b/src/hooks/useHomeDailyBrief.ts
index d4252e694b3..b1a4839c676 100644
--- a/src/hooks/useHomeDailyBrief.ts
+++ b/src/hooks/useHomeDailyBrief.ts
@@ -1,12 +1,11 @@
import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';
import { useClientDataSWR } from '@/libs/swr';
+import { homeKeys } from '@/libs/swr/keys';
import { homeService } from '@/services/home';
import { useUserStore } from '@/store/user';
import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
-const FETCH_HOME_DAILY_BRIEF_KEY = 'fetchHomeDailyBrief';
-
interface HomeDailyBriefPair {
hint: string;
welcome: string;
@@ -53,9 +52,8 @@ export const useHomeDailyBrief = (): UseHomeDailyBriefResult => {
// Scope the SWR key by userId so an account switch within the same SPA
// session (or signing in as a different user after sign-out) refetches
// and never serves the previous user's cached pairs from this slot.
- const { data } = useClientDataSWR(
- isLogin && userId ? [FETCH_HOME_DAILY_BRIEF_KEY, userId] : null,
- () => homeService.getDailyBrief(),
+ const { data } = useClientDataSWR(isLogin && userId ? homeKeys.dailyBrief(userId) : null, () =>
+ homeService.getDailyBrief(),
);
// Reset the module-level rotation when the user changes β€” otherwise the
diff --git a/src/hooks/usePrefetchAgent.ts b/src/hooks/usePrefetchAgent.ts
index 9a19943a778..08222fc74fb 100644
--- a/src/hooks/usePrefetchAgent.ts
+++ b/src/hooks/usePrefetchAgent.ts
@@ -1,19 +1,26 @@
import { useCallback } from 'react';
-import { mutate } from '@/libs/swr';
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { augmentKey, mutate } from '@/libs/swr';
+import { agentConfigKeys } from '@/libs/swr/keys';
import { agentService } from '@/services/agent';
-const FETCH_AGENT_CONFIG_KEY = 'FETCH_AGENT_CONFIG';
-
/**
* Returns a callback to prefetch agent config data into the SWR cache.
* Call the returned function on mouseEnter to warm the cache before navigation.
+ *
+ * Warms the exact key `useFetchAgentConfig` reads β€” the workspace-augmented
+ * form of `agentConfigKeys.config(agentId)` β€” so the prefetch actually hits the
+ * consumer's cache entry.
*/
export const usePrefetchAgent = () => {
return useCallback((agentId: string) => {
if (!agentId) return;
- const key = [FETCH_AGENT_CONFIG_KEY, agentId] as const;
+ const key = augmentKey(
+ agentConfigKeys.config(agentId),
+ getActiveWorkspaceId(),
+ ) as readonly unknown[];
// Populate the SWR cache without triggering re-renders on consuming hooks
mutate(key, agentService.getAgentConfigById(agentId), {
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index d64f97e517d..f99ecad05f1 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -131,6 +131,11 @@ export const agentConfigKeys = {
// ---- aiModel ------------------------------------------------------------
export const aiModelKeys = {
+ disabledModelsPage: def('aiModel:disabledModelsPage', (providerId: string, offset: number) => [
+ 'aiModel:disabledModelsPage',
+ providerId,
+ offset,
+ ]),
list: def('aiModel:list', (provider: string | undefined) => ['aiModel:list', provider]),
};
@@ -398,6 +403,21 @@ export const deviceKeys = {
deviceId,
path,
]),
+ gitRemoteBranches: def('device:gitRemoteBranches', (deviceId: string, dirPath: string) => [
+ 'device:gitRemoteBranches',
+ deviceId,
+ dirPath,
+ ]),
+ gitReviewPatches: def(
+ 'device:gitReviewPatches',
+ (deviceId: string, dirPath: string, mode: string, baseRef: string) => [
+ 'device:gitReviewPatches',
+ deviceId,
+ dirPath,
+ mode,
+ baseRef,
+ ],
+ ),
gitInfo: def('device:gitInfo', (deviceId: string, path: string, isGithub: boolean) => [
'device:gitInfo',
deviceId,
@@ -416,6 +436,10 @@ export const deviceKeys = {
// ---- user memory --------------------------------------------------------
export const userMemoryKeys = {
activities: def('userMemory:activities', (params: unknown) => ['userMemory:activities', params]),
+ analysisTask: def('userMemory:analysisTask', (taskId?: string) => [
+ 'userMemory:analysisTask',
+ taskId,
+ ]),
contexts: def('userMemory:contexts', (params: unknown) => ['userMemory:contexts', params]),
experiences: def('userMemory:experiences', (params: unknown) => [
'userMemory:experiences',
@@ -660,6 +684,67 @@ export const topicActionKeys = {
openNewOrSave: def('topicAction:openNewOrSave', () => ['topicAction:openNewOrSave']),
};
+// ---- misc remaining domains (memory-only; off CACHE_TIERS) --------------
+export const homeKeys = {
+ dailyBrief: def('home:dailyBrief', (userId: string) => ['home:dailyBrief', userId]),
+};
+export const taskTemplateKeys = {
+ listDailyRecommend: def(
+ 'taskTemplate:listDailyRecommend',
+ (interestsKey: string, refreshSeed: unknown, recommendationCount: number) => [
+ 'taskTemplate:listDailyRecommend',
+ interestsKey,
+ refreshSeed,
+ recommendationCount,
+ ],
+ ),
+};
+export const resourceKeys = {
+ list: def('resource:list', (params: unknown, workspaceId: string | null) => [
+ 'resource:list',
+ params,
+ workspaceId,
+ ]),
+ search: def('resource:search', (params: unknown) => ['resource:search', params]),
+};
+export const providerKeys = {
+ clientConfig: def('provider:clientConfig', (id: string) => ['provider:clientConfig', id]),
+};
+export const recommendationsKeys = {
+ heteroDetections: def('recommendations:heteroDetections', () => [
+ 'recommendations:heteroDetections',
+ ]),
+};
+export const openInAppKeys = {
+ detect: def('openInApp:detect', () => ['openInApp:detect']),
+};
+export const gatewayKeys = {
+ reconnect: def('gateway:reconnect', (operationId: string) => ['gateway:reconnect', operationId]),
+};
+export const userKeys = {
+ checkTrace: def('user:checkTrace', () => ['user:checkTrace']),
+ initState: def('user:initState', () => ['user:initState']),
+};
+export const builtinAgentKeys = {
+ init: def('builtinAgent:init', (slug: string) => ['builtinAgent:init', slug]),
+};
+export const imessageKeys = {
+ bridgeStatus: def('imessage:bridgeStatus', () => ['imessage:bridgeStatus']),
+};
+export const sidebarKeys = {
+ taskGroups: def('sidebar:taskGroups', (agentId: string) => ['sidebar:taskGroups', agentId]),
+};
+// Desktop/electron IPC fetches β€” roots keep their existing `electron:getXxx` value.
+export const electronKeys = {
+ appTrayVisible: def('electron:getAppTrayVisible', () => ['electron:getAppTrayVisible']),
+ desktopHotkeys: def('electron:getDesktopHotkeys', () => ['electron:getDesktopHotkeys']),
+ gatewayDeviceInfo: def('electron:getGatewayDeviceInfo', () => ['electron:getGatewayDeviceInfo']),
+ proxySettings: def('electron:getProxySettings', () => ['electron:getProxySettings']),
+ remoteServerConfig: def('electron:getRemoteServerConfig', () => [
+ 'electron:getRemoteServerConfig',
+ ]),
+};
+
/**
* Build a `mutate` matcher that selects every key in a `domain:` namespace.
*
@@ -684,19 +769,24 @@ export const swrKeys = {
aiModel: aiModelKeys,
auth: authKeys,
brief: briefKeys,
+ builtinAgent: builtinAgentKeys,
changelog: changelogKeys,
chatTool: chatToolKeys,
cron: cronKeys,
device: deviceKeys,
discover: discoverKeys,
document: documentSWRKeys,
+ electron: electronKeys,
eval: evalKeys,
favorite: favoriteKeys,
file: fileKeys,
fork: forkKeys,
+ gateway: gatewayKeys,
global: globalKeys,
group: groupKeys,
+ home: homeKeys,
image: imageKeys,
+ imessage: imessageKeys,
inbox: inboxKeys,
knowledgeBase: knowledgeBaseKeys,
message: messageKeys,
@@ -704,18 +794,25 @@ export const swrKeys = {
notebook: notebookSWRKeys,
ollama: ollamaKeys,
onboarding: onboardingKeys,
+ openInApp: openInAppKeys,
portal: portalKeys,
+ provider: providerKeys,
ragEval: ragEvalKeys,
recent: recentKeys,
+ recommendations: recommendationsKeys,
+ resource: resourceKeys,
serverConfig: serverConfigKeys,
session: sessionKeys,
share: shareKeys,
+ sidebar: sidebarKeys,
stats: statsKeys,
task: taskKeys,
+ taskTemplate: taskTemplateKeys,
thread: threadKeys,
tool: toolKeys,
topic: topicKeys,
topicAction: topicActionKeys,
+ user: userKeys,
userMemory: userMemoryKeys,
verify: verifyKeys,
video: videoKeys,
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Task/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Task/index.tsx
index ad41fc67d95..fb4ab128e61 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Task/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Task/index.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useClientDataSWR } from '@/libs/swr';
+import { sidebarKeys } from '@/libs/swr/keys';
import { taskService } from '@/services/task';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -20,8 +21,6 @@ const SIDEBAR_GROUPS = [
];
const STATUS_ORDER = SIDEBAR_GROUPS.map((g) => g.key);
-const FETCH_SIDEBAR_TASK_GROUPS_KEY = 'fetchSidebarTaskGroups';
-
interface TaskListProps {
itemKey: string;
}
@@ -33,7 +32,7 @@ const TaskList = memo<TaskListProps>(({ itemKey }) => {
const enabled = !isHeterogeneous && !!agentId;
const { data, isLoading } = useClientDataSWR<{ data: TaskGroupItem[]; success: boolean }>(
- enabled ? [FETCH_SIDEBAR_TASK_GROUPS_KEY, agentId] : null,
+ enabled ? sidebarKeys.taskGroups(agentId) : null,
async ([, id]: [string, string]) =>
taskService.groupList({ assigneeAgentId: id, groups: SIDEBAR_GROUPS }),
{
diff --git a/src/routes/(main)/agent/channel/platform/imessage/CredentialExtras.tsx b/src/routes/(main)/agent/channel/platform/imessage/CredentialExtras.tsx
index a520c7c35ab..7fe78013d6c 100644
--- a/src/routes/(main)/agent/channel/platform/imessage/CredentialExtras.tsx
+++ b/src/routes/(main)/agent/channel/platform/imessage/CredentialExtras.tsx
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import { FormInput, FormPassword } from '@/components/FormInput';
import { useClientDataSWR } from '@/libs/swr';
+import { imessageKeys } from '@/libs/swr/keys';
import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
import { imessageBridgeService } from '@/services/electron/imessageBridge';
@@ -65,8 +66,6 @@ type TestStatus = 'idle' | 'success' | 'failed';
const BLUEBUBBLES_ICON_URL = 'https://bluebubbles.app/web/splash/img/light-2x.png';
-const BRIDGE_STATUS_KEY = 'imessage-bridge-status';
-
const getErrorMessage = (error: unknown) =>
error instanceof Error ? error.message : String(error);
@@ -83,7 +82,7 @@ const CredentialExtras = memo(() => {
// it through SWR (revalidates on focus + after each mutation) instead of
// caching a copy that can drift β€” so there's no manual Refresh to keep in sync.
const { data: status, mutate } = useClientDataSWR<ImessageBridgeStatus | undefined>(
- isDesktop ? BRIDGE_STATUS_KEY : null,
+ isDesktop ? imessageKeys.bridgeStatus() : null,
() => imessageBridgeService.getStatus(),
);
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts
index b13f032f3f2..b3684d770e8 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts
@@ -4,6 +4,7 @@ import type {
} from '@lobechat/electron-client-ipc';
import { useClientDataSWR } from '@/libs/swr';
+import { deviceKeys } from '@/libs/swr/keys';
import { gitService } from '@/services/git';
export type ReviewMode = 'unstaged' | 'branch';
@@ -62,7 +63,7 @@ export const useReviewPatches = (
) => {
const enabled = Boolean(dirPath);
const key = enabled
- ? ['git-review-patches', deviceId ?? 'local', dirPath, mode, baseRef ?? '']
+ ? deviceKeys.gitReviewPatches(deviceId ?? 'local', dirPath!, mode, baseRef ?? '')
: null;
return useClientDataSWR<ReviewPatchesData>(
@@ -90,7 +91,8 @@ export const useGitRemoteBranches = (
enabled: boolean,
deviceId?: string,
) => {
- const key = dirPath && enabled ? ['git-remote-branches', deviceId ?? 'local', dirPath] : null;
+ const key =
+ dirPath && enabled ? deviceKeys.gitRemoteBranches(deviceId ?? 'local', dirPath) : null;
return useClientDataSWR(
key,
() => gitService.listGitRemoteBranches({ deviceId, path: dirPath! }),
diff --git a/src/routes/(main)/memory/features/MemoryAnalysis/useTask.ts b/src/routes/(main)/memory/features/MemoryAnalysis/useTask.ts
index a5a0fba3135..bc3592b1501 100644
--- a/src/routes/(main)/memory/features/MemoryAnalysis/useTask.ts
+++ b/src/routes/(main)/memory/features/MemoryAnalysis/useTask.ts
@@ -2,14 +2,13 @@ import { AsyncTaskStatus } from '@lobechat/types';
import { useEffect } from 'react';
import { useClientDataSWR } from '@/libs/swr';
+import { userMemoryKeys } from '@/libs/swr/keys';
import { type MemoryExtractionTask } from '@/services/userMemory/extraction';
import { memoryExtractionService } from '@/services/userMemory/extraction';
-const SWR_KEY = 'user-memory:analysis-task';
-
export const useMemoryAnalysisAsyncTask = (taskId?: string) => {
const swr = useClientDataSWR<MemoryExtractionTask | null>(
- taskId ? [SWR_KEY, taskId] : SWR_KEY,
+ taskId ? userMemoryKeys.analysisTask(taskId) : userMemoryKeys.analysisTask(),
() => memoryExtractionService.getTask(taskId),
{
refreshInterval: (data) =>
diff --git a/src/routes/(main)/settings/provider/detail/default/ClientMode.tsx b/src/routes/(main)/settings/provider/detail/default/ClientMode.tsx
index ad4610e5d98..1c1b53fade7 100644
--- a/src/routes/(main)/settings/provider/detail/default/ClientMode.tsx
+++ b/src/routes/(main)/settings/provider/detail/default/ClientMode.tsx
@@ -5,6 +5,7 @@ import { memo } from 'react';
import Loading from '@/components/Loading/BrandTextLoading';
import { useClientDataSWR } from '@/libs/swr';
+import { providerKeys } from '@/libs/swr/keys';
import { aiProviderService } from '@/services/aiProvider';
import { useAiInfraStore } from '@/store/aiInfra';
@@ -15,7 +16,7 @@ const ClientMode = memo<{ id: string }>(({ id }) => {
const useFetchAiProviderItem = useAiInfraStore((s) => s.useFetchAiProviderItem);
useFetchAiProviderItem(id);
- const { data, isLoading } = useClientDataSWR(`get-client-provider-${id}`, () =>
+ const { data, isLoading } = useClientDataSWR(providerKeys.clientConfig(id), () =>
aiProviderService.getAiProviderById(id),
);
diff --git a/src/routes/(main)/settings/provider/features/ModelList/DisabledModels.tsx b/src/routes/(main)/settings/provider/features/ModelList/DisabledModels.tsx
index eb62498a3b3..9716376a798 100644
--- a/src/routes/(main)/settings/provider/features/ModelList/DisabledModels.tsx
+++ b/src/routes/(main)/settings/provider/features/ModelList/DisabledModels.tsx
@@ -7,6 +7,7 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import useSWRInfinite from 'swr/infinite';
+import { aiModelKeys } from '@/libs/swr/keys';
import { aiModelService } from '@/services/aiModel';
import { useAiInfraStore } from '@/store/aiInfra';
import { aiModelSelectors } from '@/store/aiInfra/selectors';
@@ -30,7 +31,6 @@ enum SortType {
}
const PAGE_SIZE = 30;
-const FETCH_DISABLED_MODELS_PAGE_KEY = 'FETCH_DISABLED_MODELS_PAGE';
const DisabledModels = memo<DisabledModelsProps>(({ activeTab, providerId }) => {
const { t } = useTranslation(['modelProvider', 'common']);
@@ -76,7 +76,7 @@ const DisabledModels = memo<DisabledModelsProps>(({ activeTab, providerId }) =>
// start fetching after the initial list from store
const offset = disabledModels.length + pageIndex * PAGE_SIZE;
- return [FETCH_DISABLED_MODELS_PAGE_KEY, providerId, offset] as const;
+ return aiModelKeys.disabledModelsPage(providerId, offset);
},
[disabledModels.length, providerId, remoteEnabled],
);
diff --git a/src/store/agent/slices/builtin/action.ts b/src/store/agent/slices/builtin/action.ts
index dbf68bd8a83..ac4965c90da 100644
--- a/src/store/agent/slices/builtin/action.ts
+++ b/src/store/agent/slices/builtin/action.ts
@@ -3,6 +3,7 @@ import { type SWRResponse } from 'swr';
import { type PartialDeep } from 'type-fest';
import { useOnlyFetchOnceSWR } from '@/libs/swr';
+import { builtinAgentKeys } from '@/libs/swr/keys';
import { agentService } from '@/services/agent';
import { type StoreSetter } from '@/store/types';
@@ -55,7 +56,7 @@ export class BuiltinAgentSliceActionImpl {
context?: UseInitBuiltinAgentContext,
): SWRResponse<AgentItem | null> => {
return useOnlyFetchOnceSWR(
- context?.isLogin === false ? null : `initBuiltinAgent:${slug}`,
+ context?.isLogin === false ? null : builtinAgentKeys.init(slug),
async () => {
const data = await agentService.getBuiltinAgent(slug);
diff --git a/src/store/agentGroup/action.ts b/src/store/agentGroup/action.ts
index 5b1084c36d1..0ad1f8ab867 100644
--- a/src/store/agentGroup/action.ts
+++ b/src/store/agentGroup/action.ts
@@ -250,7 +250,6 @@ class ChatGroupInternalAction implements ResetableStore {
n('useFetchGroups/onData'),
);
},
- suspense: true,
},
);
}
diff --git a/src/store/aiInfra/slices/aiProvider/action.ts b/src/store/aiInfra/slices/aiProvider/action.ts
index fb5b4600282..ecfaeca0462 100644
--- a/src/store/aiInfra/slices/aiProvider/action.ts
+++ b/src/store/aiInfra/slices/aiProvider/action.ts
@@ -431,10 +431,7 @@ export class AiProviderActionImpl {
);
};
- useFetchAiProviderList = (opts?: {
- enabled?: boolean;
- suspense?: boolean;
- }): SWRResponse<AiProviderListItem[]> => {
+ useFetchAiProviderList = (opts?: { enabled?: boolean }): SWRResponse<AiProviderListItem[]> => {
return useClientDataSWR<AiProviderListItem[]>(
opts?.enabled === false ? null : AiProviderSwrKey.fetchAiProviderList,
() => aiProviderService.getAiProviderList(),
diff --git a/src/store/electron/actions/gateway.ts b/src/store/electron/actions/gateway.ts
index 6e59d5fb8fe..123b585a151 100644
--- a/src/store/electron/actions/gateway.ts
+++ b/src/store/electron/actions/gateway.ts
@@ -3,13 +3,12 @@ import { type SWRResponse } from 'swr';
import useSWR from 'swr';
import { mutate } from '@/libs/swr';
+import { electronKeys } from '@/libs/swr/keys';
import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
import { type StoreSetter } from '@/store/types';
import { type ElectronStore } from '../store';
-const GATEWAY_DEVICE_INFO_KEY = 'electron:getGatewayDeviceInfo';
-
type Setter = StoreSetter<ElectronStore>;
export const gatewaySlice = (set: Setter, get: () => ElectronStore, _api?: unknown) =>
new ElectronGatewayActionImpl(set, get, _api);
@@ -55,7 +54,7 @@ export class ElectronGatewayActionImpl {
};
refreshGatewayDeviceInfo = async (): Promise<void> => {
- await mutate(GATEWAY_DEVICE_INFO_KEY);
+ await mutate(electronKeys.gatewayDeviceInfo());
};
setGatewayConnectionStatus = (status: GatewayConnectionStatus): void => {
@@ -82,7 +81,7 @@ export class ElectronGatewayActionImpl {
useFetchGatewayDeviceInfo = (): SWRResponse<GatewayDeviceInfo> => {
return useSWR<GatewayDeviceInfo>(
- GATEWAY_DEVICE_INFO_KEY,
+ electronKeys.gatewayDeviceInfo(),
async () => gatewayConnectionService.getDeviceInfo() as Promise<GatewayDeviceInfo>,
{
onSuccess: (data) => {
diff --git a/src/store/electron/actions/settings.ts b/src/store/electron/actions/settings.ts
index 659ca5b3531..ec6165ac1d3 100644
--- a/src/store/electron/actions/settings.ts
+++ b/src/store/electron/actions/settings.ts
@@ -7,6 +7,7 @@ import { type SWRResponse } from 'swr';
import useSWR from 'swr';
import { mutate } from '@/libs/swr';
+import { electronKeys } from '@/libs/swr/keys';
import { desktopSettingsService } from '@/services/electron/settings';
import { type StoreSetter } from '@/store/types';
@@ -16,10 +17,6 @@ import { type ElectronStore } from '../store';
* Settings actions
*/
-const ELECTRON_PROXY_SETTINGS_KEY = 'electron:getProxySettings';
-const ELECTRON_DESKTOP_HOTKEYS_KEY = 'electron:getDesktopHotkeys';
-const ELECTRON_APP_TRAY_VISIBLE_KEY = 'electron:getAppTrayVisible';
-
type Setter = StoreSetter<ElectronStore>;
export const settingsSlice = (set: Setter, get: () => ElectronStore, _api?: unknown) =>
new ElectronSettingsActionImpl(set, get, _api);
@@ -35,15 +32,15 @@ export class ElectronSettingsActionImpl {
}
refreshDesktopHotkeys = async (): Promise<void> => {
- await mutate(ELECTRON_DESKTOP_HOTKEYS_KEY);
+ await mutate(electronKeys.desktopHotkeys());
};
refreshAppTrayVisible = async (): Promise<void> => {
- await mutate(ELECTRON_APP_TRAY_VISIBLE_KEY);
+ await mutate(electronKeys.appTrayVisible());
};
refreshProxySettings = async (): Promise<void> => {
- await mutate(ELECTRON_PROXY_SETTINGS_KEY);
+ await mutate(electronKeys.proxySettings());
};
setAppTrayVisible = async (visible: boolean): Promise<void> => {
@@ -79,7 +76,7 @@ export class ElectronSettingsActionImpl {
useFetchDesktopHotkeys = (): SWRResponse => {
return useSWR<Record<string, string>>(
- ELECTRON_DESKTOP_HOTKEYS_KEY,
+ electronKeys.desktopHotkeys(),
async () => desktopSettingsService.getDesktopHotkeys(),
{
onSuccess: (data) => {
@@ -93,7 +90,7 @@ export class ElectronSettingsActionImpl {
useGetAppTrayVisible = (enabled = true): SWRResponse => {
return useSWR<boolean>(
- enabled ? ELECTRON_APP_TRAY_VISIBLE_KEY : null,
+ enabled ? electronKeys.appTrayVisible() : null,
async () => desktopSettingsService.getAppTrayVisible(),
{
onSuccess: (data) => {
@@ -107,7 +104,7 @@ export class ElectronSettingsActionImpl {
useGetProxySettings = (): SWRResponse => {
return useSWR<NetworkProxySettings>(
- ELECTRON_PROXY_SETTINGS_KEY,
+ electronKeys.proxySettings(),
async () => desktopSettingsService.getProxySettings(),
{
onSuccess: (data) => {
diff --git a/src/store/electron/actions/sync.ts b/src/store/electron/actions/sync.ts
index 82c9695e3b3..f15329187a3 100644
--- a/src/store/electron/actions/sync.ts
+++ b/src/store/electron/actions/sync.ts
@@ -4,6 +4,7 @@ import { type SWRResponse } from 'swr';
import useSWR from 'swr';
import { mutate } from '@/libs/swr';
+import { electronKeys } from '@/libs/swr/keys';
import { remoteServerService } from '@/services/electron/remoteServer';
import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
@@ -14,8 +15,6 @@ import { type ElectronStore } from '../store';
* Remote server actions
*/
-const REMOTE_SERVER_CONFIG_KEY = 'electron:getRemoteServerConfig';
-
type Setter = StoreSetter<ElectronStore>;
export const remoteSyncSlice = (set: Setter, get: () => ElectronStore, _api?: unknown) =>
new ElectronRemoteServerActionImpl(set, get, _api);
@@ -91,7 +90,7 @@ export class ElectronRemoteServerActionImpl {
};
refreshServerConfig = async (): Promise<void> => {
- await mutate(REMOTE_SERVER_CONFIG_KEY);
+ await mutate(electronKeys.remoteServerConfig());
};
refreshUserData = async (): Promise<void> => {
@@ -111,7 +110,7 @@ export class ElectronRemoteServerActionImpl {
useDataSyncConfig = (): SWRResponse => {
return useSWR<DataSyncConfig>(
- REMOTE_SERVER_CONFIG_KEY,
+ electronKeys.remoteServerConfig(),
async () => {
try {
return await remoteServerService.getRemoteServerConfig();
diff --git a/src/store/file/slices/resource/hooks.test.ts b/src/store/file/slices/resource/hooks.test.ts
index 9127310db0d..e74167f0e3d 100644
--- a/src/store/file/slices/resource/hooks.test.ts
+++ b/src/store/file/slices/resource/hooks.test.ts
@@ -53,9 +53,9 @@ describe('revalidateResources', () => {
const [matcher] = vi.mocked(mutate).mock.calls[0] as [(key: unknown) => boolean];
expect(matcher).toEqual(expect.any(Function));
- expect(matcher(['SWR_RESOURCES', mocks.queryParams, 'workspace-1'])).toBe(true);
- expect(matcher(['SWR_RESOURCES', mocks.queryParams, 'workspace-2'])).toBe(false);
- expect(matcher(['SWR_RESOURCES', mocks.queryParams])).toBe(false);
+ expect(matcher(['resource:list', mocks.queryParams, 'workspace-1'])).toBe(true);
+ expect(matcher(['resource:list', mocks.queryParams, 'workspace-2'])).toBe(false);
+ expect(matcher(['resource:list', mocks.queryParams])).toBe(false);
expect(matcher(['OTHER_KEY', mocks.queryParams, 'workspace-1'])).toBe(false);
expect(getActiveWorkspaceId).toHaveBeenCalled();
});
@@ -73,7 +73,7 @@ describe('useFetchResources', () => {
renderHook(() => useFetchResources(mocks.queryParams));
expect(mocks.useClientDataSWR).toHaveBeenCalledWith(
- ['SWR_RESOURCES', mocks.queryParams, 'workspace-1'],
+ ['resource:list', mocks.queryParams, 'workspace-1'],
expect.any(Function),
expect.any(Object),
);
diff --git a/src/store/file/slices/resource/hooks.ts b/src/store/file/slices/resource/hooks.ts
index 5f1a915d5b1..f5e5a6469db 100644
--- a/src/store/file/slices/resource/hooks.ts
+++ b/src/store/file/slices/resource/hooks.ts
@@ -7,14 +7,14 @@ import {
useActiveWorkspaceId,
} from '@/business/client/hooks/useActiveWorkspaceId';
import { mutate, useClientDataSWR } from '@/libs/swr';
+import { resourceKeys } from '@/libs/swr/keys';
import { resourceService } from '@/services/resource';
import type { ResourceQueryParams } from '@/types/resource';
import { useFileStore } from '../../store';
import { mergeServerResourcesWithOptimistic } from './utils';
-const SWR_KEY_RESOURCES = 'SWR_RESOURCES';
-type ResourceSWRKey = [typeof SWR_KEY_RESOURCES, ResourceQueryParams, string | null];
+type ResourceSWRKey = [string, ResourceQueryParams, string | null];
const isResourceSWRKey = (
key: unknown,
@@ -23,7 +23,9 @@ const isResourceSWRKey = (
) => {
if (!Array.isArray(key)) return false;
- return key[0] === SWR_KEY_RESOURCES && isEqual(key[1], queryParams) && key[2] === workspaceId;
+ return (
+ key[0] === resourceKeys.list.root && isEqual(key[1], queryParams) && key[2] === workspaceId
+ );
};
/**
@@ -51,7 +53,7 @@ export const useFetchResources = (params: ResourceQueryParams | null, enable: an
const workspaceId = useActiveWorkspaceId();
const swr = useClientDataSWR(
- enable && params ? ([SWR_KEY_RESOURCES, params, workspaceId] satisfies ResourceSWRKey) : null,
+ enable && params ? resourceKeys.list(params, workspaceId) : null,
async ([, queryParams]: ResourceSWRKey) => {
const response = await resourceService.queryResources({
...queryParams,
diff --git a/src/store/image/slices/generationTopic/action.ts b/src/store/image/slices/generationTopic/action.ts
index 6aa17ab309d..1d8dfae7522 100644
--- a/src/store/image/slices/generationTopic/action.ts
+++ b/src/store/image/slices/generationTopic/action.ts
@@ -211,7 +211,6 @@ export class GenerationTopicActionImpl {
enabled ? imageKeys.generationTopics() : null,
() => generationTopicService.getAllGenerationTopics('image'),
{
- suspense: true,
onSuccess: (data) => {
// No need to update if data is the same
if (isEqual(data, this.#get().generationTopics)) return;
diff --git a/src/store/library/slices/crud/action.ts b/src/store/library/slices/crud/action.ts
index e81233e9dc7..36e8214a096 100644
--- a/src/store/library/slices/crud/action.ts
+++ b/src/store/library/slices/crud/action.ts
@@ -80,9 +80,7 @@ export class KnowledgeBaseCrudActionImpl {
);
};
- useFetchKnowledgeBaseList = (
- params: { suspense?: boolean } = {},
- ): SWRResponse<KnowledgeBaseItem[]> => {
+ useFetchKnowledgeBaseList = (): SWRResponse<KnowledgeBaseItem[]> => {
return useClientDataSWR<KnowledgeBaseItem[]>(
knowledgeBaseKeys.list(),
() => knowledgeBaseService.getKnowledgeBaseList(),
@@ -92,7 +90,6 @@ export class KnowledgeBaseCrudActionImpl {
if (!this.#get().initKnowledgeBaseList)
this.#set({ initKnowledgeBaseList: true }, false, 'useFetchKnowledgeBaseList/init');
},
- suspense: params.suspense,
},
);
};
diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.ts
index deaff4fd044..3aaa35342b4 100644
--- a/src/store/session/slices/session/action.ts
+++ b/src/store/session/slices/session/action.ts
@@ -261,7 +261,6 @@ export class SessionActionImpl {
n('useFetchSessions/onSuccess', data),
);
},
- suspense: true,
},
);
};
diff --git a/src/store/user/slices/auth/action.test.ts b/src/store/user/slices/auth/action.test.ts
index a061544c905..a9d93a60079 100644
--- a/src/store/user/slices/auth/action.test.ts
+++ b/src/store/user/slices/auth/action.test.ts
@@ -2,6 +2,7 @@ import { act, renderHook } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { mutate } from '@/libs/swr';
+import { userKeys } from '@/libs/swr/keys';
import { useUserStore } from '@/store/user';
vi.mock('zustand/traditional');
@@ -44,7 +45,7 @@ describe('createAuthSlice', () => {
await result.current.refreshUserState();
});
- expect(mutate).toHaveBeenCalledWith('initUserState');
+ expect(mutate).toHaveBeenCalledWith(userKeys.initState());
});
});
diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.ts
index 936865aa0b5..53498005b13 100644
--- a/src/store/user/slices/common/action.ts
+++ b/src/store/user/slices/common/action.ts
@@ -7,6 +7,7 @@ import { type PartialDeep } from 'type-fest';
import { DEFAULT_PREFERENCE } from '@/const/user';
import { mutate, useOnlyFetchOnceSWR } from '@/libs/swr';
+import { userKeys } from '@/libs/swr/keys';
import { userService } from '@/services/user';
import { type StoreSetter } from '@/store/types';
import { type UserStore } from '@/store/user';
@@ -20,7 +21,6 @@ import { userGeneralSettingsSelectors } from '../settings/selectors';
const n = setNamespace('common');
-const GET_USER_STATE_KEY = 'initUserState';
/**
* Common actions
*/
@@ -40,7 +40,7 @@ export class CommonActionImpl {
}
refreshUserState = async (): Promise<void> => {
- await mutate(GET_USER_STATE_KEY);
+ await mutate(userKeys.initState());
};
updateAvatar = async (avatar: string): Promise<void> => {
@@ -73,7 +73,7 @@ export class CommonActionImpl {
useCheckTrace = (shouldFetch: boolean): SWRResponse<any> => {
return useSWR<boolean>(
- shouldFetch ? 'checkTrace' : null,
+ shouldFetch ? userKeys.checkTrace() : null,
() => {
const telemetry = userGeneralSettingsSelectors.telemetry(this.#get());
@@ -97,7 +97,7 @@ export class CommonActionImpl {
},
): SWRResponse => {
return useOnlyFetchOnceSWR<UserInitializationState>(
- !!isLogin || isDesktop ? GET_USER_STATE_KEY : null,
+ !!isLogin || isDesktop ? userKeys.initState() : null,
() => userService.getUserState(),
{
onError: (error) => {
diff --git a/src/store/video/slices/generationTopic/action.ts b/src/store/video/slices/generationTopic/action.ts
index a782c74050f..53a8007f662 100644
--- a/src/store/video/slices/generationTopic/action.ts
+++ b/src/store/video/slices/generationTopic/action.ts
@@ -274,7 +274,6 @@ export class GenerationTopicActionImpl {
if (isEqual(data, this.#get().generationTopics)) return;
this.#set({ generationTopics: data }, false, n('useFetchGenerationTopics'));
},
- suspense: true,
},
);
}