🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(label): move the agent label registry onto @lobechat/replica (#20622)
Arvin Xuf8c6bc3dd7af
diff --git a/src/hooks/useFetchAgentLabels.ts b/src/hooks/useFetchAgentLabels.tsindex 7f080162246..470f24656e1 100644--- a/src/hooks/useFetchAgentLabels.ts+++ b/src/hooks/useFetchAgentLabels.ts@@ -1,20 +1,35 @@-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useHomeStore } from '@/store/home';+import { agentLabelSelectors } from '@/store/home/selectors';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/slices/auth/selectors';/**- * Hook to fetch the agent label registry into the home store. Mounted by- * every surface that renders labels (sidebar list, view-all page, settings) —- * SWR dedupes concurrent mounts.+ * Sync the agent label registry into the home store (the labels are read+ * through `agentLabelSelectors`). Mounted by every surface that renders labels+ * (sidebar list, view-all page, settings) — the replica's sync hook dedupes+ * concurrent mounts.*- * Scoped by workspace: the registries are disjoint, so a switch must refetch- * rather than reuse the previous scope's cache.+ * The scope (personal / workspace) is owned by the replica, so the caller no+ * longer passes a workspace id: a switch drops the previous registry and+ * refetches on its own.+ *+ * @returns isLoading - registry not loaded yet and a fetch is in flight (drives+ * the settings page skeleton instead of an empty "no labels" state)+ * @returns error - the network error, so consumers can surface a failure state+ * instead of a permanent skeleton+ * @returns mutate - retry the same request (wired into the error state's Retry)*/export const useFetchAgentLabels = () => {const isLogin = useUserStore(authSelectors.isLogin);- const workspaceId = useActiveWorkspaceId();const useFetchAgentLabelsHook = useHomeStore((s) => s.useFetchAgentLabels);- return useFetchAgentLabelsHook(isLogin, workspaceId);+ const isAgentLabelsInit = useHomeStore(agentLabelSelectors.isLabelsInit);++ const { error, isValidating, revalidate } = useFetchAgentLabelsHook(isLogin);++ return {+ error,+ isLoading: !isAgentLabelsInit && isValidating,+ mutate: revalidate,+ };};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 2a3aafa8e2b..59442efb324 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -239,20 +239,6 @@ export const isDocumentCommentKeyForEvent = (return false;};-// ---- agent labels --------------------------------------------------------export const agentLabelKeys = {- /**- * Agent label registry (workspace-shared, or personal). Keyed by workspace:- * the registries are disjoint per scope, so a shared key would serve the- * previous workspace's labels across a switch.- */- list: def('agentLabel:list', (isLogin: boolean, workspaceId: string | null | undefined) => [- 'agentLabel:list',- isLogin,- workspaceId ?? null,- ]),-};-// ---- agent builder (opening-suggestion chips) ---------------------------// Persisted to the localStorage tier (see `CACHE_TIERS.local`) so revisits skip// the LLM generation instead of paying a skeleton + a generateJSON call every@@ -1425,7 +1411,6 @@ export const swrKeys = {agentDocument: agentDocumentSWRKeys,agentHome: agentHomeKeys,agentKnowledge: agentKnowledgeKeys,- agentLabel: agentLabelKeys,agentProfile: agentProfileKeys,agentSignal: agentSignalKeys,aiModel: aiModelKeys,diff --git a/src/store/home/slices/label/action.ts b/src/store/home/slices/label/action.tsindex 89aeb2f05c5..cd82f00d614 100644--- a/src/store/home/slices/label/action.ts+++ b/src/store/home/slices/label/action.ts@@ -5,30 +5,62 @@ import {type SidebarGroup,} from '@lobechat/types';import isEqual from 'fast-deep-equal';-import { useEffect } from 'react';-import { type SWRResponse } from 'swr';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { agentLabelKeys } from '@/libs/swr/keys';+import { createReplicaSlice, type ReplicaLens, type ReplicaSyncResult } from '@/libs/replica';import { agentLabelService } from '@/services/agentLabel';import { type HomeStore } from '@/store/home/store';import { type StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';+import { AGENT_LABELS_KEY, agentLabelsResource } from './projection';+const n = setNamespace('label');+const LIST_PARAMS = {} as Record<string, never>;++/**+ * The registry keeps its long-standing flat field (`agentLabels`) as the+ * replica view, gated by `isAgentLabelsInit` so a loaded-but-empty registry+ * stays distinguishable from one that was never fetched.+ *+ * The cache scope (`${userId}:${workspaceId}`) owns the partition now: a switch+ * clears the view before paint (the replica's `useSync` resets the scope in a+ * layout effect), so the previous workspace's label ids can never be applied to+ * an agent here.+ */+const agentLabelsLens: ReplicaLens<HomeStore, AgentLabelListItem[]> = {+ clear: () => ({ agentLabels: [], isAgentLabelsInit: false }),+ get: (state) => (state.isAgentLabelsInit ? state.agentLabels : undefined),+ keys: (state) => (state.isAgentLabelsInit ? [AGENT_LABELS_KEY] : []),+ set: (_state, _key, data) =>+ data+ ? { agentLabels: data, isAgentLabelsInit: true }+ : { agentLabels: [], isAgentLabelsInit: false },+};+type Setter = StoreSetter<HomeStore>;export const createLabelSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>new LabelActionImpl(set, get, _api);export class LabelActionImpl {readonly #get: () => HomeStore;+ readonly #labels;readonly #set: Setter;constructor(set: Setter, get: () => HomeStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#labels = createReplicaSlice(agentLabelsResource, {+ actionPrefix: n('agentLabels'),+ fetcher: () => agentLabelService.getLabels(),+ get,+ // An unchanged registry must not re-render the picker / settings table.+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'agentLabelsReplica',+ view: agentLabelsLens,+ });}createAgentLabel = async (params: {@@ -41,11 +73,13 @@ export class LabelActionImpl {return id;};+ /**+ * Revalidate the registry of the current identity. The replica scope carries+ * the workspace, so this always refreshes the registry the caller is in —+ * never another scope's.+ */refreshAgentLabels = async (): Promise<void> => {- // Revalidate the key for the scope the registry was loaded for, not a- // hardcoded one — the key carries the workspace, so mutating inside a- // workspace must not refresh the personal list instead.- await mutate(agentLabelKeys.list(true, this.#get().agentLabelsWorkspaceId));+ await this.#labels.revalidate();};removeAgentLabel = async (id: string): Promise<void> => {@@ -145,48 +179,14 @@ export class LabelActionImpl {await Promise.all([this.refreshAgentLabels(), this.#get().refreshAgentList()]);};- useFetchAgentLabels = (- isLogin: boolean | undefined,- workspaceId: string | null | undefined,- ): SWRResponse<AgentLabelListItem[]> => {- const scopeId = workspaceId ?? null;-- // Changing the SWR key refetches, but the store keeps serving the previous- // scope's registry until that request lands. Drop it immediately instead:- // an empty picker is a moment of missing UI, while a picker holding- // foreign label ids is a destructive write waiting to happen.- useEffect(() => {- if (this.#get().agentLabelsWorkspaceId === scopeId) return;-- this.#set(- { agentLabels: [], agentLabelsWorkspaceId: scopeId, isAgentLabelsInit: false },- false,- n('useFetchAgentLabels/scopeChanged'),- );- }, [scopeId]);-- return useClientDataSWR<AgentLabelListItem[]>(- isLogin === true ? agentLabelKeys.list(isLogin, scopeId) : null,- () => agentLabelService.getLabels(),- {- onSuccess: (data) => {- const state = this.#get();- if (- state.isAgentLabelsInit &&- state.agentLabelsWorkspaceId === scopeId &&- isEqual(state.agentLabels, data)- )- return;-- this.#set(- { agentLabels: data, agentLabelsWorkspaceId: scopeId, isAgentLabelsInit: true },- false,- n('useFetchAgentLabels/onSuccess'),- );- },- },- );- };+ /**+ * Fetch orchestration for every surface that renders labels (sidebar, view-all+ * page, settings). The registry is read through `agentLabelSelectors`, not+ * from this return value; the layout effect inside `useSync` drops the+ * previous scope's registry before paint on a workspace switch.+ */+ useFetchAgentLabels = (isLogin: boolean | undefined): ReplicaSyncResult =>+ this.#labels.useSync(LIST_PARAMS, { enabled: isLogin === true });}export type LabelAction = Pick<LabelActionImpl, keyof LabelActionImpl>;diff --git a/src/store/home/slices/label/initialState.ts b/src/store/home/slices/label/initialState.tsindex b87eb6d055f..ab1b10cd7d7 100644--- a/src/store/home/slices/label/initialState.ts+++ b/src/store/home/slices/label/initialState.ts@@ -1,5 +1,7 @@import { type AgentLabelListItem } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+export interface LabelState {/*** Agent label registry for the current scope (workspace-shared, or@@ -8,13 +10,13 @@ export interface LabelState {*/agentLabels: AgentLabelListItem[];/**- * Workspace the loaded registry belongs to (`null` for personal scope).- * Registries are disjoint per scope, so anything loaded for another- * workspace must count as not-yet-loaded rather than as stale-but-usable:+ * Replica bookkeeping for the registry (the flat `agentLabels` field is its+ * view). The cache scope partitions the registry, so a scope switch counts+ * an already-loaded list as not-yet-loaded rather than as stale-but-usable:* applying a label id from the wrong scope is a destructive write, not a* cosmetic glitch.*/- agentLabelsWorkspaceId: string | null;+ agentLabelsReplica: ReplicaState<AgentLabelListItem[]>;/*** Whether the label list has been initialized*/@@ -23,6 +25,6 @@ export interface LabelState {export const initialLabelState: LabelState = {agentLabels: [],- agentLabelsWorkspaceId: null,+ agentLabelsReplica: createReplicaState(),isAgentLabelsInit: false,};diff --git a/src/store/home/slices/label/projection.ts b/src/store/home/slices/label/projection.tsnew file mode 100644index 00000000000..b30ec854a9d--- /dev/null+++ b/src/store/home/slices/label/projection.ts@@ -0,0 +1,25 @@+import type { AgentLabelListItem } from '@lobechat/types';++import { defineReplica } from '@/libs/replica';++/**+ * The label registry is one entry per cache scope. Labels are+ * workspace-shared, or personal outside a workspace; the registries are+ * disjoint, and the replica scope (`${userId}:${workspaceId}`) is what keeps a+ * switch from serving the previous workspace's labels — a shared key would let+ * a foreign label id be applied to an agent here, which is a destructive write.+ */+export const AGENT_LABELS_KEY = 'registry';++/**+ * Agent label registry for the current scope. Includes archived labels —+ * consumers filter as needed. Read by the sidebar label picker and the+ * workspace labels page; the persisted copy keeps the picker populated instead+ * of flashing empty while the network answers.+ */+export const agentLabelsResource = defineReplica<Record<string, never>, AgentLabelListItem[]>({+ key: () => AGENT_LABELS_KEY,+ name: 'agentLabels',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/home/slices/label/replica.test.ts b/src/store/home/slices/label/replica.test.tsnew file mode 100644index 00000000000..bcb56625eaa--- /dev/null+++ b/src/store/home/slices/label/replica.test.ts@@ -0,0 +1,143 @@+/**+ * @vitest-environment happy-dom+ *+ * The agent-label registry is a `@lobechat/replica` resource whose view is the+ * home store's flat `agentLabels` field: the persisted projection paints while+ * the network confirms it, an unchanged response keeps the array reference, and+ * a cache-scope switch drops the previous workspace's registry before paint —+ * applying a foreign label id to an agent would be a destructive write.+ */+import { randomUUID } from 'node:crypto';++import type { AgentLabelListItem } from '@lobechat/types';+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { agentLabelService } from '@/services/agentLabel';+import { useHomeStore } from '@/store/home';+import { agentLabelSelectors } from '@/store/home/selectors';++import { initialLabelState } from './initialState';+import { agentLabelsResource } from './projection';++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const label = (id: string, overrides: Partial<AgentLabelListItem> = {}): AgentLabelListItem =>+ ({+ archived: false,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id,+ name: id,+ usageCount: 0,+ ...overrides,+ }) as AgentLabelListItem;++/** Never-resolving fetch: what the store holds can only have come from storage. */+const pending = () => new Promise<never>(() => {});++const STORAGE_KEY = agentLabelsResource.storageKey({});++const renderSync = () =>+ renderHook(() => useHomeStore((s) => s.useFetchAgentLabels)(true), { wrapper });++describe('agent label registry replica', () => {+ const scopes = new Set<string>();+ let scope = '';++ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };++ beforeEach(() => {+ useScope(`label-user-${randomUUID()}:personal`);+ useHomeStore.setState({ ...initialLabelState });+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].map((value) =>+ agentLabelsResource.storage!.remove({ queryKey: STORAGE_KEY, scope: value }),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted registry before the network answers', async () => {+ await agentLabelsResource.storage!.set(+ { queryKey: STORAGE_KEY, scope },+ { data: [label('l1', { name: 'Cached' })], updatedAt: 1 },+ );+ vi.spyOn(agentLabelService, 'getLabels').mockImplementation(pending);++ renderSync();++ await waitFor(() => expect(useHomeStore.getState().isAgentLabelsInit).toBe(true));+ expect(agentLabelSelectors.allLabels(useHomeStore.getState())[0].name).toBe('Cached');+ });++ it('keeps the registry reference when the server returns an unchanged list', async () => {+ const getLabels = vi.spyOn(agentLabelService, 'getLabels').mockResolvedValue([label('l1')]);+ renderSync();+ await waitFor(() => expect(useHomeStore.getState().agentLabels).toHaveLength(1));+ const before = useHomeStore.getState().agentLabels;++ getLabels.mockResolvedValue([label('l1')]);+ await act(() => useHomeStore.getState().refreshAgentLabels());++ expect(useHomeStore.getState().agentLabels).toBe(before);+ });++ it('drops the previous scope’s registry on a cache-scope switch', async () => {+ const getLabels = vi+ .spyOn(agentLabelService, 'getLabels')+ .mockResolvedValue([label('l1', { name: 'Personal' })]);+ const { rerender } = renderSync();+ await waitFor(() => expect(useHomeStore.getState().agentLabels).toHaveLength(1));++ // Switch identity: the new scope's registry is still in flight.+ useScope(`${scope.split(':')[0]}:ws-1`);+ getLabels.mockImplementation(pending);+ rerender();++ expect(useHomeStore.getState().agentLabels).toEqual([]);+ expect(agentLabelSelectors.isLabelsInit(useHomeStore.getState())).toBe(false);+ });++ it('refreshes the registry after a label is created', async () => {+ const getLabels = vi.spyOn(agentLabelService, 'getLabels').mockResolvedValue([]);+ vi.spyOn(agentLabelService, 'createLabel').mockResolvedValue('l1');+ renderSync();+ await waitFor(() => expect(useHomeStore.getState().isAgentLabelsInit).toBe(true));++ getLabels.mockResolvedValue([label('l1', { name: 'Fresh' })]);+ await act(() => useHomeStore.getState().createAgentLabel({ name: 'Fresh' }));++ await waitFor(() =>+ expect(agentLabelSelectors.allLabels(useHomeStore.getState())).toHaveLength(1),+ );+ expect(agentLabelSelectors.allLabels(useHomeStore.getState())[0].name).toBe('Fresh');+ });+});