🤯 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(tool): move agent-document skills onto @lobechat/replica (#20571)
Arvin Xu9d023ae0d291
diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.test.ts b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.test.tsnew file mode 100644index 00000000000..5573bee86a5--- /dev/null+++ b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.test.ts@@ -0,0 +1,113 @@+/**+ * @vitest-environment happy-dom+ *+ * Drives the REAL slash menu hook (the ChatInput consumer) against the real+ * tool store and the agent-document skills replica, so the migration is checked+ * at the product seam rather than only in the slice.+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { agentDocumentService } from '@/services/agentDocument';+import { invalidateDocumentMutation } from '@/services/document/invalidation';+import { useAgentStore } from '@/store/agent';+import { useToolStore } from '@/store/tool';++import { useSlashActionItems } from './useSlashActionItems';++vi.mock('@/features/ChatInput/store', () => ({+ useChatInputStore: (selector: (state: { agentId: string; editor: undefined }) => unknown) =>+ selector({ agentId: 'agent-1', editor: undefined }),+}));++vi.mock('@/services/agentDocument', () => ({+ agentDocumentService: { listDocuments: vi.fn() },+}));++const skillDoc = (filename: string, title: string) => ({+ description: null,+ documentId: `doc-${filename}`,+ filename,+ isSkillBundle: true,+ title,+});++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,+ );++/** The agent-skill entries the menu currently offers. */+const agentSkillItems = (items: any[]) =>+ items.filter((item) => item.metadata?.category === 'agentSkill');++describe('useSlashActionItems · agent-document skills', () => {+ const listDocuments = () => vi.mocked(agentDocumentService.listDocuments);++ beforeEach(() => {+ vi.spyOn(cacheScope, 'get').mockImplementation(() => 'use-slash-scope');+ vi.spyOn(cacheScope, 'use').mockImplementation(() => 'use-slash-scope');+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useAgentStore.setState({ activeAgentId: 'agent-1' }));+ listDocuments().mockReset();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('lists the agent’s skill bundles with their display title', async () => {+ listDocuments().mockResolvedValue([skillDoc('release-notes', 'Release notes')] as any);++ const { result } = renderHook(() => useSlashActionItems(), { wrapper });+ await waitFor(() =>+ expect(+ agentSkillItems(useToolStore.getState().agentDocumentSkillsMap['agent-1'] ?? []),+ ).toBeDefined(),+ );+ await waitFor(async () => expect(agentSkillItems(await result.current(null))).toHaveLength(1));++ const [skill] = agentSkillItems(await result.current(null));+ expect(skill).toMatchObject({+ key: 'agent-skill-agent-skills:release-notes',+ label: 'Release notes',+ metadata: { category: 'agentSkill', type: 'agent-skills:release-notes' },+ });+ });++ it('picks up a newly converted skill bundle after a document mutation, without a remount', async () => {+ listDocuments().mockResolvedValue([skillDoc('release-notes', 'Release notes')] as any);++ const { result } = renderHook(() => useSlashActionItems(), { wrapper });+ await waitFor(async () => expect(agentSkillItems(await result.current(null))).toHaveLength(1));++ // The user converts another document into a skill bundle elsewhere in the app.+ listDocuments().mockResolvedValue([+ skillDoc('release-notes', 'Release notes'),+ skillDoc('support-triage', 'Support triage'),+ ] as any);+ await act(() => invalidateDocumentMutation({ agentId: 'agent-1' }));++ await waitFor(async () =>+ expect(agentSkillItems(await result.current(null)).map((item: any) => item.label)).toEqual([+ 'Release notes',+ 'Support triage',+ ]),+ );+ });+});diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.tsindex 27e24adba7b..f79656714c3 100644--- a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts@@ -95,10 +95,11 @@ export const useSlashActionItems = (): SlashOptions['items'] => {const projectSkills = projectSkillsData?.skills;// Agent-document skill bundles (the "Agent skills" group in the working- // sidebar). Share the SWR key with the sidebar fetch so we don't double-fetch.+ // sidebar). The registry is a per-agent replica, so a switch paints the+ // cached bundles at once.useToolStore((s) => s.useFetchAgentDocumentSkills)(agentId);const agentDocumentSkills = useToolStore(- agentDocumentSkillsSelectors.getAgentDocumentSkills,+ agentDocumentSkillsSelectors.getAgentDocumentSkills(agentId),isEqual,);diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsxindex 3cb36f838ba..ce63a02ddc4 100644--- a/src/features/Conversation/ConversationProvider.test.tsx+++ b/src/features/Conversation/ConversationProvider.test.tsx@@ -77,6 +77,11 @@ vi.mock('@/libs/swr', () => ({vi.mock('@/libs/swr/useCacheScope', () => ({getCacheScope: () => 'user-1:personal',+ // `@/services/document/invalidation` (reached through the Portal document+ // hooks) now imports `@/libs/replica`, whose module init builds the SWR-backed+ // replica scope and therefore reads all three helpers.+ isScopeTrusted: () => true,+ useCacheScope: () => 'user-1:personal',}));vi.mock('@/store/agent', () => ({diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.tsindex 92c9e8f3e00..40f92ff4ad2 100644--- a/src/services/document/invalidation.ts+++ b/src/services/document/invalidation.ts@@ -1,5 +1,7 @@+import { revalidateReplica } from '@/libs/replica';import { mutate } from '@/libs/swr';import { portalKeys } from '@/libs/swr/keys';+import { agentDocumentSkillsResource } from '@/store/tool/slices/agentDocumentSkills/projection';import { agentDocumentSWRKeys, documentSWRKeys, notebookSWRKeys } from './swrKeys';@@ -48,13 +50,17 @@ export const invalidateDocumentMutation = async (if (agentId) {revalidations.push(mutate(agentDocumentSWRKeys.documents(agentId)));- // Prefix match so every `agent:documentsList` variant (full list + the- // `non-web` hot-path variant, in both personal and workspace scope where the- // workspace id is appended) revalidates together. The scoped `mutate` passes- // function keys through untouched, so this predicate sees the real cache key.+ // Prefix match so every `agent:documentsList` variant (full list + any+ // hot-path variant, in both personal and workspace scope where the workspace+ // id is appended) revalidates together. The scoped `mutate` passes function+ // keys through untouched, so this predicate sees the real cache key.revalidations.push(mutate((key) => Array.isArray(key) && key[0] === 'agent:documentsList' && key[1] === agentId),);+ // The slash-menu skill registry is a replica, so its sync lives outside the+ // `agent:documentsList` SWR cache. Refresh it here too: a create / delete /+ // convert-to-skill must reach the menu without waiting for a remount.+ revalidations.push(revalidateReplica(agentDocumentSkillsResource, agentId));}if (agentId && agentDocumentId) {diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.tsindex 7d4aae34d02..18ea650bc88 100644--- a/src/services/document/swrKeys.ts+++ b/src/services/document/swrKeys.ts@@ -9,13 +9,6 @@ export const agentDocumentSWRKeys = {* under that key, which drops those fields.*/documentsList: (agentId: string) => ['agent:documentsList', agentId] as const,- /**- * Hot-path variant that excludes unbounded `sourceType: 'web'` clips. Shares- * the `agent:documentsList` prefix so `invalidateDocumentMutation` revalidates- * it (and the full list) together via a prefix matcher. Used by consumers that- * never render web docs (slash menu / skills) so the homepage batch stays slim.- */- documentsNonWebList: (agentId: string) => ['agent:documentsList', agentId, 'non-web'] as const,documentChatTopic: (agentId: string, documentId: string) =>['agent:documentChatTopic', agentId, documentId] as const,readerDocument: (agentId: string, documentId: string) =>diff --git a/src/store/tool/slices/agentDocumentSkills/action.test.ts b/src/store/tool/slices/agentDocumentSkills/action.test.tsnew file mode 100644index 00000000000..d556b59d534--- /dev/null+++ b/src/store/tool/slices/agentDocumentSkills/action.test.ts@@ -0,0 +1,210 @@+/**+ * @vitest-environment happy-dom+ *+ * The agent-document skill registry is a per-agent replica: it paints from the+ * persisted copy on the first frame, the network only confirms, and each agent+ * keeps its own entry so switching never leaks the previous agent's bundles.+ */+import { randomUUID } from 'node:crypto';++import { act, 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 { agentDocumentService } from '@/services/agentDocument';++import { useToolStore } from '../../store';+import { initialAgentDocumentSkillsState } from './initialState';+import { type AgentDocumentSkillItem, agentDocumentSkillsResource } from './projection';+import { agentDocumentSkillsSelectors } from './selectors';++vi.mock('@/services/agentDocument', () => ({+ agentDocumentService: { listDocuments: vi.fn() },+}));++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 doc = (overrides: Record<string, unknown> = {}) =>+ ({+ description: null,+ documentId: 'doc-1',+ filename: 'demo',+ isSkillBundle: true,+ title: 'Demo',+ ...overrides,+ }) as any;++const skill = (+ name: string,+ overrides: Partial<AgentDocumentSkillItem> = {},+): AgentDocumentSkillItem => ({+ documentId: `doc-${name}`,+ identifier: `agent-skills:${name}`,+ name,+ ...overrides,+});++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const AGENT_1 = 'agent-1';+const AGENT_2 = 'agent-2';+const rowKey = (agentId: string) => agentDocumentSkillsResource.storageKey(agentId);++describe('agentDocumentSkills 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);+ };++ const listDocuments = () => vi.mocked(agentDocumentService.listDocuments);+ const skillsFor = (agentId: string) => useToolStore.getState().agentDocumentSkillsMap[agentId];+ const fetchSkills = (agentId: string | undefined) =>+ renderHook(() => useToolStore((s) => s.useFetchAgentDocumentSkills)(agentId), { wrapper });+ const readSkills = (agentId: string | undefined) =>+ renderHook(() => useToolStore(agentDocumentSkillsSelectors.getAgentDocumentSkills(agentId)));+ /**+ * Both agents in ONE tree: each `renderHook` mounts its own `SWRConfig`, so+ * only the last one's cache would receive the globally-scoped `mutate`.+ */+ const fetchBothAgents = () =>+ renderHook(+ () => ({+ one: useToolStore((s) => s.useFetchAgentDocumentSkills)(AGENT_1),+ two: useToolStore((s) => s.useFetchAgentDocumentSkills)(AGENT_2),+ }),+ { wrapper },+ );++ beforeEach(() => {+ useScope(`agent-doc-user-${randomUUID()}:personal`);+ act(() => useToolStore.setState(initialAgentDocumentSkillsState));+ listDocuments().mockReset();+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((value) =>+ [AGENT_1, AGENT_2].map((agentId) =>+ agentDocumentSkillsResource.storage!.remove({ queryKey: rowKey(agentId), scope: value }),+ ),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted bundles before the network answers', async () => {+ await agentDocumentSkillsResource.storage!.set(+ { queryKey: rowKey(AGENT_1), scope },+ { data: [skill('cached', { title: 'Cached' })], updatedAt: 1 },+ );+ listDocuments().mockImplementation(pending);++ const sync = fetchSkills(AGENT_1);+ const items = readSkills(AGENT_1);++ await waitFor(() => expect(items.result.current.map((s) => s.name)).toEqual(['cached']));+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('replaces the persisted copy with the server response and persists it', async () => {+ listDocuments().mockResolvedValue([+ doc({ documentId: 'd1', filename: 'server-skill', title: 'Server skill' }),+ ]);++ fetchSkills(AGENT_1);++ await waitFor(() => expect(skillsFor(AGENT_1)?.map((s) => s.name)).toEqual(['server-skill']));+ await waitFor(async () =>+ expect(+ (await agentDocumentSkillsResource.storage!.get({ queryKey: rowKey(AGENT_1), scope }))+ ?.data,+ ).toEqual([skill('server-skill', { documentId: 'd1', title: 'Server skill' })]),+ );+ });++ it('asks the server for the non-web skill bundles of the selected agent', async () => {+ listDocuments().mockResolvedValue([]);++ fetchSkills(AGENT_1);++ await waitFor(() => expect(listDocuments()).toHaveBeenCalled());+ expect(listDocuments()).toHaveBeenCalledWith({ agentId: AGENT_1, excludeWeb: true });+ });++ it('keeps each agent in its own entry and never leaks across agents', async () => {+ listDocuments().mockImplementation((async ({ agentId }: any) => [+ doc({ documentId: `d-${agentId}`, filename: agentId }),+ ]) as any);++ fetchBothAgents();++ await waitFor(() => expect(skillsFor(AGENT_1)?.map((s) => s.name)).toEqual([AGENT_1]));+ await waitFor(() => expect(skillsFor(AGENT_2)?.map((s) => s.name)).toEqual([AGENT_2]));++ // Neither agent's fetch overwrites the other's entry…+ expect(skillsFor(AGENT_1)?.map((s) => s.name)).toEqual([AGENT_1]);+ expect(skillsFor(AGENT_2)?.map((s) => s.name)).toEqual([AGENT_2]);+ // …and each selector reads only its own agent's bundles.+ expect(readSkills(AGENT_1).result.current.map((s) => s.name)).toEqual([AGENT_1]);+ expect(readSkills(AGENT_2).result.current.map((s) => s.name)).toEqual([AGENT_2]);+ });++ it('claims no entry and hits no network while no agent is selected', () => {+ const sync = fetchSkills(undefined);+ const items = readSkills(undefined);++ expect(sync.result.current.isValidating).toBe(false);+ expect(items.result.current).toEqual([]);+ expect(listDocuments()).not.toHaveBeenCalled();+ });++ it('refreshAgentDocumentSkills re-syncs one agent only', async () => {+ listDocuments().mockResolvedValue([doc({ filename: 'first' })]);+ fetchBothAgents();+ await waitFor(() => expect(skillsFor(AGENT_1)?.map((s) => s.name)).toEqual(['first']));+ await waitFor(() => expect(skillsFor(AGENT_2)?.map((s) => s.name)).toEqual(['first']));++ listDocuments().mockResolvedValue([doc({ filename: 'refreshed' })]);+ await act(() => useToolStore.getState().refreshAgentDocumentSkills(AGENT_1));++ await waitFor(() => expect(skillsFor(AGENT_1)?.map((s) => s.name)).toEqual(['refreshed']));+ // The refreshed agent must not drag the other agent's entry along: had the+ // refresh matched agent-2's sync too, it would now hold 'refreshed' as well.+ expect(skillsFor(AGENT_2)?.map((s) => s.name)).toEqual(['first']);+ });++ it('clearAgentDocumentSkills drops one agent’s cached entry', async () => {+ listDocuments().mockResolvedValue([doc({ filename: 'one' })]);+ fetchSkills(AGENT_1);+ await waitFor(() => expect(skillsFor(AGENT_1)).toBeDefined());++ act(() => useToolStore.getState().clearAgentDocumentSkills(AGENT_1));++ expect(skillsFor(AGENT_1)).toBeUndefined();+ });+});diff --git a/src/store/tool/slices/agentDocumentSkills/action.ts b/src/store/tool/slices/agentDocumentSkills/action.tsindex 74982941781..c0740676e39 100644--- a/src/store/tool/slices/agentDocumentSkills/action.ts+++ b/src/store/tool/slices/agentDocumentSkills/action.ts@@ -1,121 +1,69 @@-import { buildAgentSkillIdentifier } from '@lobechat/const';-import useSWR, { type SWRResponse } from 'swr';--import {- type AgentDocumentListItem,- agentDocumentService,- agentDocumentSWRKeys,-} from '@/services/agentDocument';+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';+import { agentDocumentService } from '@/services/agentDocument';import { type StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';import { type ToolStore } from '../../store';-import { type AgentDocumentSkillItem, type AgentDocumentSkillsState } from './initialState';+import {+ type AgentDocumentSkillItem,+ agentDocumentSkillsResource,+ mapDocsToSkills,+} from './projection';const n = setNamespace('agentDocumentSkills');type Setter = StoreSetter<ToolStore>;-const mapDocsToSkills = (docs: AgentDocumentListItem[]): AgentDocumentSkillItem[] =>- docs- .filter((doc) => doc.isSkillBundle)- .map((doc) => ({- description: doc.description ?? undefined,- documentId: doc.documentId,- identifier: buildAgentSkillIdentifier(doc.filename),- name: doc.filename,- title: doc.title || undefined,- }));-export const createAgentDocumentSkillsSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>new AgentDocumentSkillsActionImpl(set, get, _api);export class AgentDocumentSkillsActionImpl {readonly #get: () => ToolStore;- readonly #set: Setter;+ readonly #skills;constructor(set: Setter, get: () => ToolStore, _api?: unknown) {void _api;- this.#set = set;this.#get = get;+ this.#skills = createReplicaSlice(agentDocumentSkillsResource, {+ actionPrefix: n('agentDocumentSkills'),+ // The slash menu never renders web-clip docs, so the hot-path list drops+ // the unbounded `sourceType: 'web'` rows the full document list carries.+ fetcher: (agentId) => agentDocumentService.listDocuments({ agentId, excludeWeb: true }),+ get,+ merge: (docs) => mapDocsToSkills(docs),+ set,+ stateKey: 'agentDocumentSkillsReplica',+ view: recordLens<ToolStore, AgentDocumentSkillItem[]>('agentDocumentSkillsMap'),+ });}/**- * Load (or refresh) the agent-document skill bundles for the given agent and- * publish them to the tool store registry. Cleared first when switching- * agents so consumers never see stale items from the previous agent.+ * Force a fresh sync of one agent's skill bundles (or every loaded agent).+ * The view is read through `agentDocumentSkillsSelectors`; this only schedules+ * the network round-trip, so the caller never touches the replica directly.*/- refreshAgentDocumentSkills = async (agentId: string): Promise<void> => {- const previousAgentId = this.#get().agentDocumentSkillsAgentId;- if (previousAgentId && previousAgentId !== agentId) {- this.#set(- { agentDocumentSkills: [], agentDocumentSkillsAgentId: agentId },- false,- n('switchAgent'),- );- } else if (!previousAgentId) {- this.#set({ agentDocumentSkillsAgentId: agentId }, false, n('initAgent'));- }-- try {- const docs = await agentDocumentService.listDocuments({ agentId, excludeWeb: true });- const items = mapDocsToSkills(docs);- this.#set(- { agentDocumentSkills: items, agentDocumentSkillsAgentId: agentId },- false,- n('refreshAgentDocumentSkills'),- );- } catch (error) {- // Surface registry as empty on failure rather than throwing — slash menu- // and drag chips degrade gracefully (just nothing to drag) instead of- // crashing the working sidebar.-- console.warn('[agentDocumentSkills] failed to refresh:', error);- this.#set(- { agentDocumentSkills: [] } satisfies Partial<AgentDocumentSkillsState>,- false,- n('refreshAgentDocumentSkillsError'),- );- }+ refreshAgentDocumentSkills = async (agentId?: string): Promise<void> => {+ await this.#skills.revalidate(agentId);};- clearAgentDocumentSkills = (): void => {- this.#set(- { agentDocumentSkills: [], agentDocumentSkillsAgentId: undefined },- false,- n('clearAgentDocumentSkills'),- );+ /**+ * Drop an agent's cached bundles (or every loaded agent's) from memory and+ * storage. Agents are isolated by key, so switching agents never needs this;+ * it is for explicit invalidation (e.g. releasing a signed-out identity).+ */+ clearAgentDocumentSkills = (agentId?: string): void => {+ const keys = agentId ? [agentId] : Object.keys(this.#get().agentDocumentSkillsMap);+ for (const key of keys) this.#skills.remove(key);};/**- * SWR-backed hook that fetches the agent's skill bundles and keeps the store- * in sync. Fetches the `non-web` variant (drops the unbounded web-clip docs it- * never needs) so this eager, always-mounted slash-menu hook doesn't pull the- * full document list into the homepage batch. The working-sidebar panel keeps- * its own full-list fetch; both revalidate together via the shared- * `agent:documentsList` prefix (see `invalidateDocumentMutation`).+ * Fetch orchestration for the slash menu: one replica entry per agent, so an+ * agent switch paints the cached bundles immediately and the network only+ * confirms. Read the items with `agentDocumentSkillsSelectors`, not from the+ * return value.*/- useFetchAgentDocumentSkills = (- agentId: string | undefined,- ): SWRResponse<AgentDocumentListItem[]> =>- useSWR<AgentDocumentListItem[]>(- agentId ? agentDocumentSWRKeys.documentsNonWebList(agentId) : null,- async () => agentDocumentService.listDocuments({ agentId: agentId!, excludeWeb: true }),- {- onSuccess: (docs) => {- if (!agentId) return;- this.#set(- {- agentDocumentSkills: mapDocsToSkills(docs),- agentDocumentSkillsAgentId: agentId,- },- false,- n('useFetchAgentDocumentSkills'),- );- },- revalidateOnFocus: false,- },- );+ useFetchAgentDocumentSkills = (agentId: string | undefined): ReplicaSyncResult =>+ this.#skills.useSync(agentId ?? null, { revalidateOnFocus: false });}export type AgentDocumentSkillsAction = Pick<diff --git a/src/store/tool/slices/agentDocumentSkills/documentInvalidation.test.ts b/src/store/tool/slices/agentDocumentSkills/documentInvalidation.test.tsnew file mode 100644index 00000000000..05ccf4a18a3--- /dev/null+++ b/src/store/tool/slices/agentDocumentSkills/documentInvalidation.test.ts@@ -0,0 +1,51 @@+/**+ * Guards the migration's cross-layer wiring: an agent-document write must+ * revalidate the slash-menu skill registry, which now lives in a replica+ * (`replica:sync` keys) instead of the `agent:documentsList` SWR entry.+ */+import { describe, expect, it, vi } from 'vitest';++import { invalidateDocumentMutation } from '@/services/document/invalidation';++vi.mock('@/libs/swr', () => ({ mutate: vi.fn() }));++const functionKeys = async () => {+ const { mutate } = await import('@/libs/swr');+ return vi+ .mocked(mutate)+ .mock.calls.map(([key]) => key)+ .filter((key): key is (queryKey: unknown) => boolean => typeof key === 'function');+};++describe('agentDocumentSkills invalidation wiring', () => {+ it('revalidates the skill registry replica for the mutated agent only', async () => {+ const { cacheScope } = await import('@/libs/replica');+ const scope = cacheScope.get();++ await invalidateDocumentMutation({ agentId: 'agent-1' });++ const matchers = await functionKeys();+ const matches = (key: unknown) => matchers.some((matcher) => matcher(key));++ expect(matches(['replica:sync', 'agentDocumentSkills', 1, scope, 'agent-1', 'agent-1'])).toBe(+ true,+ );+ expect(matches(['replica:sync', 'agentDocumentSkills', 1, scope, 'agent-2', 'agent-2'])).toBe(+ false,+ );+ });++ it('does not touch the skill registry when no agent is involved', async () => {+ await invalidateDocumentMutation({ documentId: 'page-doc-1' });++ const matchers = await functionKeys();+ const { cacheScope } = await import('@/libs/replica');+ const scope = cacheScope.get();++ expect(+ matchers.some((matcher) =>+ matcher(['replica:sync', 'agentDocumentSkills', 1, scope, 'agent-1', 'agent-1']),+ ),+ ).toBe(false);+ });+});diff --git a/src/store/tool/slices/agentDocumentSkills/index.ts b/src/store/tool/slices/agentDocumentSkills/index.tsindex 55b4d68b202..3e1cf229bf6 100644--- a/src/store/tool/slices/agentDocumentSkills/index.ts+++ b/src/store/tool/slices/agentDocumentSkills/index.ts@@ -1,7 +1,8 @@export { type AgentDocumentSkillsAction, createAgentDocumentSkillsSlice } from './action';+export { type AgentDocumentSkillsState, initialAgentDocumentSkillsState } from './initialState';export {type AgentDocumentSkillItem,- type AgentDocumentSkillsState,- initialAgentDocumentSkillsState,-} from './initialState';+ agentDocumentSkillsResource,+ mapDocsToSkills,+} from './projection';export { agentDocumentSkillsSelectors } from './selectors';diff --git a/src/store/tool/slices/agentDocumentSkills/initialState.ts b/src/store/tool/slices/agentDocumentSkills/initialState.tsindex e28bb58277b..1635f04d274 100644--- a/src/store/tool/slices/agentDocumentSkills/initialState.ts+++ b/src/store/tool/slices/agentDocumentSkills/initialState.ts@@ -1,31 +1,21 @@-/**- * Lightweight registry entry for an agent-document skill bundle (the "Agent Skills"- * group, sourced from the `agent_document` table).- *- * Distinct from the user/market `SkillListItem` shape because these skills are- * per-agent and don't carry a full `SkillManifest`. The slash menu, drag chip,- * and runtime activation all key off `identifier` — the prefix lets the server- * resolver tell them apart from builtin/DB skills.- */-export interface AgentDocumentSkillItem {- description?: string;- documentId: string;- /** `agent-document:<filename>` — matches the server-side runtime identifier. */- identifier: string;- /** Bundle filename (slug). */- name: string;- /** Human-readable display title; falls back to `name`. */- title?: string;-}+import { createReplicaState, type ReplicaState } from '@/libs/replica';++import type { AgentDocumentSkillItem } from './projection';++export type { AgentDocumentSkillItem } from './projection';export interface AgentDocumentSkillsState {- /** Skills belonging to the currently-active agent; cleared on agent switch. */- agentDocumentSkills: AgentDocumentSkillItem[];- /** The agent id the current `agentDocumentSkills` snapshot belongs to. */- agentDocumentSkillsAgentId: string | undefined;+ /**+ * Skill bundles per agent, keyed by `agentId`. Each agent is its own replica+ * entry, so switching agents paints the cached bundles at once and never+ * leaks the previous agent's items.+ */+ agentDocumentSkillsMap: Record<string, AgentDocumentSkillItem[]>;+ /** Replica bookkeeping for `agentDocumentSkillsMap`. */+ agentDocumentSkillsReplica: ReplicaState<AgentDocumentSkillItem[]>;}export const initialAgentDocumentSkillsState: AgentDocumentSkillsState = {- agentDocumentSkills: [],- agentDocumentSkillsAgentId: undefined,+ agentDocumentSkillsMap: {},+ agentDocumentSkillsReplica: createReplicaState(),};diff --git a/src/store/tool/slices/agentDocumentSkills/projection.test.ts b/src/store/tool/slices/agentDocumentSkills/projection.test.tsnew file mode 100644index 00000000000..2524411f6aa--- /dev/null+++ b/src/store/tool/slices/agentDocumentSkills/projection.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';++import { mapDocsToSkills } from './projection';++const doc = (overrides: Record<string, unknown> = {}) =>+ ({+ description: null,+ documentId: 'doc-1',+ filename: 'demo',+ isSkillBundle: true,+ title: 'Demo',+ ...overrides,+ }) as any;++describe('mapDocsToSkills', () => {+ it('keeps only the skill bundles', () => {+ const mapped = mapDocsToSkills([+ doc({ documentId: 'd1', filename: 'one', isSkillBundle: true }),+ doc({ documentId: 'd2', filename: 'clip', isSkillBundle: false }),+ ]);++ expect(mapped.map((s) => s.name)).toEqual(['one']);+ });++ it('builds the identifier from the filename and keeps title / description', () => {+ const mapped = mapDocsToSkills([+ doc({+ description: 'Does a thing',+ documentId: 'd9',+ filename: 'release-notes',+ title: 'Release notes',+ }),+ ]);++ expect(mapped).toEqual([+ {+ description: 'Does a thing',+ documentId: 'd9',+ identifier: 'agent-skills:release-notes',+ name: 'release-notes',+ title: 'Release notes',+ },+ ]);+ });++ it('omits empty description / title so the UI falls back to the filename', () => {+ const [skill] = mapDocsToSkills([doc({ description: null, filename: 'bare', title: '' })]);++ expect(skill.description).toBeUndefined();+ expect(skill.title).toBeUndefined();+ expect(skill.name).toBe('bare');+ });++ it('returns an empty registry for an empty or all-non-skill list', () => {+ expect(mapDocsToSkills([])).toEqual([]);+ expect(mapDocsToSkills([doc({ isSkillBundle: false })])).toEqual([]);+ });+});diff --git a/src/store/tool/slices/agentDocumentSkills/projection.ts b/src/store/tool/slices/agentDocumentSkills/projection.tsnew file mode 100644index 00000000000..28d16e8e436--- /dev/null+++ b/src/store/tool/slices/agentDocumentSkills/projection.ts@@ -0,0 +1,62 @@+import { buildAgentSkillIdentifier } from '@lobechat/const';++import { defineReplica } from '@/libs/replica';+import type { agentDocumentService } from '@/services/agentDocument';++type AgentDocumentListResponse = Awaited<ReturnType<typeof agentDocumentService.listDocuments>>;+export type AgentDocumentListItem = AgentDocumentListResponse[number];++/**+ * Lightweight registry entry for an agent-document skill bundle (the "Agent Skills"+ * group, sourced from the `agent_document` table).+ *+ * Distinct from the user/market `SkillListItem` shape because these skills are+ * per-agent and don't carry a full `SkillManifest`. The slash menu, drag chip,+ * and runtime activation all key off `identifier` — the prefix lets the server+ * resolver tell them apart from builtin/DB skills.+ */+export interface AgentDocumentSkillItem {+ description?: string;+ documentId: string;+ /** `agent-skills:<filename>` — matches the server-side runtime identifier. */+ identifier: string;+ /** Bundle filename (slug). */+ name: string;+ /** Human-readable display title; falls back to `name`. */+ title?: string;+}++/**+ * Keep only the skill bundles and shape them into the registry entries the UI+ * keys off. The raw document list carries every agent document (including web+ * clips), so this is also the filter that keeps the registry to skills.+ */+export const mapDocsToSkills = (docs: AgentDocumentListItem[]): AgentDocumentSkillItem[] =>+ docs+ .filter((doc) => doc.isSkillBundle)+ .map((doc) => ({+ description: doc.description ?? undefined,+ documentId: doc.documentId,+ identifier: buildAgentSkillIdentifier(doc.filename),+ name: doc.filename,+ title: doc.title || undefined,+ }));++/**+ * One agent's skill bundles, keyed by `agentId` (`agentDocumentSkillsMap[agentId]`).+ *+ * Read-mostly: the registry is refreshed from `agentDocument` mutations (see+ * `invalidateDocumentMutation`), so the persisted copy paints the first frame+ * and the network only confirms. IndexedDB, not localStorage, because the list+ * is only read once a chat is open.+ */+export const agentDocumentSkillsResource = defineReplica<+ string,+ AgentDocumentSkillItem[],+ AgentDocumentListResponse+>({+ key: (agentId) => agentId,+ name: 'agentDocumentSkills',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/tool/slices/agentDocumentSkills/selectors.ts b/src/store/tool/slices/agentDocumentSkills/selectors.tsindex 2c58faecc7c..92c6a868a5a 100644--- a/src/store/tool/slices/agentDocumentSkills/selectors.ts+++ b/src/store/tool/slices/agentDocumentSkills/selectors.ts@@ -1,13 +1,18 @@import type { ToolStoreState } from '../../initialState';-import type { AgentDocumentSkillItem } from './initialState';+import type { AgentDocumentSkillItem } from './projection';-const getAgentDocumentSkills = (s: ToolStoreState): AgentDocumentSkillItem[] =>- s.agentDocumentSkills || [];+const EMPTY_AGENT_DOCUMENT_SKILLS: AgentDocumentSkillItem[] = [];++/** The agent's skill bundles as its replica entry holds them. */+const getAgentDocumentSkills =+ (agentId: string | undefined) =>+ (s: ToolStoreState): AgentDocumentSkillItem[] =>+ (agentId ? s.agentDocumentSkillsMap[agentId] : undefined) ?? EMPTY_AGENT_DOCUMENT_SKILLS;const getAgentDocumentSkillByIdentifier =- (identifier: string) =>+ (agentId: string | undefined, identifier: string) =>(s: ToolStoreState): AgentDocumentSkillItem | undefined =>- (s.agentDocumentSkills || []).find((skill) => skill.identifier === identifier);+ getAgentDocumentSkills(agentId)(s).find((skill) => skill.identifier === identifier);export const agentDocumentSkillsSelectors = {getAgentDocumentSkillByIdentifier,