🤯 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(skills): persist the project-skills scan through @lobechat/replica (#20848)
Arvin Xuc793d987ccb4
diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.tsindex e6abab5da28..4dd9aa99145 100644--- a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts@@ -13,12 +13,11 @@ import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';-import { useFetchProjectSkills } from '@/hooks/useFetchProjectSkills';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { useToolStore } from '@/store/tool';-import { agentDocumentSkillsSelectors } from '@/store/tool/selectors';+import { agentDocumentSkillsSelectors, projectSkillsSelectors } from '@/store/tool/selectors';import type { AgentDocumentSkillItem } from '@/store/tool/slices/agentDocumentSkills/initialState';import { useAgentId } from '../../hooks/useAgentId';@@ -89,11 +88,12 @@ export const useSlashActionItems = (): SlashOptions['items'] => {// makes filesystem skills reachable even when this client isn't the desktop app// (previously gated on `isDesktop` alone, so remote/web runs got nothing).const projectSkillsEnabled = (isDesktop || !!remoteDeviceId) && !!workingDirectory;- const { data: projectSkillsData } = useFetchProjectSkills(- projectSkillsEnabled ? workingDirectory : undefined,- remoteDeviceId,+ const projectSkillsDirectory = projectSkillsEnabled ? workingDirectory : undefined;+ useToolStore((s) => s.useFetchProjectSkills)(projectSkillsDirectory, remoteDeviceId);+ const projectSkills = useToolStore(+ (s) =>+ projectSkillsSelectors.getProjectSkills(projectSkillsDirectory, remoteDeviceId)(s)?.skills,);- const projectSkills = projectSkillsData?.skills;// Agent-document skill bundles (the "Agent skills" group in the working// sidebar). The registry is a per-agent replica, so a switch paints thediff --git a/src/features/SkillsList/useProjectSkills.test.ts b/src/features/SkillsList/useProjectSkills.test.tsnew file mode 100644index 00000000000..10cabc95490--- /dev/null+++ b/src/features/SkillsList/useProjectSkills.test.ts@@ -0,0 +1,110 @@+/**+ * @vitest-environment happy-dom+ *+ * Regression: after a reload the working-sidebar Skills section must paint the+ * last project-skills scan straight away instead of a spinner, while the IPC /+ * RPC scan revalidates in the background.+ */+import { randomUUID } from 'node:crypto';++import type { ListProjectSkillsResult, ProjectSkillItem } from '@lobechat/electron-client-ipc';+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 { projectSkillService } from '@/services/projectSkill';+import { useToolStore } from '@/store/tool';+import { initialState as initialToolState } from '@/store/tool/initialState';++import { useProjectSkills } from './useProjectSkills';++vi.mock('@/services/projectSkill', () => ({+ projectSkillService: { listProjectSkills: vi.fn() },+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++/** Each mount gets a fresh in-memory SWR cache, as after a page reload. */+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const skill = (name: string): ProjectSkillItem => ({+ fileCount: 1,+ files: ['SKILL.md'],+ name,+ path: `/repo/.agents/skills/${name}/SKILL.md`,+ previewRoot: '/repo',+ scope: 'project',+ skillDir: `/repo/.agents/skills/${name}`,+ source: 'agents',+});++const scan = (...names: string[]): ListProjectSkillsResult => ({+ root: '/repo',+ skills: names.map(skill),+ source: 'agents',+});++describe('useProjectSkills after a reload', () => {+ const listProjectSkills = () => vi.mocked(projectSkillService.listProjectSkills);++ beforeEach(() => {+ const scope = `use-project-skills-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useToolStore.setState(initialToolState));+ listProjectSkills().mockReset();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('paints the cached scan before the fresh scan answers, then replaces it', async () => {+ listProjectSkills().mockResolvedValue(scan('alpha', 'beta'));+ const first = renderHook(() => useProjectSkills('/repo'), { wrapper });+ await waitFor(() =>+ expect(first.result.current.items.map((i) => i.name)).toEqual(['alpha', 'beta']),+ );+ // Let the scan settle into the local copy before the "reload".+ await act(() => new Promise((resolve) => setTimeout(resolve, 50)));+ first.unmount();++ // Reload: in-memory state is gone and the scan is held open.+ act(() => useToolStore.setState(initialToolState));+ let release!: (value: ListProjectSkillsResult) => void;+ listProjectSkills().mockImplementation(+ () => new Promise<ListProjectSkillsResult>((resolve) => (release = resolve)),+ );++ const reloaded = renderHook(() => useProjectSkills('/repo'), { wrapper });++ await waitFor(() =>+ expect(reloaded.result.current.items.map((i) => i.name)).toEqual(['alpha', 'beta']),+ );+ expect(reloaded.result.current.isLoading).toBe(false);++ await act(async () => release(scan('alpha', 'beta', 'gamma')));+ await waitFor(() =>+ expect(reloaded.result.current.items.map((i) => i.name)).toEqual(['alpha', 'beta', 'gamma']),+ );+ });+});diff --git a/src/features/SkillsList/useProjectSkills.ts b/src/features/SkillsList/useProjectSkills.tsindex c02844d74af..d0dd475bd7a 100644--- a/src/features/SkillsList/useProjectSkills.ts+++ b/src/features/SkillsList/useProjectSkills.ts@@ -4,14 +4,15 @@ import path from 'pathe';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { useFetchProjectSkills } from '@/hooks/useFetchProjectSkills';import { useChatStore } from '@/store/chat';+import { useToolStore } from '@/store/tool';+import { projectSkillsSelectors } from '@/store/tool/selectors';import type { SkillListItem, SkillRowAction } from './SkillsList';export interface UseProjectSkillsResult {deviceItems: SkillListItem[];- /** The thrown error from the SWR scan, if it failed. */+ /** The thrown error from the latest scan, if it failed. */error: unknown;/*** Per-row actions for filesystem skills: "view" opens the SKILL.md (locally@@ -19,9 +20,10 @@ export interface UseProjectSkillsResult {* rename / delete are stubbed (disabled) until filesystem-mutation IPC lands.*/getRowActions: (item: SkillListItem) => SkillRowAction[];+ /** No scan (persisted or fresh) for this device + directory yet. */isLoading: boolean;items: SkillListItem[];- /** Retry the failed scan (SWR `mutate`). */+ /** Retry the failed scan. */mutate: () => void;onOpenFile: (item: SkillListItem, relativePath: string) => void;onOpenSkill: (item: SkillListItem) => void;@@ -30,7 +32,7 @@ export interface UseProjectSkillsResult {}/**- * Shared SWR + handlers for filesystem-backed skills. Project skills live+ * Shared scan + handlers for filesystem-backed skills. Project skills live* under `.agents/skills` / `.claude/skills` in `workingDirectory`; device* skills live under those directories in the execution device's home.*@@ -50,10 +52,17 @@ export const useProjectSkills = (const { t } = useTranslation('chat');const openLocalFile = useChatStore((s) => s.openLocalFile);- const { data, error, isLoading, mutate } = useFetchProjectSkills(workingDirectory, deviceId);+ const { error, revalidate } = useToolStore((s) => s.useFetchProjectSkills)(+ workingDirectory,+ deviceId,+ );+ // The persisted scan paints on boot; the IPC / RPC scan replaces it once it+ // returns. `undefined` only until either one lands for this device + directory.+ const data = useToolStore(projectSkillsSelectors.getProjectSkills(workingDirectory, deviceId));+ const isLoading = !!workingDirectory && !data && !error;// listProjectSkills approves per-skill preview roots. Fall back to the- // requested workingDirectory while the SWR fetch is in flight or when reading+ // requested workingDirectory while the scan is in flight or when reading// legacy cached payloads without previewRoot.const previewRoot = data?.root || workingDirectory || '';@@ -158,8 +167,8 @@ export const useProjectSkills = ();const retry = useCallback(() => {- void mutate();- }, [mutate]);+ void revalidate();+ }, [revalidate]);return {deviceItems,diff --git a/src/hooks/useFetchProjectSkills.ts b/src/hooks/useFetchProjectSkills.tsdeleted file mode 100644index 4c2a1e9f5a7..00000000000--- a/src/hooks/useFetchProjectSkills.ts+++ /dev/null@@ -1,26 +0,0 @@-import { type ListProjectSkillsResult } from '@lobechat/electron-client-ipc';--import { useClientDataSWR } from '@/libs/swr';-import { projectSkillService } from '@/services/projectSkill';--/**- * Shared SWR fetch for filesystem-backed project and device skills.- *- * `deviceId` picks the transport: a bound device scans over the- * `device.listProjectSkills` RPC, the local desktop reads over Electron IPC. The- * SWR key is stable across callers (the `/` slash menu and the SkillsList UI- * hook), so they dedupe a single fetch. Pass `undefined` workingDirectory to- * keep the hook inert — no fetch fires.- */-export const useFetchProjectSkills = (workingDirectory: string | undefined, deviceId?: string) => {- const isRemote = !!deviceId;- return useClientDataSWR<ListProjectSkillsResult | undefined>(- workingDirectory ? ['project-skills', deviceId ?? 'local', workingDirectory] : null,- () => projectSkillService.listProjectSkills({ deviceId, scope: workingDirectory! }),- // Remote skills live on a device this client can't watch for filesystem- // changes, so refetch on focus to pick up edits made on the device. The- // local IPC path stays off-focus — its scan is cheap to trigger explicitly- // and the desktop already sees its own filesystem.- { revalidateOnFocus: isRemote, shouldRetryOnError: false },- );-};diff --git a/src/store/tool/initialState.ts b/src/store/tool/initialState.tsindex f69a9e8caa3..84118f9268c 100644--- a/src/store/tool/initialState.ts+++ b/src/store/tool/initialState.ts@@ -19,6 +19,10 @@ import {} from './slices/lobehubSkillStore/initialState';import { initialMCPStoreState, type MCPStoreState } from './slices/mcpStore/initialState';import { initialPluginState, type PluginState } from './slices/plugin/initialState';+import {+ initialProjectSkillsState,+ type ProjectSkillsState,+} from './slices/projectSkills/initialState';export type ToolStoreState = ConnectorState &PluginState &@@ -28,7 +32,8 @@ export type ToolStoreState = ConnectorState &ComposioStoreState &LobehubSkillStoreState &AgentSkillsState &- AgentDocumentSkillsState;+ AgentDocumentSkillsState &+ ProjectSkillsState;export const initialState: ToolStoreState = {...initialConnectorState,@@ -40,4 +45,5 @@ export const initialState: ToolStoreState = {...initialLobehubSkillStoreState,...initialAgentSkillsState,...initialAgentDocumentSkillsState,+ ...initialProjectSkillsState,};diff --git a/src/store/tool/selectors/index.ts b/src/store/tool/selectors/index.tsindex 3f308092fb8..503447acf9f 100644--- a/src/store/tool/selectors/index.ts+++ b/src/store/tool/selectors/index.ts@@ -9,4 +9,5 @@ export { customPluginSelectors } from '../slices/customPlugin/selectors';export { lobehubSkillStoreSelectors } from '../slices/lobehubSkillStore/selectors';export { mcpStoreSelectors } from '../slices/mcpStore/selectors';export { pluginSelectors } from '../slices/plugin/selectors';+export { projectSkillsSelectors } from '../slices/projectSkills/selectors';export { toolSelectors } from './tool';diff --git a/src/store/tool/slices/projectSkills/action.test.ts b/src/store/tool/slices/projectSkills/action.test.tsnew file mode 100644index 00000000000..cf727bca823--- /dev/null+++ b/src/store/tool/slices/projectSkills/action.test.ts@@ -0,0 +1,200 @@+/**+ * @vitest-environment happy-dom+ *+ * The project / device skills scan is a replica keyed per device + directory:+ * after a reload the Skills section and the `/` menu paint the persisted scan+ * before the IPC / RPC scan answers, and the fresh scan then replaces it.+ */+import { randomUUID } from 'node:crypto';++import type { ListProjectSkillsResult, ProjectSkillItem } from '@lobechat/electron-client-ipc';+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 { projectSkillService } from '@/services/projectSkill';++import { useToolStore } from '../../store';+import { initialProjectSkillsState } from './initialState';+import { type ProjectSkillsParams, projectSkillsResource } from './projection';+import { projectSkillsSelectors } from './selectors';++vi.mock('@/services/projectSkill', () => ({+ projectSkillService: { listProjectSkills: vi.fn() },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++/** A fresh SWR cache per mount, like a reload: nothing survives but storage. */+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const skill = (name: string): ProjectSkillItem => ({+ fileCount: 1,+ files: ['SKILL.md'],+ name,+ path: `/repo/.agents/skills/${name}/SKILL.md`,+ previewRoot: '/repo',+ scope: 'project',+ skillDir: `/repo/.agents/skills/${name}`,+ source: 'agents',+});++const scan = (...names: string[]): ListProjectSkillsResult => ({+ root: '/repo',+ skills: names.map(skill),+ source: 'agents',+});++/** Never-resolving scan: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const LOCAL_REPO: ProjectSkillsParams = { workingDirectory: '/repo' };+const DEVICE_REPO: ProjectSkillsParams = { deviceId: 'device-1', workingDirectory: '/repo' };+const LOCAL_OTHER: ProjectSkillsParams = { workingDirectory: '/other' };+const ALL_PARAMS = [LOCAL_REPO, DEVICE_REPO, LOCAL_OTHER];++describe('projectSkills 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 listProjectSkills = () => vi.mocked(projectSkillService.listProjectSkills);+ const rowKey = (params: ProjectSkillsParams) => projectSkillsResource.storageKey(params);+ const persist = (params: ProjectSkillsParams, data: ListProjectSkillsResult) =>+ projectSkillsResource.storage!.set({ queryKey: rowKey(params), scope }, { data, updatedAt: 1 });+ const fetchSkills = ({ deviceId, workingDirectory }: ProjectSkillsParams) =>+ renderHook(() => useToolStore((s) => s.useFetchProjectSkills)(workingDirectory, deviceId), {+ wrapper,+ });+ const skillNames = ({ deviceId, workingDirectory }: ProjectSkillsParams) =>+ projectSkillsSelectors+ .getProjectSkills(+ workingDirectory,+ deviceId,+ )(useToolStore.getState())+ ?.skills.map((s) => s.name);+ /** A reload: the in-memory store is gone, only the persisted rows remain. */+ const reload = () => act(() => useToolStore.setState(initialProjectSkillsState));++ beforeEach(() => {+ useScope(`project-skills-user-${randomUUID()}:personal`);+ reload();+ listProjectSkills().mockReset();+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((value) =>+ ALL_PARAMS.map((params) =>+ projectSkillsResource.storage!.remove({ queryKey: rowKey(params), scope: value }),+ ),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the last scan after a reload before the scan answers, then replaces it', async () => {+ listProjectSkills().mockResolvedValue(scan('alpha', 'beta'));+ const first = fetchSkills(LOCAL_REPO);+ await waitFor(() => expect(skillNames(LOCAL_REPO)).toEqual(['alpha', 'beta']));+ // Wait for the scan to land in storage before "reloading".+ await waitFor(async () =>+ expect(+ (await projectSkillsResource.storage!.get({ queryKey: rowKey(LOCAL_REPO), scope }))?.data,+ ).toEqual(scan('alpha', 'beta')),+ );+ first.unmount();++ reload();+ expect(skillNames(LOCAL_REPO)).toBeUndefined();++ let release!: (value: ListProjectSkillsResult) => void;+ listProjectSkills().mockImplementation(+ () => new Promise<ListProjectSkillsResult>((resolve) => (release = resolve)),+ );+ const sync = fetchSkills(LOCAL_REPO);++ // The persisted scan paints while the IPC scan is still held open.+ await waitFor(() => expect(skillNames(LOCAL_REPO)).toEqual(['alpha', 'beta']));+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);++ await act(async () => release(scan('alpha', 'beta', 'gamma')));+ await waitFor(() => expect(skillNames(LOCAL_REPO)).toEqual(['alpha', 'beta', 'gamma']));+ });++ it('scans through the device RPC or local IPC for the requested directory', async () => {+ listProjectSkills().mockResolvedValue(scan('alpha'));++ fetchSkills(DEVICE_REPO);+ await waitFor(() =>+ expect(listProjectSkills()).toHaveBeenCalledWith({ deviceId: 'device-1', scope: '/repo' }),+ );++ fetchSkills(LOCAL_REPO);+ await waitFor(() =>+ expect(listProjectSkills()).toHaveBeenCalledWith({ deviceId: undefined, scope: '/repo' }),+ );+ });++ it('keeps each device + directory in its own entry', async () => {+ await persist(LOCAL_REPO, scan('local-repo'));+ await persist(DEVICE_REPO, scan('device-repo'));+ await persist(LOCAL_OTHER, scan('local-other'));+ listProjectSkills().mockImplementation(pending);++ fetchSkills(DEVICE_REPO);+ await waitFor(() => expect(skillNames(DEVICE_REPO)).toEqual(['device-repo']));+ expect(skillNames(LOCAL_REPO)).toBeUndefined();++ fetchSkills(LOCAL_OTHER);+ await waitFor(() => expect(skillNames(LOCAL_OTHER)).toEqual(['local-other']));+ expect(skillNames(LOCAL_REPO)).toBeUndefined();+ });++ it('does not paint another user scope’s persisted scan', async () => {+ await persist(LOCAL_REPO, scan('someone-else'));+ useScope(`project-skills-user-${randomUUID()}:personal`);+ listProjectSkills().mockImplementation(pending);++ const sync = fetchSkills(LOCAL_REPO);+ await waitFor(() => expect(sync.result.current.isHydrated).toBe(true));+ expect(skillNames(LOCAL_REPO)).toBeUndefined();+ });++ it('settles a host without a scanner to an empty scan', async () => {+ listProjectSkills().mockResolvedValue(undefined);++ fetchSkills(LOCAL_REPO);+ await waitFor(() => expect(skillNames(LOCAL_REPO)).toEqual([]));+ });++ it('stays inert without a working directory', async () => {+ const sync = fetchSkills({ workingDirectory: '' });++ await waitFor(() => expect(sync.result.current.isValidating).toBe(false));+ expect(listProjectSkills()).not.toHaveBeenCalled();+ });+});diff --git a/src/store/tool/slices/projectSkills/action.ts b/src/store/tool/slices/projectSkills/action.tsnew file mode 100644index 00000000000..0ce3ad5e308--- /dev/null+++ b/src/store/tool/slices/projectSkills/action.ts@@ -0,0 +1,57 @@+import type { ListProjectSkillsResult } from '@lobechat/electron-client-ipc';++import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';+import { projectSkillService } from '@/services/projectSkill';+import { type StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import { type ToolStore } from '../../store';+import { EMPTY_PROJECT_SKILLS, projectSkillsResource } from './projection';++const n = setNamespace('projectSkills');++type Setter = StoreSetter<ToolStore>;++export const createProjectSkillsSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>+ new ProjectSkillsActionImpl(set, get, _api);++export class ProjectSkillsActionImpl {+ readonly #skills;++ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {+ void _api;+ this.#skills = createReplicaSlice(projectSkillsResource, {+ actionPrefix: n('projectSkills'),+ // A host without a scanner answers `undefined`; settle it as an empty scan+ // so the entry stops reading as loading.+ fetcher: async ({ deviceId, workingDirectory }) =>+ (await projectSkillService.listProjectSkills({ deviceId, scope: workingDirectory })) ??+ EMPTY_PROJECT_SKILLS,+ get,+ set,+ stateKey: 'projectSkillsReplica',+ view: recordLens<ToolStore, ListProjectSkillsResult>('projectSkillsMap'),+ });+ }++ /**+ * Scan the project and execution-device skills of one device + directory,+ * shared by the `/` slash menu and the working-sidebar Skills section. A bound+ * `deviceId` scans over the `device.listProjectSkills` RPC, the local desktop+ * over Electron IPC. Pass `undefined` workingDirectory to keep it inert. Read+ * the scan with `projectSkillsSelectors`, not from the return value.+ */+ useFetchProjectSkills = (+ workingDirectory: string | undefined,+ deviceId?: string,+ ): ReplicaSyncResult =>+ this.#skills.useSync(workingDirectory ? { deviceId, workingDirectory } : null, {+ // Remote skills live on a device this client can't watch for filesystem+ // changes, so refetch on focus to pick up edits made on the device. The+ // local IPC path stays off-focus — the desktop already sees its own+ // filesystem.+ revalidateOnFocus: !!deviceId,+ });+}++export type ProjectSkillsAction = Pick<ProjectSkillsActionImpl, keyof ProjectSkillsActionImpl>;diff --git a/src/store/tool/slices/projectSkills/index.ts b/src/store/tool/slices/projectSkills/index.tsnew file mode 100644index 00000000000..132ecfbc299--- /dev/null+++ b/src/store/tool/slices/projectSkills/index.ts@@ -0,0 +1,4 @@+export { createProjectSkillsSlice, type ProjectSkillsAction } from './action';+export { initialProjectSkillsState, type ProjectSkillsState } from './initialState';+export { projectSkillsKey, type ProjectSkillsParams, projectSkillsResource } from './projection';+export { projectSkillsSelectors } from './selectors';diff --git a/src/store/tool/slices/projectSkills/initialState.ts b/src/store/tool/slices/projectSkills/initialState.tsnew file mode 100644index 00000000000..45926af771b--- /dev/null+++ b/src/store/tool/slices/projectSkills/initialState.ts@@ -0,0 +1,15 @@+import type { ListProjectSkillsResult } from '@lobechat/electron-client-ipc';++import { createReplicaState, type ReplicaState } from '@/libs/replica';++export interface ProjectSkillsState {+ /** Filesystem skill scans, keyed by `projectSkillsKey({ deviceId, workingDirectory })`. */+ projectSkillsMap: Record<string, ListProjectSkillsResult>;+ /** Replica bookkeeping for `projectSkillsMap`. */+ projectSkillsReplica: ReplicaState<ListProjectSkillsResult>;+}++export const initialProjectSkillsState: ProjectSkillsState = {+ projectSkillsMap: {},+ projectSkillsReplica: createReplicaState(),+};diff --git a/src/store/tool/slices/projectSkills/projection.ts b/src/store/tool/slices/projectSkills/projection.tsnew file mode 100644index 00000000000..6fc79dfd761--- /dev/null+++ b/src/store/tool/slices/projectSkills/projection.ts@@ -0,0 +1,37 @@+import type { ListProjectSkillsResult } from '@lobechat/electron-client-ipc';++import { defineReplica } from '@/libs/replica';++/** One filesystem skill scan target: a bound device (or the local desktop) + directory. */+export interface ProjectSkillsParams {+ /** Bound device scanned over RPC; `undefined` is the local desktop over IPC. */+ deviceId?: string;+ workingDirectory: string;+}++/**+ * How many scans stay persisted per scope. Each scan carries every skill's file+ * list (capped by the scanner), so only the recently opened device + directory+ * pairs are kept; the one on screen is pinned by its mounted `useSync`.+ */+export const MAX_PERSISTED_PROJECT_SKILL_SCANS = 20;++/** A settled scan that found nothing (or a host without a skills scanner). */+export const EMPTY_PROJECT_SKILLS: ListProjectSkillsResult = { root: '', skills: [], source: null };++export const projectSkillsKey = ({ deviceId, workingDirectory }: ProjectSkillsParams): string =>+ JSON.stringify([deviceId ?? 'local', workingDirectory]);++/**+ * The `.agents/skills` / `.claude/skills` scan of one device + directory, keyed+ * per device and directory so switching either never paints another target's+ * skills. Persisted so the working-sidebar Skills section and the `/` menu paint+ * the last scan on boot while the IPC / RPC scan confirms it.+ */+export const projectSkillsResource = defineReplica<ProjectSkillsParams, ListProjectSkillsResult>({+ key: projectSkillsKey,+ name: 'projectSkills',+ persist: { maxEntries: MAX_PERSISTED_PROJECT_SKILL_SCANS },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/tool/slices/projectSkills/selectors.ts b/src/store/tool/slices/projectSkills/selectors.tsnew file mode 100644index 00000000000..435802eb55d--- /dev/null+++ b/src/store/tool/slices/projectSkills/selectors.ts@@ -0,0 +1,16 @@+import type { ListProjectSkillsResult } from '@lobechat/electron-client-ipc';++import type { ToolStoreState } from '../../initialState';+import { projectSkillsKey } from './projection';++/** The scan of one device + directory; `undefined` until it is hydrated or fetched. */+const getProjectSkills =+ (workingDirectory: string | undefined, deviceId?: string) =>+ (s: ToolStoreState): ListProjectSkillsResult | undefined =>+ workingDirectory+ ? s.projectSkillsMap[projectSkillsKey({ deviceId, workingDirectory })]+ : undefined;++export const projectSkillsSelectors = {+ getProjectSkills,+};diff --git a/src/store/tool/store.ts b/src/store/tool/store.tsindex df01dfd460e..8d9f27cccfa 100644--- a/src/store/tool/store.ts+++ b/src/store/tool/store.ts@@ -22,6 +22,7 @@ import {} from './slices/lobehubSkillStore';import { createMCPPluginStoreSlice, type PluginMCPStoreAction } from './slices/mcpStore';import { createPluginSlice, type PluginAction } from './slices/plugin';+import { createProjectSkillsSlice, type ProjectSkillsAction } from './slices/projectSkills';// =============== Aggregate createStoreFn ============ //@@ -35,6 +36,7 @@ export type ToolStore = ToolStoreState &LobehubSkillStoreAction &AgentSkillsAction &AgentDocumentSkillsAction &+ ProjectSkillsAction &ResetableStore;type ToolStoreAction = ConnectorAction &@@ -46,6 +48,7 @@ type ToolStoreAction = ConnectorAction &LobehubSkillStoreAction &AgentSkillsAction &AgentDocumentSkillsAction &+ ProjectSkillsAction &ResetableStore;class ToolStoreResetAction extends ResetableStoreAction<ToolStore> {@@ -66,6 +69,7 @@ const createStore: StateCreator<ToolStore, [['zustand/devtools', never]]> = (createLobehubSkillStoreSlice(...parameters),createAgentSkillsSlice(...parameters),createAgentDocumentSkillsSlice(...parameters),+ createProjectSkillsSlice(...parameters),new ToolStoreResetAction(...parameters),]),});