🤯 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(skill): move the agent skills list and detail onto @lobechat/replica (#20570)
Arvin Xu647c58ab4d11
diff --git a/src/features/Settings/skill/features/SkillDetail/index.test.tsx b/src/features/Settings/skill/features/SkillDetail/index.test.tsxindex cb88b9b391b..60ef4d772f7 100644--- a/src/features/Settings/skill/features/SkillDetail/index.test.tsx+++ b/src/features/Settings/skill/features/SkillDetail/index.test.tsx@@ -12,6 +12,10 @@ import SkillDetail from './index';const mocks = vi.hoisted(() => {const toolState = {+ agentSkillListMap: {} as Record<+ string,+ Array<{ id: string; identifier: string; userId?: string }>+ >,builtinSkills: [],checkLobehubSkillStatus: vi.fn(),composioServers: [] as Array<{ identifier: string; status: string }>,@@ -139,6 +143,9 @@ vi.mock('@/store/tool', () => ({}));vi.mock('@/store/tool/selectors', () => ({+ agentSkillsSelectors: {+ getAgentSkills: (state: typeof mocks.toolState) => state.agentSkillListMap.all || [],+ },builtinToolSelectors: {isBuiltinToolInstalled:(identifier: string) =>diff --git a/src/features/Settings/skill/features/SkillDetail/index.tsx b/src/features/Settings/skill/features/SkillDetail/index.tsxindex 0c705aff42e..fcaf5e4d8e1 100644--- a/src/features/Settings/skill/features/SkillDetail/index.tsx+++ b/src/features/Settings/skill/features/SkillDetail/index.tsx@@ -17,7 +17,11 @@ import { useSkillConnect } from '@/features/SkillStore/SkillList/LobeHub/useSkilimport { usePermission } from '@/hooks/usePermission';import { useResourceManageable } from '@/hooks/useResourceManageable';import { useToolStore } from '@/store/tool';-import { builtinToolSelectors, lobehubSkillStoreSelectors } from '@/store/tool/selectors';+import {+ agentSkillsSelectors,+ builtinToolSelectors,+ lobehubSkillStoreSelectors,+} from '@/store/tool/selectors';import { loadBuiltinSkill } from '@/store/tool/slices/builtin/loadBuiltinSkills';import { connectorSelectors } from '@/store/tool/slices/connector';import { pluginSelectors } from '@/store/tool/slices/plugin/selectors';@@ -203,7 +207,10 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {// Creator attribution for the row-level manage gate: agent skills carry it// on the skill row; connector-backed types on the connector row.const agentSkillRow = useToolStore(- (s) => (s.agentSkills || []).find((sk) => sk.id === identifier || sk.identifier === identifier),+ (s) =>+ agentSkillsSelectors+ .getAgentSkills(s)+ .find((sk) => sk.id === identifier || sk.identifier === identifier),isEqual,);const canManage = useResourceManageable(diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 41aea39a340..bd0ef879bf0 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -897,8 +897,6 @@ export const userMemoryKeys = {// ---- tool (skills / plugins / builtin / mcp / composio stores) -------------export const toolKeys = {- agentSkillDetail: def('tool:agentSkillDetail', (id: string) => ['tool:agentSkillDetail', id]),- agentSkills: def('tool:agentSkills', () => ['tool:agentSkills']),composioAppTools: def('tool:composioAppTools', (appSlug: string) => ['tool:composioAppTools',appSlug,diff --git a/src/services/chat/mecha/skillEngineering.test.ts b/src/services/chat/mecha/skillEngineering.test.tsindex cd1c302cd12..3309498c382 100644--- a/src/services/chat/mecha/skillEngineering.test.ts+++ b/src/services/chat/mecha/skillEngineering.test.ts@@ -27,12 +27,23 @@ vi.mock('@/helpers/toolAvailability', () => ({const mockedGetToolStoreState = vi.mocked(getToolStoreState);const mockedGetById = vi.mocked(agentSkillService.getById);+/**+ * The skills list and the loaded detail are replica views: the list lives in+ * `agentSkillListMap[AGENT_SKILL_LIST_KEY]` and each detail entry wraps the+ * skill (`{ resourceTree, skillDetail }`).+ */const setToolState = (state: any) => {+ const { agentSkillDetailMap = {}, agentSkills = [], ...rest } = state;mockedGetToolStoreState.mockReturnValue({- agentSkillDetailMap: {},- agentSkills: [],+ agentSkillDetailMap: Object.fromEntries(+ Object.entries(agentSkillDetailMap).map(([id, skillDetail]) => [+ id,+ { resourceTree: [], skillDetail },+ ]),+ ),+ agentSkillListMap: { all: agentSkills },builtinSkills: [],- ...state,+ ...rest,} as any);};diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.tsindex a3a1a4a95a4..6733c4530f4 100644--- a/src/services/chat/mecha/skillEngineering.ts+++ b/src/services/chat/mecha/skillEngineering.ts@@ -7,6 +7,7 @@ import debug from 'debug';import { agentSkillService } from '@/services/skill';import { getToolStoreState } from '@/store/tool';+import { agentSkillsSelectors } from '@/store/tool/slices/agentSkills/selectors';import { loadBuiltinSkills } from '@/store/tool/slices/builtin/loadBuiltinSkills';const log = debug('context-engine:resolveClientSkills');@@ -29,7 +30,7 @@ const buildDbSkillContent = (detail: SkillItem): string | undefined => {** Sources:* 1. Builtin skills (e.g., Artifacts) - from toolStore.builtinSkills- * 2. DB skills (user/market) - from toolStore.agentSkills+ * 2. DB skills (user/market) - from the `agentSkillList` replica** Pinned skills (ids in `pluginIds`) carry their full `content` so the* SkillContextProvider can inject it directly into the system prompt instead of@@ -66,7 +67,8 @@ export const resolveClientSkills = async (}));const dbMetas = await Promise.all(- (toolState.agentSkills || [])+ agentSkillsSelectors+ .getAgentSkills(toolState).filter((s) => !disabledIdSet.has(s.identifier)).map(async (s) => {const meta = {@@ -89,7 +91,8 @@ export const resolveClientSkills = async (try {const detail =- toolState.agentSkillDetailMap?.[s.id] ?? (await agentSkillService.getById(s.id));+ agentSkillsSelectors.getAgentSkillDetail(s.id)(toolState) ??+ (await agentSkillService.getById(s.id));const content = detail && buildDbSkillContent(detail);// Mark activated only when content is available, otherwise the skill would// be excluded from both the activated and the <available_skills> lists.diff --git a/src/services/chat/mecha/skillPreload.ts b/src/services/chat/mecha/skillPreload.tsindex 5fce786d7db..c224830006f 100644--- a/src/services/chat/mecha/skillPreload.ts+++ b/src/services/chat/mecha/skillPreload.ts@@ -9,6 +9,7 @@ import type { RuntimeSelectedSkill, UserCredSummary } from '@lobechat/types';import { agentSkillService } from '@/services/skill';import { getToolStoreState } from '@/store/tool';+import { agentSkillsSelectors } from '@/store/tool/slices/agentSkills/selectors';import { loadBuiltinSkill } from '@/store/tool/slices/builtin/loadBuiltinSkills';interface PreloadedSkill {@@ -116,12 +117,12 @@ const loadSkillContent = async (};}- const listItem = (toolState.agentSkills || []).find(- (skill) => skill.identifier === selectedSkill.identifier,- );+ const listItem = agentSkillsSelectors+ .getAgentSkills(toolState)+ .find((skill) => skill.identifier === selectedSkill.identifier);const detail =- (listItem && toolState.agentSkillDetailMap?.[listItem.id]) ||+ (listItem && agentSkillsSelectors.getAgentSkillDetail(listItem.id)(toolState)) ||(listItem ? await agentSkillService.getById(listItem.id) : undefined) ||(await agentSkillService.getByIdentifier(selectedSkill.identifier));diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.tsindex dbcd4c13710..a1e7d77656c 100644--- a/src/store/tool/selectors/tool.ts+++ b/src/store/tool/selectors/tool.ts@@ -10,6 +10,7 @@ import { type MetaData } from '@/types/meta';import { type LobeToolMeta } from '@/types/tool/tool';import { type ToolStoreState } from '../initialState';+import { agentSkillsSelectors } from '../slices/agentSkills/selectors';import { builtinToolSelectors } from '../slices/builtin/selectors';import { ComposioServerStatus } from '../slices/composioStore';import { lobehubSkillStoreSelectors } from '../slices/lobehubSkillStore';@@ -132,7 +133,9 @@ export interface AvailableToolForDiscovery {const availableToolsForDiscovery = (s: ToolStoreState): AvailableToolForDiscovery[] => {// Build exclusion sets for deduplicationconst builtinSkillIds = new Set((s.builtinSkills || []).map((skill) => skill.identifier));- const agentSkillIds = new Set((s.agentSkills || []).map((skill) => skill.identifier));+ const agentSkillIds = new Set(+ agentSkillsSelectors.getAgentSkills(s).map((skill) => skill.identifier),+ );const composioIds = new Set((s.composioServers || []).map((server) => server.identifier));const lobehubSkillIds = new Set((s.lobehubSkillServers || []).map((server) => server.identifier));diff --git a/src/store/tool/slices/agentSkills/action.test.ts b/src/store/tool/slices/agentSkills/action.test.tsnew file mode 100644index 00000000000..30fe1583352--- /dev/null+++ b/src/store/tool/slices/agentSkills/action.test.ts@@ -0,0 +1,321 @@+/**+ * @vitest-environment happy-dom+ *+ * The installed skills list and the loaded skill details are replicas: they+ * paint from the persisted copy on the first frame, the network only confirms,+ * a rename or delete reaches the list row and the loaded detail at once, and a+ * scope switch drops the previous identity's rows before the next paints.+ */+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 { agentSkillService } from '@/services/skill';++import { useToolStore } from '../../store';+import { initialAgentSkillsState } from './initialState';+import {+ AGENT_SKILL_LIST_KEY,+ type AgentSkillDetail,+ agentSkillDetailResource,+ type AgentSkillListItem,+ agentSkillListResource,+} from './projection';++vi.mock('@/services/skill', () => ({+ agentSkillService: {+ createSkill: vi.fn(),+ deleteSkill: vi.fn(),+ getById: vi.fn(),+ importFromGitHub: vi.fn(),+ importFromUrl: vi.fn(),+ importFromZip: vi.fn(),+ list: vi.fn(),+ listResources: vi.fn(),+ updateSkill: 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 skill = (id: string, name = id): AgentSkillListItem =>+ ({ id, identifier: id, name }) as AgentSkillListItem;++const detailOf = (item: AgentSkillListItem): AgentSkillDetail => ({+ resourceTree: [{ name: 'SKILL.md', path: 'SKILL.md', type: 'file' }],+ skillDetail: { ...item, content: '# body' } as any,+});++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const LIST_STORAGE_KEY = agentSkillListResource.storageKey({});++describe('agentSkills replicas', () => {+ 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(`skill-user-${randomUUID()}:personal`);+ act(() => useToolStore.setState(initialAgentSkillsState));+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((value) => [+ agentSkillListResource.storage!.remove({ queryKey: LIST_STORAGE_KEY, scope: value }),+ agentSkillDetailResource.storage!.remove({ queryKey: 'db-1', scope: value }),+ agentSkillDetailResource.storage!.remove({ queryKey: 'missing', scope: value }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted list before the network answers', async () => {+ await agentSkillListResource.storage!.set(+ { queryKey: LIST_STORAGE_KEY, scope },+ { data: [skill('db-1', 'Cached')], updatedAt: 1 },+ );+ vi.mocked(agentSkillService.list).mockImplementation(pending);++ const sync = renderHook(() => useToolStore((s) => s.useFetchAgentSkills)(true), { wrapper });++ await waitFor(() =>+ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]?.[0]?.name).toBe(+ 'Cached',+ ),+ );+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('replaces the list with the server response and persists it', async () => {+ vi.mocked(agentSkillService.list).mockResolvedValue({+ data: [skill('db-1', 'Server')],+ total: 1,+ });++ renderHook(() => useToolStore((s) => s.useFetchAgentSkills)(true), { wrapper });++ await waitFor(() =>+ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]?.[0]?.name).toBe(+ 'Server',+ ),+ );+ await waitFor(async () =>+ expect(+ (await agentSkillListResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope }))?.data,+ ).toEqual([skill('db-1', 'Server')]),+ );+ });++ it('paints a skill detail page (skill + resource tree) from the persisted copy', async () => {+ await agentSkillDetailResource.storage!.set(+ { queryKey: 'db-1', scope },+ { data: detailOf(skill('db-1', 'Cached page')), updatedAt: 1 },+ );+ vi.mocked(agentSkillService.getById).mockImplementation(pending);+ vi.mocked(agentSkillService.listResources).mockImplementation(pending);++ const sync = renderHook(() => useToolStore((s) => s.useFetchAgentSkillDetail)('db-1'), {+ wrapper,+ });++ await waitFor(() =>+ expect(useToolStore.getState().agentSkillDetailMap['db-1']?.skillDetail?.name).toBe(+ 'Cached page',+ ),+ );+ expect(sync.result.current.data?.resourceTree).toHaveLength(1);+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('keeps a not-found detail as an empty value instead of failing the surface', async () => {+ vi.mocked(agentSkillService.list).mockResolvedValue({ data: [], total: 0 });+ vi.mocked(agentSkillService.getById).mockResolvedValue(undefined);+ vi.mocked(agentSkillService.listResources).mockResolvedValue([]);++ renderHook(() => useToolStore((s) => s.useFetchAgentSkillDetail)('missing'), { wrapper });++ await waitFor(() =>+ expect(useToolStore.getState().agentSkillDetailMap['missing']).toBeDefined(),+ );+ expect(useToolStore.getState().agentSkillDetailMap['missing'].skillDetail).toBeUndefined();+ expect(useToolStore.getState().agentSkillDetailMap['missing'].resourceTree).toEqual([]);+ });++ it('drops the previous identity’s skills before the next one paints', async () => {+ vi.mocked(agentSkillService.list).mockResolvedValue({+ data: [skill('db-1', 'Mine')],+ total: 1,+ });+ const sync = renderHook(() => useToolStore((s) => s.useFetchAgentSkills)(true), { wrapper });+ await waitFor(() =>+ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]).toHaveLength(1),+ );++ vi.mocked(agentSkillService.list).mockImplementation(pending);+ useScope(`skill-user-${randomUUID()}:personal`);+ sync.rerender();++ await waitFor(() =>+ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]).toBeUndefined(),+ );+ });++ describe('mutations', () => {+ const seed = async () => {+ vi.mocked(agentSkillService.list).mockResolvedValue({+ data: [skill('db-1', 'Original'), skill('db-2')],+ total: 2,+ });+ vi.mocked(agentSkillService.getById).mockResolvedValue({+ content: 'body',+ id: 'db-1',+ identifier: 'db-1',+ name: 'Original',+ } as any);+ vi.mocked(agentSkillService.listResources).mockResolvedValue([+ { name: 'SKILL.md', path: 'SKILL.md', type: 'file' },+ ]);+ renderHook(+ () => {+ useToolStore((s) => s.useFetchAgentSkills)(true);+ useToolStore((s) => s.useFetchAgentSkillDetail)('db-1');+ },+ { wrapper },+ );+ await waitFor(() => {+ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]).toHaveLength(2);+ expect(useToolStore.getState().agentSkillDetailMap['db-1']).toBeDefined();+ });+ };++ it('renames the list row and the loaded detail optimistically', async () => {+ await seed();+ let resolveUpdate!: (value: unknown) => void;+ vi.mocked(agentSkillService.updateSkill).mockImplementation(+ () => new Promise((resolve) => (resolveUpdate = resolve)) as any,+ );++ const operation = useToolStore.getState().updateAgentSkill({ id: 'db-1', name: 'Renamed' });++ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY][0].name).toBe(+ 'Renamed',+ );+ expect(useToolStore.getState().agentSkillDetailMap['db-1'].skillDetail?.name).toBe('Renamed');++ const renamed = {+ content: 'body',+ id: 'db-1',+ identifier: 'db-1',+ name: 'Renamed',+ updatedAt: 'server',+ };+ // The refresh that follows the rename sees the server's new state.+ vi.mocked(agentSkillService.list).mockResolvedValue({+ data: [skill('db-1', 'Renamed'), skill('db-2')],+ total: 2,+ });+ await act(async () => {+ resolveUpdate(renamed);+ await operation;+ });+ expect(useToolStore.getState().agentSkillDetailMap['db-1'].skillDetail?.updatedAt).toBe(+ 'server',+ );+ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY][0].name).toBe(+ 'Renamed',+ );+ });++ it('rolls both copies back when the rename fails', async () => {+ await seed();+ vi.mocked(agentSkillService.updateSkill).mockRejectedValue(new Error('boom'));++ await expect(+ useToolStore.getState().updateAgentSkill({ id: 'db-1', name: 'Renamed' }),+ ).rejects.toThrow('boom');++ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY][0].name).toBe(+ 'Original',+ );+ expect(useToolStore.getState().agentSkillDetailMap['db-1'].skillDetail?.name).toBe(+ 'Original',+ );+ });++ it('removes a deleted skill from the list and its detail', async () => {+ await seed();+ vi.mocked(agentSkillService.deleteSkill).mockResolvedValue({ success: true });+ vi.mocked(agentSkillService.list).mockResolvedValue({ data: [skill('db-2')], total: 1 });++ await act(() => useToolStore.getState().deleteAgentSkill('db-1'));++ expect(+ useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY].map((item) => item.id),+ ).toEqual(['db-2']);+ expect(useToolStore.getState().agentSkillDetailMap['db-1']).toBeUndefined();+ });++ it('populates the store from a refresh even without a mounted list hook', async () => {+ // Mirrors the create-agent modal flow: no list hook is mounted, yet+ // `refreshAgentSkills` must populate the store for the selectors.+ vi.mocked(agentSkillService.list).mockResolvedValue({+ data: [skill('db-9', 'Imported')],+ total: 1,+ });++ await act(() => useToolStore.getState().refreshAgentSkills());++ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]?.[0]?.id).toBe('db-9');+ });++ it('drops a refresh response that resolves after the scope switched', async () => {+ let resolveList!: (value: unknown) => void;+ vi.mocked(agentSkillService.list).mockImplementation(+ () => new Promise((resolve) => (resolveList = resolve)) as any,+ );++ const operation = useToolStore.getState().refreshAgentSkills();++ // The identity switches before the in-flight request resolves: the+ // response belongs to the previous scope and must not be written (or+ // persisted) into the next scope's partition.+ useScope(`skill-user-${randomUUID()}:personal`);+ await act(async () => {+ resolveList({ data: [skill('db-1', 'A workspace')], total: 1 });+ await operation;+ });++ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]).toBeUndefined();+ });+ });+});diff --git a/src/store/tool/slices/agentSkills/action.ts b/src/store/tool/slices/agentSkills/action.tsindex 71f27a8984c..2b4c95c2240 100644--- a/src/store/tool/slices/agentSkills/action.ts+++ b/src/store/tool/slices/agentSkills/action.ts@@ -1,31 +1,53 @@-import {- type CreateSkillInput,- type ImportGitHubInput,- type ImportUrlInput,- type ImportZipInput,- type SkillImportResult,- type SkillItem,- type SkillListItem,- type SkillResourceTreeNode,- type UpdateSkillInput,+import type {+ CreateSkillInput,+ ImportGitHubInput,+ ImportUrlInput,+ ImportZipInput,+ SkillImportResult,+ UpdateSkillInput,} from '@lobechat/types';-import { produce } from 'immer';-import useSWR, { mutate, type SWRResponse } from 'swr';-import { useClientDataSWR } from '@/libs/swr';-import { toolKeys } from '@/libs/swr/keys';+import {+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ type ReplicaSyncResult,+} from '@/libs/replica';import { agentSkillService } from '@/services/skill';-import { type StoreSetter } from '@/store/types';-import { setNamespace } from '@/utils/storeDebug';+import type { StoreSetter } from '@/store/types';-import { type ToolStore } from '../../store';-import { type AgentSkillsState } from './initialState';--const n = setNamespace('agentSkills');+import type { ToolStore } from '../../store';+import { useToolStore } from '../../store';+import {+ AGENT_SKILL_LIST_KEY,+ type AgentSkillDetail,+ agentSkillDetailEntity,+ type AgentSkillDetailItem,+ agentSkillDetailResource,+ agentSkillListEntity,+ type AgentSkillListItem,+ agentSkillListResource,+} from './projection';++/** The skills list has a single entry; its params carry no filter. */+const LIST_PARAMS = {} as Record<string, never>;++/** Sync result of the skills list: replica flags plus the value the UI reads. */+export interface AgentSkillsSyncResult extends ReplicaSyncResult {+ /** The installed skills, `undefined` until the first entry lands. */+ data: AgentSkillListItem[] | undefined;+ /** A request is in flight and there is nothing to show for this entry yet. */+ isLoading: boolean;+ /** Alias of `revalidate`, kept for the existing "reload skills" controls. */+ mutate: () => Promise<unknown>;+}-export interface AgentSkillDetailData {- resourceTree: SkillResourceTreeNode[];- skillDetail?: SkillItem;+/** Sync result of one skill detail page. */+export interface AgentSkillDetailSyncResult extends ReplicaSyncResult {+ /** The detail value: the skill and its resource tree. */+ data: AgentSkillDetail | undefined;+ /** A request is in flight and there is nothing to show for this entry yet. */+ isLoading: boolean;}type Setter = StoreSetter<ToolStore>;@@ -34,59 +56,94 @@ export const createAgentSkillsSlice = (set: Setter, get: () => ToolStore, _api?:new AgentSkillsActionImpl(set, get, _api);export class AgentSkillsActionImpl {- readonly #get: () => ToolStore;- readonly #set: Setter;+ readonly #detail;+ readonly #list;+ /** One skill lives in the list row and in every loaded detail entry. */+ readonly #skill;constructor(set: Setter, get: () => ToolStore, _api?: unknown) {void _api;- this.#set = set;- this.#get = get;+ this.#list = createReplicaSlice(agentSkillListResource, {+ actionPrefix: 'agentSkillList',+ entity: agentSkillListEntity,+ fetcher: () => agentSkillService.list(),+ get,+ merge: (response) => response.data,+ set,+ stateKey: 'agentSkillListReplica',+ view: recordLens<ToolStore, AgentSkillListItem[]>('agentSkillListMap'),+ });+ this.#detail = createReplicaSlice(agentSkillDetailResource, {+ actionPrefix: 'agentSkillDetail',+ entity: agentSkillDetailEntity,+ fetcher: (id) => this.#fetchDetail(id),+ get,+ set,+ stateKey: 'agentSkillDetailReplica',+ view: recordLens<ToolStore, AgentSkillDetail>('agentSkillDetailMap'),+ });+ this.#skill = linkReplicaEntity<AgentSkillListItem>([this.#list, this.#detail]);}- createAgentSkill = async (params: CreateSkillInput): Promise<SkillItem | undefined> => {- const result = await agentSkillService.createSkill(params);- await this.#get().refreshAgentSkills();- return result;+ #fetchDetail = async (id: string): Promise<AgentSkillDetail> => {+ const [skillDetail, resourceTree] = await Promise.all([+ agentSkillService.getById(id),+ agentSkillService.listResources(id, true),+ ]);+ return { resourceTree, skillDetail };};- deleteAgentSkill = async (id: string): Promise<void> => {- await agentSkillService.deleteSkill(id);-- this.#set(- produce((draft: AgentSkillsState) => {- delete draft.agentSkillDetailMap[id];- }),- false,- n('deleteAgentSkill'),- );-- await mutate(toolKeys.agentSkillDetail(id), undefined, { revalidate: false });-- await this.#get().refreshAgentSkills();+ /** The replica scope a request starts under; its result may only land there. */+ #captureScope = (): string => this.#list.resource.scope.get();++ /** Whether the identity a request started under is still the active one. */+ #isCurrentScope = (scope: string): boolean => this.#list.resource.scope.get() === scope;++ /**+ * Fetch the list and write it straight into the replica. `refreshAgentSkills`+ * is also called from flows where the list hook is not mounted (installing a+ * suggested skill from the create-agent modal), and it must populate the+ * store regardless, so this does not just revalidate the SWR entry.+ *+ * The scope is captured before the request and passed to `replace`, so a+ * response that resolves after an identity switch is dropped instead of being+ * written (and persisted) into the next scope's partition.+ */+ #refreshList = async (): Promise<void> => {+ const scope = this.#captureScope();+ const response = await agentSkillService.list();+ this.#list.replace(LIST_PARAMS, response, scope);};- fetchAgentSkillDetail = async (id: string): Promise<SkillItem | undefined> => {- const cached = this.#get().agentSkillDetailMap[id];- if (cached) return cached;-- const detail = await agentSkillService.getById(id);- if (detail) {- this.#set(- produce((draft: AgentSkillsState) => {- draft.agentSkillDetailMap[id] = detail;- }),- false,- n('fetchAgentSkillDetail'),+ createAgentSkill = async (+ params: CreateSkillInput,+ ): Promise<AgentSkillDetailItem | undefined> => {+ const scope = this.#captureScope();+ const result = await agentSkillService.createSkill(params);+ // A created skill belongs to the scope that started the create; never+ // splice it into a list the identity has since switched to.+ if (result && this.#isCurrentScope(scope)) {+ this.#list.update(AGENT_SKILL_LIST_KEY, (items) =>+ items && !items.some((item) => item.id === result.id) ? [result, ...items] : items,);}- return detail;+ await this.#refreshList();+ return result;+ };++ deleteAgentSkill = async (id: string): Promise<void> => {+ const scope = this.#captureScope();+ await agentSkillService.deleteSkill(id);+ // Drops the list row and the loaded detail entry in one fan-out.+ if (this.#isCurrentScope(scope)) this.#skill.remove(id);+ await this.#refreshList();};importAgentSkillFromGitHub = async (params: ImportGitHubInput,): Promise<SkillImportResult | undefined> => {const result = await agentSkillService.importFromGitHub(params);- await this.#get().refreshAgentSkills();+ await this.#refreshList();return result;};@@ -94,7 +151,7 @@ export class AgentSkillsActionImpl {params: ImportUrlInput,): Promise<SkillImportResult | undefined> => {const result = await agentSkillService.importFromUrl(params);- await this.#get().refreshAgentSkills();+ await this.#refreshList();return result;};@@ -102,72 +159,61 @@ export class AgentSkillsActionImpl {params: ImportZipInput,): Promise<SkillImportResult | undefined> => {const result = await agentSkillService.importFromZip(params);- await this.#get().refreshAgentSkills();+ await this.#refreshList();return result;};refreshAgentSkills = async (): Promise<void> => {- const { data } = await agentSkillService.list();- this.#set({ agentSkills: data }, false, n('refreshAgentSkills'));+ await this.#refreshList();};- updateAgentSkill = async (params: UpdateSkillInput): Promise<SkillItem | undefined> => {- const result = await agentSkillService.updateSkill(params);-- if (result) {- this.#set(- produce((draft: AgentSkillsState) => {- draft.agentSkillDetailMap[params.id] = result;- }),- false,- n('updateAgentSkill'),- );+ updateAgentSkill = async (+ params: UpdateSkillInput,+ ): Promise<AgentSkillDetailItem | undefined> => {+ const scope = this.#captureScope();+ const result = await this.#skill.optimistic(+ params.id,+ (skill) => ({+ ...skill,+ ...(params.name !== undefined ? { name: params.name } : {}),+ ...(params.description !== undefined ? { description: params.description } : {}),+ ...(params.manifest ? { manifest: { ...skill.manifest, ...params.manifest } } : {}),+ }),+ () => agentSkillService.updateSkill(params),+ );+ // The detail holds the full skill (content, resources); take the server+ // value — but only while the identity that started the edit is still active.+ if (this.#isCurrentScope(scope)) {+ this.#detail.update(params.id, (data) => (data ? { ...data, skillDetail: result } : data));}-- await mutate(toolKeys.agentSkillDetail(params.id), undefined, { revalidate: false });-- await this.#get().refreshAgentSkills();+ await this.#refreshList();return result;};- useFetchAgentSkillDetail = (skillId?: string): SWRResponse<AgentSkillDetailData> =>- useClientDataSWR<AgentSkillDetailData>(- skillId ? toolKeys.agentSkillDetail(skillId) : null,- async () => {- const [detail, resourceTree] = await Promise.all([- agentSkillService.getById(skillId!),- agentSkillService.listResources(skillId!, true),- ]);-- if (detail) {- this.#set(- produce((draft: AgentSkillsState) => {- draft.agentSkillDetailMap[skillId!] = detail;- }),- false,- n('useFetchAgentSkillDetail'),- );- }-- return { resourceTree, skillDetail: detail };- },- { revalidateOnFocus: false },- );+ /**+ * Fetch orchestration only; read the value through `agentSkillDetailMap[id]`.+ */+ useFetchAgentSkillDetail = (skillId?: string): AgentSkillDetailSyncResult => {+ const sync = this.#detail.useSync(skillId || null);+ const data = useToolStore((s) => (skillId ? s.agentSkillDetailMap[skillId] : undefined));+ return {+ ...sync,+ data,+ isLoading: !data && (sync.isValidating || !sync.isHydrated),+ };+ };- useFetchAgentSkills = (enabled: boolean): SWRResponse<SkillListItem[]> =>- useSWR<SkillListItem[]>(- enabled ? toolKeys.agentSkills() : null,- async () => {- const { data } = await agentSkillService.list();- return data;- },- {- onSuccess: (data) => {- this.#set({ agentSkills: data }, false, n('useFetchAgentSkills'));- },- revalidateOnFocus: false,- },- );+ /** Fetch orchestration only; read the rows through `agentSkillsSelectors`. */+ useFetchAgentSkills = (enabled: boolean): AgentSkillsSyncResult => {+ const sync = this.#list.useSync(LIST_PARAMS, { enabled });+ const data = useToolStore((s) => s.agentSkillListMap[AGENT_SKILL_LIST_KEY]);+ return {+ ...sync,+ data,+ isLoading: !data && (sync.isValidating || !sync.isHydrated),+ mutate: sync.revalidate,+ };+ };}export type AgentSkillsAction = Pick<AgentSkillsActionImpl, keyof AgentSkillsActionImpl>;diff --git a/src/store/tool/slices/agentSkills/index.ts b/src/store/tool/slices/agentSkills/index.tsindex f9f1301c302..b094bc247e0 100644--- a/src/store/tool/slices/agentSkills/index.ts+++ b/src/store/tool/slices/agentSkills/index.ts@@ -1,3 +1,9 @@export { type AgentSkillsAction, createAgentSkillsSlice } from './action';export { type AgentSkillsState, initialAgentSkillsState } from './initialState';+export {+ AGENT_SKILL_LIST_KEY,+ type AgentSkillDetail,+ type AgentSkillDetailItem,+ type AgentSkillListItem,+} from './projection';export { agentSkillsSelectors } from './selectors';diff --git a/src/store/tool/slices/agentSkills/initialState.ts b/src/store/tool/slices/agentSkills/initialState.tsindex 4ea75ad4e79..d028f9ef0c7 100644--- a/src/store/tool/slices/agentSkills/initialState.ts+++ b/src/store/tool/slices/agentSkills/initialState.ts@@ -1,13 +1,21 @@-import type { SkillItem, SkillListItem } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';++import type { AgentSkillDetail, AgentSkillListItem } from './projection';export interface AgentSkillsState {- agentSkillDetailMap: Record<string, SkillItem>;- agentSkills: SkillListItem[];- agentSkillsLoading: boolean;+ /** Replica view of the loaded skill details, one entry per skill id. */+ agentSkillDetailMap: Record<string, AgentSkillDetail>;+ /** Replica bookkeeping of `agentSkillDetailMap`. */+ agentSkillDetailReplica: ReplicaState<AgentSkillDetail>;+ /** Replica view of the installed skills, one entry per scope (`AGENT_SKILL_LIST_KEY`). */+ agentSkillListMap: Record<string, AgentSkillListItem[]>;+ /** Replica bookkeeping of `agentSkillListMap`. */+ agentSkillListReplica: ReplicaState<AgentSkillListItem[]>;}export const initialAgentSkillsState: AgentSkillsState = {agentSkillDetailMap: {},- agentSkills: [],- agentSkillsLoading: false,+ agentSkillDetailReplica: createReplicaState(),+ agentSkillListMap: {},+ agentSkillListReplica: createReplicaState(),};diff --git a/src/store/tool/slices/agentSkills/projection.ts b/src/store/tool/slices/agentSkills/projection.tsnew file mode 100644index 00000000000..9f69edda94a--- /dev/null+++ b/src/store/tool/slices/agentSkills/projection.ts@@ -0,0 +1,70 @@+import type { SkillResourceTreeNode } from '@lobechat/types';++import { arrayEntity, defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';+import type { agentSkillService } from '@/services/skill';++type SkillListResponse = Awaited<ReturnType<typeof agentSkillService.list>>;++type SkillDetailResponse = Awaited<ReturnType<typeof agentSkillService.getById>>;++/** One row of the installed skills list. */+export type AgentSkillListItem = SkillListResponse['data'][number];++/** The full skill behind a detail page (`getById` — content included). */+export type AgentSkillDetailItem = NonNullable<SkillDetailResponse>;++/**+ * A skill detail entry: the skill plus the resource tree fetched alongside it,+ * so a detail surface paints both from one replica value.+ */+export interface AgentSkillDetail {+ resourceTree: SkillResourceTreeNode[];+ skillDetail?: AgentSkillDetailItem;+}++/**+ * Installed skills of the active scope. The list is not paged, so every loaded+ * skill sits in the single `all` entry (`agentSkillListMap[AGENT_SKILL_LIST_KEY]`).+ */+export const AGENT_SKILL_LIST_KEY = 'all';++/** Every installed skill of the active scope (`agentSkillListMap.all`). */+export const agentSkillListResource = defineReplica<+ Record<string, never>,+ AgentSkillListItem[],+ SkillListResponse+>({+ key: () => AGENT_SKILL_LIST_KEY,+ name: 'agentSkillList',+ storage: 'indexedDB',+ version: 1,+});++/** One skill detail page, keyed by skill id (`agentSkillDetailMap[id]`). */+export const agentSkillDetailResource = defineReplica<string, AgentSkillDetail>({+ key: (id) => id,+ name: 'agentSkillDetail',+ storage: 'indexedDB',+ version: 1,+});++/** Skills are addressed by `id` across the tool store. */+export const agentSkillListEntity: ReplicaEntityAdapter<AgentSkillListItem[], AgentSkillListItem> =+ arrayEntity<AgentSkillListItem>((skill) => skill.id);++/**+ * The detail value wraps one skill: a list-row change patches that skill — the+ * patch merges into the richer `SkillItem`, so fields the list does not carry+ * (content, resources) survive — and deleting it drops the whole detail entry.+ */+export const agentSkillDetailEntity: ReplicaEntityAdapter<AgentSkillDetail, AgentSkillListItem> = {+ has: (data, id) => data.skillDetail?.id === id,+ map: (data, _id, fn) => {+ const current = data.skillDetail;+ if (!current) return data;+ const next = fn(current);+ if (next === undefined) return undefined;+ if (next === (current as AgentSkillListItem)) return data;+ return { ...data, skillDetail: { ...current, ...next } };+ },+};diff --git a/src/store/tool/slices/agentSkills/selectors.ts b/src/store/tool/slices/agentSkills/selectors.tsindex d2c914f86b9..0c4329c183f 100644--- a/src/store/tool/slices/agentSkills/selectors.ts+++ b/src/store/tool/slices/agentSkills/selectors.ts@@ -1,32 +1,38 @@-import type { LobeToolMeta, SkillItem, SkillListItem } from '@lobechat/types';+import type { LobeToolMeta } from '@lobechat/types';import type { ToolStoreState } from '../../initialState';+import {+ AGENT_SKILL_LIST_KEY,+ type AgentSkillDetailItem,+ type AgentSkillListItem,+} from './projection';-const getAgentSkills = (s: ToolStoreState): SkillListItem[] => s.agentSkills || [];+const getAgentSkills = (s: ToolStoreState): AgentSkillListItem[] =>+ s.agentSkillListMap?.[AGENT_SKILL_LIST_KEY] || [];-const getMarketAgentSkills = (s: ToolStoreState): SkillListItem[] =>- (s.agentSkills || []).filter((skill) => skill.source === 'market');+const getMarketAgentSkills = (s: ToolStoreState): AgentSkillListItem[] =>+ getAgentSkills(s).filter((skill) => skill.source === 'market');-const getUserAgentSkills = (s: ToolStoreState): SkillListItem[] =>- (s.agentSkills || []).filter((skill) => skill.source === 'user');+const getUserAgentSkills = (s: ToolStoreState): AgentSkillListItem[] =>+ getAgentSkills(s).filter((skill) => skill.source === 'user');const getAgentSkillByIdentifier =(identifier: string) =>- (s: ToolStoreState): SkillListItem | undefined =>- (s.agentSkills || []).find((skill) => skill.identifier === identifier);+ (s: ToolStoreState): AgentSkillListItem | undefined =>+ getAgentSkills(s).find((skill) => skill.identifier === identifier);const getAgentSkillDetail =(id: string) =>- (s: ToolStoreState): SkillItem | undefined =>- s.agentSkillDetailMap?.[id];+ (s: ToolStoreState): AgentSkillDetailItem | undefined =>+ s.agentSkillDetailMap?.[id]?.skillDetail;const isAgentSkill =(identifier: string) =>(s: ToolStoreState): boolean =>- (s.agentSkills || []).some((skill) => skill.identifier === identifier);+ getAgentSkills(s).some((skill) => skill.identifier === identifier);const agentSkillMetaList = (s: ToolStoreState): LobeToolMeta[] =>- (s.agentSkills || []).map((skill) => {+ getAgentSkills(s).map((skill) => {const author = skill.manifest?.author;const authorName = typeof author === 'string' ? author : author?.name || 'User';