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.

πŸ”’ chore(swr): freeze SWR key registry, route new server data to local-replica (#22727)

Arvin Xu59269b4d6241
diff --git a/.agents/skills/data-fetching-architecture/SKILL.md b/.agents/skills/data-fetching-architecture/SKILL.md
index 7ab4b90a5fd..79748b0ac84 100644
--- a/.agents/skills/data-fetching-architecture/SKILL.md
+++ b/.agents/skills/data-fetching-architecture/SKILL.md
@@ -7,20 +7,24 @@ user-invocable: false
# LobeHub Data Fetching Architecture
```text
-Component β†’ Store useFetchXxx hook β†’ Service β†’ lambdaClient
- ← SWR request state + store data ← response
+Component β†’ Store useFetchXxx hook β†’ replica slice β†’ Service β†’ lambdaClient
+ ← sync flags + store data (selectors) ← response
```
+New server data the UI paints goes through `local-replica` (`@/libs/replica`), not a
+new SWR key. `src/libs/swr/keys.ts` is frozen: `src/libs/swr/keys.frozen.test.ts`
+fails on any added key, and its legacy list only shrinks.
+
## Layer boundaries
- Services in `src/services/` own API calls: `.query()` for reads, `.mutate()` for writes.
Export a service instance per domain; components and stores do not call `lambdaClient` directly.
-- Store read hooks use `useClientDataSWR` and return its SWR response, including `error`
- and `mutate`. Sync successful results into the store through the wrapper's supported
- callback (`onSuccess`, or `onData` for the sync wrapper).
-- Server lists and details that paint from a local copy go through `@/libs/replica`
- instead: the store's `useFetchXxx` returns `slice.useSync(params)` (flags only) and
- the engine writes the store. See the Replica section of [zustand](../zustand/SKILL.md).
+- Server lists and details go through `@/libs/replica`: the store's `useFetchXxx`
+ returns `slice.useSync(params)` (flags only) and the engine writes the store. See
+ the Replica section of [zustand](../zustand/SKILL.md).
+- `useClientDataSWR` + `onSuccess` syncing into the store is the legacy layout. Keep
+ it only inside an existing hook whose key is already in `src/libs/swr/keys.ts`; do
+ not add keys or new SWR-backed store hooks for server data.
- Components call these hooks and read store data through selectors. Do not fetch in
`useEffect` or duplicate server data in component `useState`.
- Use `useFetchXxx` for read hooks and `refreshXxx` for cache invalidation.
@@ -36,37 +40,35 @@ avoiding flicker, reusing persistence, and the user `displaySnapshot.ts` boundar
## Cache keys and refresh
-Reuse the domain key factory in `src/libs/swr/keys.ts`; define a shared key if the
-domain has none. Include every parameter that changes the response: entity or parent
-id, filters, sort, and pagination. Read and refresh must construct the same key.
-
-Import `useClientDataSWR` and `mutate` from `@/libs/swr`, keeping the application's
-workspace/cache handling. Return a `null` key when a required id is absent; passing
-`undefined` to a store hook only disables fetching if that hook maps it to `null`.
+Do not add SWR keys. A resource that needs a new key gets a replica instead
+(`defineReplica` / `definePagedReplica` in the store's `projection.ts`). The replica
+params replace the key, so include every parameter that changes the response:
+entity or parent id, filters, sort, and pagination. Refresh with
+`slice.fetch(params, { fresh: true })` or `revalidate()` from `useSync`; read and
+refresh must use the same params. Disable a sync whose required id is absent with
+`useSync(params, { enabled: false })`.
For example, inside an action class:
```typescript
-useFetchBenchmarks = () =>
- useClientDataSWR(evalKeys.benchmarks(), () => agentEvalService.listBenchmarks(), {
- onSuccess: (data) => {
- this.#set({ benchmarkList: data, benchmarkListInit: true });
- },
- });
-
-refreshBenchmarks = async () => {
- await mutate(evalKeys.benchmarks());
+useFetchAgentLabels = (isLogin: boolean | undefined): ReplicaSyncResult =>
+ this.#labels.useSync(LIST_PARAMS, { enabled: isLogin === true });
+
+refreshAgentLabels = async () => {
+ await this.#labels.revalidate();
};
```
-Read the current [benchmark action](../../../src/store/eval/slices/benchmark/action.ts)
-for store wiring and the [SWR wrappers](../../../src/libs/swr/index.ts) for their
-actual options. These links locate implementation; they do not make every existing
+Read the current [label action](../../../src/store/home/slices/label/action.ts) for
+store wiring. These links locate implementation; they do not make every existing
call site a template to copy unchanged.
+Legacy SWR hooks keep their existing key from `src/libs/swr/keys.ts` and import
+`useClientDataSWR` and `mutate` from `@/libs/swr`. When you migrate one to a replica,
+delete its key and its entry in `keys.frozen.test.ts`.
+
Hooks that share a known parent id can run together. If one request needs a value
-returned by another, keep its key `null` until that value exists. Do not assume the
-application wrapper uses upstream SWR's default deduplication interval.
+returned by another, keep it disabled until that value exists.
For lists cached separately under multiple parents, see
[parent-keyed lists](references/walkthrough.md). Ordinary flat lists need no extra layer.
@@ -89,33 +91,33 @@ For lists cached separately under multiple parents, see
## Render loading, errors, and settled data
-Consume the read hook's SWR response. Success-only flags such as `isInit`, missing
-map entries, and `data ?? []` cannot distinguish an initial request failure from
-loading or empty results.
+Success-only flags such as `isInit`, missing map entries, and `data ?? []` cannot
+distinguish an initial request failure from loading or empty results.
Use `AsyncBoundary` for standard loading/error/empty/data surfaces; use `AsyncError`
-for custom layouts and inline failures. Pass the original SWR `data` to the boundary:
-`undefined` means no successful result, whereas `[]` is a settled empty result.
+for custom layouts and inline failures. `undefined` data means no successful result,
+whereas `[]` is a settled empty result.
Replica `useSync` returns no `data`. Feed `AsyncBoundary` its `error` and a settled
signal from the store entry (`data={isListInit || undefined}`, where the selector is
-`entry !== undefined`); see `src/features/Pages/PageLayout/Body/index.tsx`.
+`entry !== undefined`); see `src/features/Pages/PageLayout/Body/index.tsx`. Legacy
+SWR hooks pass the original SWR `data` instead.
```tsx
const BenchmarkList = () => {
- const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
- const benchmarks = useEvalStore((s) => s.benchmarkList);
- const { data, error, isLoading, mutate } = useFetchBenchmarks();
+ const { error, revalidate } = benchmarkActions.useFetchBenchmarks();
+ const isListInit = useEvalStore(benchmarkSelectors.isBenchmarkListInit);
+ const benchmarks = useEvalStore(benchmarkSelectors.benchmarkList);
return (
<AsyncBoundary
- data={data}
+ data={isListInit || undefined}
empty={<EmptyState />}
error={error}
- isEmpty={data?.length === 0}
- isLoading={isLoading}
+ isEmpty={benchmarks.length === 0}
+ isLoading={!isListInit && !error}
onRetry={() => {
- void mutate();
+ void revalidate();
}}
>
<BenchmarkCards items={benchmarks} />
@@ -139,12 +141,13 @@ renderers. Follow these distinctions when adapting it:
## Migrating an existing fetch
-Move the API call into its service and the request into a store SWR hook. Reuse the
-existing state shape and action organization unless they need to change for the task.
+Move the API call into its service and the request into a replica-backed store hook.
+Reuse the existing action organization unless it needs to change for the task.
Replace the component's effect/local fetch state with that hook and selectors, then
-connect `error`, retry, and pending feedback. Refresh the same cache key after writes.
+connect `error`, retry, and pending feedback. Refresh the same replica params after
+writes.
Check initial failure, retry, settled-empty results, background failure, and switching
-ids against the surface being changed. For stale data, compare read/refresh keys and
-the store bucket they update; for stuck loading, inspect rejected requests as well as
+ids against the surface being changed. For stale data, compare read/refresh params (or
+legacy keys) and the store bucket they update; for stuck loading, inspect rejected requests as well as
success callbacks. Do not add a second fetch or another loading flag to mask the cause.
diff --git a/.agents/skills/data-fetching-architecture/references/walkthrough.md b/.agents/skills/data-fetching-architecture/references/walkthrough.md
index 56941841f6b..bc17bb38adf 100644
--- a/.agents/skills/data-fetching-architecture/references/walkthrough.md
+++ b/.agents/skills/data-fetching-architecture/references/walkthrough.md
@@ -1,5 +1,11 @@
# Parent-Keyed Lists
+> Legacy SWR layout. New parent-keyed data uses a replica: its `key(params)` returns
+> the parent id, so the view map holds one entry per parent and no SWR key is added (see
+> [zustand](../../zustand/SKILL.md), Replica-Backed Server Data). Apply this page only
+> when editing an existing SWR-backed store whose key is already in
+> `src/libs/swr/keys.ts`.
+
Use this variant when the store needs to retain separate lists for multiple parents,
such as datasets under different benchmarks. A single visible list does not need a
parent-keyed map merely because its request has a parent parameter.
diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.ts
new file mode 100644
index 00000000000..c96f8049f78
--- /dev/null
+++ b/src/libs/swr/keys.frozen.test.ts
@@ -0,0 +1,225 @@
+import { describe, expect, it } from 'vitest';
+
+import * as keyRegistry from './keys';
+
+/**
+ * SWR key registry freeze.
+ *
+ * Server data the UI paints moves onto `local-replica` (`@/libs/replica`, see the
+ * `zustand` skill, "Replica-Backed Server Data"). The SWR key factories below are
+ * legacy: nothing may be added here, and this list only shrinks.
+ *
+ * - A key you need is missing β†’ model the data as a replica instead of adding a key.
+ * - You removed or migrated a key β†’ delete its entry here too.
+ */
+const LEGACY_SWR_KEYS = [
+ 'acceptanceCollaborationKeys.conversation',
+ 'acceptanceCommentKeys.list',
+ 'agentConfigKeys.search',
+ 'agentHomeKeys.topics',
+ 'agentSignalKeys.receipts',
+ 'apiKeyKeys.list',
+ 'authKeys.oidcClientMetadata',
+ 'authKeys.oidcInteraction',
+ 'botWakeKeys.decisions',
+ 'botWakeKeys.summary',
+ 'briefKeys.news',
+ 'canvasKeys.storage',
+ 'changelogKeys.modalIndex',
+ 'changelogKeys.post',
+ 'channelKeys.agentEnvironment',
+ 'channelKeys.userCandidates',
+ 'channelKeys.wakeConfig',
+ 'cronKeys.topicsWithJobInfo',
+ 'deviceKeys.appUpdateState',
+ 'deviceKeys.browseDirectory',
+ 'deviceKeys.cliUpdateState',
+ 'deviceKeys.gitLinkedPR',
+ 'deviceKeys.gitPullRequestActivity',
+ 'deviceKeys.gitPullRequestDetail',
+ 'deviceKeys.gitPullRequestMergeContext',
+ 'deviceKeys.gitReviewPatches',
+ 'deviceKeys.repoType',
+ 'deviceKeys.systemInfo',
+ 'discoverKeys.mcpAgents',
+ 'discoverKeys.skillAgents',
+ 'discoverKeys.skillStoreMarketSkills',
+ 'documentCommentKeys.anchors',
+ 'documentCommentKeys.detail',
+ 'documentCommentKeys.replies',
+ 'documentCommentKeys.summary',
+ 'documentCommentKeys.threads',
+ 'documentLikeKeys.summary',
+ 'electronKeys.appMenu',
+ 'electronKeys.appTrayVisible',
+ 'electronKeys.claudeCodeAccounts',
+ 'electronKeys.desktopHotkeys',
+ 'electronKeys.gatewayDeviceInfo',
+ 'electronKeys.proxySettings',
+ 'electronKeys.remoteServerConfig',
+ 'electronKeys.workspaceDeviceId',
+ 'evalKeys.benchmarkDetail',
+ 'evalKeys.benchmarks',
+ 'evalKeys.datasetRuns',
+ 'evalKeys.runDetail',
+ 'evalKeys.runResults',
+ 'evalKeys.runs',
+ 'evalKeys.testCaseDetail',
+ 'evalKeys.testCases',
+ 'expertiseKeys.domain',
+ 'expertiseKeys.historyCount',
+ 'expertiseKeys.lesson',
+ 'expertiseKeys.overview',
+ 'expertiseKeys.ruleRevisions',
+ 'expertiseKeys.ruleSources',
+ 'expertiseKeys.rules',
+ 'favoriteKeys.status',
+ 'fileKeys.ttsFile',
+ 'forkKeys.groupSource',
+ 'forkKeys.source',
+ 'gatewayKeys.clientLlmWaits',
+ 'gatewayKeys.reconnect',
+ 'globalKeys.latestVersion',
+ 'globalKeys.serverVersion',
+ 'globalKeys.systemStatus',
+ 'goalKeys.pendingClarifications',
+ 'goalKeys.pendingForIsland',
+ 'groupKeys.queryAgentsForCreate',
+ 'imageKeys.generationStatus',
+ 'imessageKeys.bridgeStatus',
+ 'inboxKeys.navigationCounts',
+ 'inboxKeys.notifications',
+ 'inboxKeys.unreadCount',
+ 'inboxKeys.unreadMentions',
+ 'localFileKeys.claudeCodeMemory',
+ 'localFileKeys.gitWorkingTreeFiles',
+ 'localFileKeys.preview',
+ 'localFileKeys.projectIndex',
+ 'mcpAppKeys.resource',
+ 'messageKeys.list',
+ 'messengerKeys.agentsForBinding',
+ 'messengerKeys.availablePlatforms',
+ 'messengerKeys.bindingScopes',
+ 'messengerKeys.listMyInstallations',
+ 'messengerKeys.listMyLinks',
+ 'messengerKeys.myLink',
+ 'messengerKeys.peek',
+ 'messengerKeys.pushWindow',
+ 'ollamaKeys.downloadModel',
+ 'onboardingKeys.agentBootstrap',
+ 'onboardingKeys.agentHistoryTopics',
+ 'onboardingKeys.analysisStatus',
+ 'onboardingKeys.profile',
+ 'onboardingKeys.suggestedTasks',
+ 'onboardingKeys.understandingSession',
+ 'onboardingKeys.understandingStart',
+ 'onboardingKeys.understandingTopic',
+ 'openInAppKeys.detect',
+ 'ragEvalKeys.datasetList',
+ 'ragEvalKeys.datasetRecords',
+ 'ragEvalKeys.evaluationList',
+ 'recentKeys.topicList',
+ 'recentKeys.trayList',
+ 'recommendationsKeys.heteroDetections',
+ 'resourceKeys.list',
+ 'scmKeys.changeRequests',
+ 'scmKeys.config',
+ 'scmKeys.identity',
+ 'scmKeys.installations',
+ 'scmKeys.repositories',
+ 'scmKeys.wakeTarget',
+ 'serverConfigKeys.get',
+ 'shareKeys.agentInfo',
+ 'shareKeys.agentShareConnectors',
+ 'shareKeys.agentShareEligibleWorks',
+ 'shareKeys.agentShareGrantableSkills',
+ 'shareKeys.agentShareStats',
+ 'shareKeys.agentShareStatus',
+ 'shareKeys.artifact',
+ 'shareKeys.file',
+ 'shareKeys.pageDocument',
+ 'shareKeys.topic',
+ 'shareKeys.topicInfo',
+ 'shareKeys.visitorTopics',
+ 'statsKeys.agentUsageStat',
+ 'statsKeys.agents',
+ 'statsKeys.countAgents',
+ 'statsKeys.countMessages',
+ 'statsKeys.countTopics',
+ 'statsKeys.heatmaps',
+ 'statsKeys.maxTaskDuration',
+ 'statsKeys.messages',
+ 'statsKeys.rankAgents',
+ 'statsKeys.rankModels',
+ 'statsKeys.rankTopics',
+ 'statsKeys.sessions',
+ 'statsKeys.topics',
+ 'statsKeys.usageLogs',
+ 'statsKeys.usageStat',
+ 'statsKeys.welcome',
+ 'taskLabelKeys.list',
+ 'threadKeys.list',
+ 'toolKeys.agentSkillDetail',
+ 'toolKeys.agentSkills',
+ 'toolKeys.composioAppTools',
+ 'toolKeys.composioConnections',
+ 'topicActionKeys.openNewOrSave',
+ 'topicKeys.list',
+ 'topicKeys.scheduledRunWatch',
+ 'topicKeys.search',
+ 'userKeys.checkTrace',
+ 'userMemoryKeys.activities',
+ 'userMemoryKeys.analysisTask',
+ 'userMemoryKeys.contextStories',
+ 'userMemoryKeys.contextStory',
+ 'userMemoryKeys.contexts',
+ 'userMemoryKeys.experiences',
+ 'userMemoryKeys.memoryDetail',
+ 'userMemoryKeys.persona',
+ 'userMemoryKeys.preferences',
+ 'userMemoryKeys.retrieve',
+ 'userMemoryKeys.tags',
+ 'verifyKeys.acceptancePage',
+ 'verifyKeys.acceptancePurgePreview',
+ 'verifyKeys.acceptanceStatuses',
+ 'verifyKeys.acceptances',
+ 'verifyKeys.criteria',
+ 'verifyKeys.instruction',
+ 'verifyKeys.reportBundle',
+ 'verifyKeys.rubric',
+ 'verifyKeys.rubricCriteria',
+ 'verifyKeys.rubrics',
+ 'verifyKeys.runAcceptanceRound',
+ 'verifyKeys.tracing',
+ 'videoKeys.generationStatus',
+ 'workKeys.conversation',
+ 'workKeys.versions',
+ 'workKeys.workspace',
+];
+
+const collectRegistryKeys = () =>
+ Object.entries(keyRegistry)
+ .filter(
+ ([name, value]) =>
+ name.endsWith('Keys') && name !== 'swrKeys' && typeof value === 'object' && value !== null,
+ )
+ .flatMap(([name, value]) => Object.keys(value).map((prop) => `${name}.${prop}`))
+ .sort();
+
+describe('SWR key registry freeze', () => {
+ it('adds no new SWR keys β€” new server data goes through local-replica', () => {
+ const added = collectRegistryKeys().filter((key) => !LEGACY_SWR_KEYS.includes(key));
+
+ expect(
+ added,
+ 'New SWR keys are frozen. Model this server data with local-replica (`@/libs/replica`, zustand skill "Replica-Backed Server Data") instead of adding a key to src/libs/swr/keys.ts.',
+ ).toEqual([]);
+ });
+
+ it('drops removed keys from the legacy list so it only shrinks', () => {
+ const registry = new Set(collectRegistryKeys());
+ const stale = LEGACY_SWR_KEYS.filter((key) => !registry.has(key));
+
+ expect(stale, 'Remove these entries from LEGACY_SWR_KEYS.').toEqual([]);
+ });
+});
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 25fc4745c75..9cb5f97c856 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -1,6 +1,10 @@
/**
* Central SWR key registry
*
+ * Frozen: do not add keys. New server data the UI paints goes through
+ * `local-replica` (`@/libs/replica`). `keys.frozen.test.ts` fails on any added
+ * key; when a key is migrated or removed, delete its entry there too.
+ *
* Single source of truth for SWR cache keys, organized by business domain and
* named with one convention: the first array element is `'<domain>:<resource>'`
* (lowerCamel resource), followed by parameters.