Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(skillhub): add local skill activation and uninstall controls

xd-bobo793dcf7927fd
diff --git a/apps/desktop/help-knowledge/skills.md b/apps/desktop/help-knowledge/skills.md
index db982b0ab4..579274e9fb 100644
--- a/apps/desktop/help-knowledge/skills.md
+++ b/apps/desktop/help-knowledge/skills.md
@@ -1,7 +1,7 @@
---
id: skills
title: Skills (reusable agent capabilities)
-summary: Browse, install, publish, and update agent skills; installed skills appear as "/" slash commands and are shared across Claude Code and Codex.
+summary: Browse, install, disable, uninstall, publish, and update agent skills; installed skills appear as "/" slash commands and are shared across Claude Code and Codex.
---
Skills are reusable agent capabilities you package as a folder and load into your sessions. They're managed on the same page as Plugins — **Skills** and **Plugins** are two tabs of one management surface (the Skills tab is the in-app browser for finding, installing, publishing, and updating skills).
@@ -24,8 +24,18 @@ Skills are reusable agent capabilities you package as a folder and load into you
**Using an installed skill:**
+- Hover over a local skill in the `/` suggestions and choose **View skill details** in its information panel to open that exact skill. This does not insert or send the command.
+
- Type `/` in the composer to open the slash-command palette; your installed skills show up there alongside built-in and agent commands. Pick one to run it.
+**Disabling or uninstalling a local skill (Desktop):**
+
+- Open a skill's detail page to use the switch in the top action bar. For a market skill installed in multiple locations, select the local copy from the location dropdown beside the switch. Turning it off keeps the files and removes the skill from Cindy's command palette. New or restarted Claude Code, Codex, and Pi agents apply that choice; an already-running agent keeps its existing context.
+- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.
+- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.
+- External source imports remove only their discovery links and keep the external source files. Package-owned or built-in skills must be removed through their owning package; their uninstall action is unavailable here.
+- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If only metadata/link cleanup fails, the notice offers **Retry cleanup** in the current app run.
+
**Publishing your own skill:**
- Find the publish action on the Skills page and point it at the skill's local folder. It zips the folder and uploads it — reading your directory in place, without copying or moving anything.
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 90c87343bb..a1a7b9d3fe 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1,3 +1,4 @@
+import { readDisabledSkillPaths } from '../skillhub/activationPreferences';
/**
* apps/desktop/src/main/maker-host
*
@@ -999,6 +1000,7 @@ export function getMaker(): Maker {
log: desktopMakerLogger.child('command-gate'),
});
const claudeAgent = new ClaudeCodeAgent({
+ getDisabledSkillPaths: readDisabledSkillPaths,
auth: desktopClaudeAuthAdapter,
runtimeConfig: buildDesktopClaudeRuntimeConfig(getClaudeEndpoint),
binaryPath: claudePath,
@@ -1317,6 +1319,7 @@ export function getMaker(): Maker {
?? 'default';
};
const codexAgent = new CodexAgent({
+ getDisabledSkillPaths: readDisabledSkillPaths,
auth: desktopCodexAuthAdapter,
runtimeConfig: desktopCodexRuntimeConfig,
binaryPath: codexPath,
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 063ea2f131..3684b195c3 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -1,3 +1,4 @@
+import { readDisabledSkillPaths } from '../skillhub/activationPreferences';
/**
* pi agent 的 desktop host 装配 —— auth / runtimeConfig / 二进制解析 / 构造,
* 集中在本模块,maker-host/index.ts 只做一次 buildPiAgent() 调用。
@@ -1806,6 +1807,7 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {
}
log.info('pi agent enabled', { binaryPath });
return new PiAgent({
+ getDisabledSkillPaths: readDisabledSkillPaths,
resolveModelContextLimit: (providerId, modelId) => providerId
? readModelContextLimit('pi', providerId, modelId) : null,
auth: desktopPiAuthAdapter,
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index ce8fa7c1c6..ff6efbb436 100644
--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
@@ -143,8 +143,8 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [
{
id: "skills",
title: "Skills (reusable agent capabilities)",
- summary: "Browse, install, publish, and update agent skills; installed skills appear as \"/\" slash commands and are shared across Claude Code and Codex.",
- content: "Skills are reusable agent capabilities you package as a folder and load into your sessions. They're managed on the same page as Plugins — **Skills** and **Plugins** are two tabs of one management surface (the Skills tab is the in-app browser for finding, installing, publishing, and updating skills).\n\n**Skills work with both agents:**\n\n- Skills are **engine-shared** — the same installed skill is available to both Claude Code and Codex, so you install it once.\n\n**Where skills live on disk:**\n\n- Global (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\\Users\\<you>\\`.\n- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.\n- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.\n\n**Importing a local skill:**\n\n- On the Skills page, use **Import skill** (top-right) to pick a `.zip` package or a standalone `SKILL.md` file.\n- A zip must contain a `SKILL.md` (at the package root, or inside a single top-level folder). The YAML frontmatter must include non-empty `name` and `description` fields; `name` must match `^[a-z0-9-]{1,200}$`.\n- You then choose where to install: global, a known project, or another directory. Cindy extracts metadata from the file automatically and lists the skill with that name and description.\n- Imported skills can be uninstalled from the detail page, and you can publish them to SkillHub later if you want.\n\n**Using an installed skill:**\n\n- Type `/` in the composer to open the slash-command palette; your installed skills show up there alongside built-in and agent commands. Pick one to run it.\n\n**Publishing your own skill:**\n\n- Find the publish action on the Skills page and point it at the skill's local folder. It zips the folder and uploads it — reading your directory in place, without copying or moving anything.\n- On first publish, you set the skill's **visibility**: PUBLIC (anyone in the org) or DEPARTMENT_SCOPED (only the departments you choose).\n- The local registry records what you published, so the app knows it's \"yours\" for future updates.\n\n**Updating an already-published skill:**\n\n- On your own skill's detail page you'll see a **发布新版本** (Publish New Version) button.\n- Edit the local folder however you want and publish — the version is **auto-incremented server-side**, you don't pick a number.\n- **Old versions stay live alongside the new one.** Users who already installed an older version keep it until they choose to update.\n- The display name and description are sent on every republish, so editing those metadata fields just means doing a republish.\n\n**Managing an already-published skill:**\n\n- Change who can see or use your skill from the management menu — public, shared with selected teams / departments, or private to you.\n- **Unpublish** makes it private again and returns ownership to your personal scope; it does not remove copies other users already installed.\n- **Authorship is fixed.** Only the original author's account can publish new versions of a given skill (enforced server-side as `NOT_AUTHOR`).\n\n**Browsing and installing others' skills:**\n\n- The marketplace lets you install skills into your global skills directory. You can request a specific version on install; the local registry tracks which version you have.\n\n**Notes:**\n\n- A skill folder without a `SKILL.md` at its root won't be picked up (lowercase `skill.md` is also accepted).\n- Project-scoped skills only show up in sessions whose working directory matches — useful for skills tied to a particular repo's conventions.\n- Editing files inside an installed skill folder takes effect on the next session start; you don't need to reinstall.\n- Uninstalling only removes your local copy. For your own published skills, use unpublish or manage visibility to change market availability.",
+ summary: "Browse, install, disable, uninstall, publish, and update agent skills; installed skills appear as \"/\" slash commands and are shared across Claude Code and Codex.",
+ content: "Skills are reusable agent capabilities you package as a folder and load into your sessions. They're managed on the same page as Plugins — **Skills** and **Plugins** are two tabs of one management surface (the Skills tab is the in-app browser for finding, installing, publishing, and updating skills).\n\n**Skills work with both agents:**\n\n- Skills are **engine-shared** — the same installed skill is available to both Claude Code and Codex, so you install it once.\n\n**Where skills live on disk:**\n\n- Global (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\\Users\\<you>\\`.\n- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.\n- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.\n\n**Importing a local skill:**\n\n- On the Skills page, use **Import skill** (top-right) to pick a `.zip` package or a standalone `SKILL.md` file.\n- A zip must contain a `SKILL.md` (at the package root, or inside a single top-level folder). The YAML frontmatter must include non-empty `name` and `description` fields; `name` must match `^[a-z0-9-]{1,200}$`.\n- You then choose where to install: global, a known project, or another directory. Cindy extracts metadata from the file automatically and lists the skill with that name and description.\n- Imported skills can be uninstalled from the detail page, and you can publish them to SkillHub later if you want.\n\n**Using an installed skill:**\n\n- Hover over a local skill in the `/` suggestions and choose **View skill details** in its information panel to open that exact skill. This does not insert or send the command.\n\n- Type `/` in the composer to open the slash-command palette; your installed skills show up there alongside built-in and agent commands. Pick one to run it.\n\n**Disabling or uninstalling a local skill (Desktop):**\n\n- Open a skill's detail page to use the switch in the top action bar. For a market skill installed in multiple locations, select the local copy from the location dropdown beside the switch. Turning it off keeps the files and removes the skill from Cindy's command palette. New or restarted Claude Code, Codex, and Pi agents apply that choice; an already-running agent keeps its existing context.\n- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.\n- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.\n- External source imports remove only their discovery links and keep the external source files. Package-owned or built-in skills must be removed through their owning package; their uninstall action is unavailable here.\n- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If only metadata/link cleanup fails, the notice offers **Retry cleanup** in the current app run.\n\n**Publishing your own skill:**\n\n- Find the publish action on the Skills page and point it at the skill's local folder. It zips the folder and uploads it — reading your directory in place, without copying or moving anything.\n- On first publish, you set the skill's **visibility**: PUBLIC (anyone in the org) or DEPARTMENT_SCOPED (only the departments you choose).\n- The local registry records what you published, so the app knows it's \"yours\" for future updates.\n\n**Updating an already-published skill:**\n\n- On your own skill's detail page you'll see a **发布新版本** (Publish New Version) button.\n- Edit the local folder however you want and publish — the version is **auto-incremented server-side**, you don't pick a number.\n- **Old versions stay live alongside the new one.** Users who already installed an older version keep it until they choose to update.\n- The display name and description are sent on every republish, so editing those metadata fields just means doing a republish.\n\n**Managing an already-published skill:**\n\n- Change who can see or use your skill from the management menu — public, shared with selected teams / departments, or private to you.\n- **Unpublish** makes it private again and returns ownership to your personal scope; it does not remove copies other users already installed.\n- **Authorship is fixed.** Only the original author's account can publish new versions of a given skill (enforced server-side as `NOT_AUTHOR`).\n\n**Browsing and installing others' skills:**\n\n- The marketplace lets you install skills into your global skills directory. You can request a specific version on install; the local registry tracks which version you have.\n\n**Notes:**\n\n- A skill folder without a `SKILL.md` at its root won't be picked up (lowercase `skill.md` is also accepted).\n- Project-scoped skills only show up in sessions whose working directory matches — useful for skills tied to a particular repo's conventions.\n- Editing files inside an installed skill folder takes effect on the next session start; you don't need to reinstall.\n- Uninstalling only removes your local copy. For your own published skills, use unpublish or manage visibility to change market availability.",
},
{
id: "updates-and-about",
diff --git a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
new file mode 100644
index 0000000000..9312e1aea1
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
@@ -0,0 +1,30 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterAll, describe, expect, it, vi } from 'vitest';
+
+const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-skill-preferences-'));
+vi.mock('electron', () => ({ app: { getPath: () => root } }));
+vi.mock('../../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));
+afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
+
+describe('Skill activation preferences', () => {
+ it('defaults to native behavior, persists only disabled paths, and preserves concurrent changes', async () => {
+ const { isCindySkillEnabled, setCindySkillEnabled, readDisabledSkillPaths, skillActivationKey } = await import('../activationPreferences');
+ const a = path.join(root, 'project-a', 'skill');
+ const b = path.join(root, 'project-b', 'skill');
+ expect(isCindySkillEnabled(a)).toBe(true);
+ await Promise.all([setCindySkillEnabled(a, false), setCindySkillEnabled(b, false)]);
+ expect(new Set(readDisabledSkillPaths())).toEqual(new Set([skillActivationKey(a), skillActivationKey(b)]));
+ await setCindySkillEnabled(a, true);
+ expect(isCindySkillEnabled(a)).toBe(true);
+ expect(isCindySkillEnabled(b)).toBe(false);
+ await expect(setCindySkillEnabled(a, false, () => false)).rejects.toThrow('context changed');
+ expect(isCindySkillEnabled(a)).toBe(true);
+ vi.resetModules();
+ const reloaded = await import('../activationPreferences');
+ expect(reloaded.isCindySkillEnabled(b)).toBe(false);
+ await reloaded.setCindySkillEnabled(b, true);
+ expect(reloaded.readDisabledSkillPaths()).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
index a2a9e2b503..6c01061924 100644
--- a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
@@ -23,6 +23,13 @@ vi.mock('electron', () => ({
app: {
getPath: vi.fn(() => path.join(TEST_ROOT, 'userData')),
},
+ shell: {
+ trashItem: vi.fn(async (source: string) => {
+ const trash = path.join(TEST_ROOT, 'trash', crypto.randomUUID());
+ fs.mkdirSync(path.dirname(trash), { recursive: true });
+ await fs.promises.rename(source, trash);
+ }),
+ },
net: {
fetch: vi.fn(),
},
@@ -149,17 +156,130 @@ async function setupInstallDownload(skillName: string, zipBuf: Uint8Array) {
}
describe('skillhub/installService', () => {
- beforeEach(() => {
+ beforeEach(async () => {
vi.resetModules();
vi.clearAllMocks();
removeTestRoot();
fs.mkdirSync(TEST_ROOT, { recursive: true });
+ const { projectWorkingDirFromSkillPath } = await import('../../maker-host/shared-global-skills.js');
+ vi.mocked(projectWorkingDirFromSkillPath).mockReturnValue(null);
+ const { getAppCapabilities } = await import('../../appCapabilities.js');
+ vi.mocked(getAppCapabilities).mockReturnValue({
+ canUseCindyAccountServices: true, canUseCindyGateway: true, canUseDeviceLink: true,
+ canUseSkillHubCloud: true, canUseCindyOAuthBroker: true, canUseCindyHeartbeat: true,
+ });
});
afterAll(() => {
removeTestRoot();
});
+ async function localFixture(name: string) {
+ const source = path.join(TEST_ROOT, '.agents', 'skills', name);
+ fs.mkdirSync(source, { recursive: true });
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'fixture content');
+ const { inspectLocalSkillTarget } = await import('../localSkillTarget');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.getInstall).mockResolvedValue(null);
+ vi.mocked(registryService.readManifest).mockResolvedValue(null);
+ return { source, target: inspectLocalSkillTarget(source, [source])! };
+ }
+
+ it('trashes an unregistered scanned skill and clears its Cindy override', async () => {
+ const { source, target } = await localFixture('unregistered');
+ const { setCindySkillEnabled, isCindySkillEnabled } = await import('../activationPreferences');
+ const { uninstall } = await import('../installService');
+ await setCindySkillEnabled(source, false);
+ expect(await uninstall(source, target)).toEqual({ success: true });
+ expect(fs.existsSync(source)).toBe(false);
+ expect(isCindySkillEnabled(source)).toBe(true);
+ });
+
+ it('preserves files, registry and disabled state when system trash fails', async () => {
+ const { source, target } = await localFixture('trash-failure');
+ const { shell } = await import('electron');
+ const { registryService } = await import('../registry');
+ const { setCindySkillEnabled, isCindySkillEnabled } = await import('../activationPreferences');
+ const { uninstall } = await import('../installService');
+ await setCindySkillEnabled(source, false);
+ vi.mocked(shell.trashItem).mockRejectedValueOnce(new Error('trash unavailable'));
+ expect((await uninstall(source, target)).success).toBe(false);
+ expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('fixture content');
+ expect(registryService.removeInstall).not.toHaveBeenCalled();
+ expect(isCindySkillEnabled(source)).toBe(false);
+ });
+
+ it('removes only an external import link and leaves its source untouched', async () => {
+ const source = path.join(TEST_ROOT, 'external', 'shared');
+ const alias = path.join(TEST_ROOT, '.agents', 'skills', 'shared');
+ fs.mkdirSync(source, { recursive: true });
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'external content');
+ makeDirectoryLink(alias, source);
+ const { inspectLocalSkillTarget } = await import('../localSkillTarget');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.getInstall).mockResolvedValue(null);
+ vi.mocked(registryService.readManifest).mockResolvedValue(null);
+ const { uninstall } = await import('../installService');
+ const { shell } = await import('electron');
+ const target = inspectLocalSkillTarget(source, [alias])!;
+ expect(target.linkOnly).toBe(true);
+ expect(await uninstall(source, target)).toEqual({ success: true });
+ expect(shell.trashItem).toHaveBeenCalledWith(alias);
+ expect(fs.existsSync(alias)).toBe(false);
+ expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('external content');
+ });
+
+ it('rejects a source replaced while registry inspection is pending', async () => {
+ const { source, target } = await localFixture('replaced');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.getInstall).mockImplementationOnce(async () => {
+ fs.renameSync(source, source + '-old');
+ fs.mkdirSync(source);
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'replacement');
+ return null;
+ });
+ const { uninstall } = await import('../installService');
+ const { shell } = await import('electron');
+ expect((await uninstall(source, target)).success).toBe(false);
+ expect(shell.trashItem).not.toHaveBeenCalled();
+ expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('replacement');
+ });
+
+ it('retries metadata cleanup without trashing a second time', async () => {
+ const { source, target } = await localFixture('cleanup-retry');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.getInstall).mockResolvedValue({
+ origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ });
+ vi.mocked(registryService.removeInstall).mockRejectedValueOnce(new Error('disk unavailable')).mockResolvedValue(undefined);
+ const { uninstall, retryUninstallCleanup } = await import('../installService');
+ const { shell } = await import('electron');
+ const result = await uninstall(source, target);
+ expect(result.success).toBe(true);
+ if (!result.success) throw new Error('uninstall failed');
+ expect(result.cleanupToken).toBeTruthy();
+ expect(await retryUninstallCleanup(result.cleanupToken!, () => true)).toBe(true);
+ expect(shell.trashItem).toHaveBeenCalledTimes(1);
+ expect(registryService.removeInstall).toHaveBeenCalledTimes(2);
+ });
+
+ it('leaves a restored installation untouched when retrying cleanup', async () => {
+ const { source, target } = await localFixture('cleanup-restored');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.getInstall).mockResolvedValue({
+ origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ });
+ vi.mocked(registryService.removeInstall).mockRejectedValueOnce(new Error('disk unavailable'));
+ const { uninstall, retryUninstallCleanup } = await import('../installService');
+ const result = await uninstall(source, target);
+ if (!result.success || !result.cleanupToken) throw new Error('expected retry receipt');
+ fs.mkdirSync(source);
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'restored');
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ expect(registryService.removeInstall).toHaveBeenCalledTimes(1);
+ expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('restored');
+ });
+
it('keeps the previous install intact when extraction fails during forced update', async () => {
const finalDir = path.join(TEST_ROOT, 'skills', 'broken-skill');
fs.mkdirSync(finalDir, { recursive: true });
@@ -204,7 +324,7 @@ describe('skillhub/installService', () => {
expect(fs.readFileSync(path.join(finalDir, 'SKILL.md'), 'utf-8')).toBe('old content');
});
- it('rejects uninstall outside a cloud capability boundary for market installs', async () => {
+ it('trashes a market install without requiring cloud capabilities', async () => {
const finalDir = path.join(TEST_ROOT, '.agents', 'skills', 'market-only');
fs.mkdirSync(finalDir, { recursive: true });
fs.writeFileSync(path.join(finalDir, 'SKILL.md'), 'content', 'utf-8');
@@ -220,7 +340,7 @@ describe('skillhub/installService', () => {
updatedAt: 1,
origin: 'installed',
});
- vi.mocked(getAppCapabilities).mockReturnValueOnce({
+ vi.mocked(getAppCapabilities).mockReturnValue({
canUseCindyAccountServices: false,
canUseCindyGateway: false,
canUseDeviceLink: false,
@@ -229,12 +349,8 @@ describe('skillhub/installService', () => {
canUseCindyHeartbeat: false,
});
- await expect(uninstall(finalDir)).resolves.toEqual({
- success: false,
- errorCode: 'AUTH_REQUIRED',
- message: 'SkillHub 卸载需要 Cindy 云端账号',
- });
- expect(fs.existsSync(finalDir)).toBe(true);
+ await expect(uninstall(finalDir)).resolves.toEqual({ success: true });
+ expect(fs.existsSync(finalDir)).toBe(false);
});
it('allows uninstalling an imported skill without cloud login', async () => {
@@ -248,7 +364,7 @@ describe('skillhub/installService', () => {
const { uninstall } = await import('../installService');
vi.mocked(getCurrentUserId).mockReturnValueOnce(null);
- vi.mocked(registryService.getInstall).mockResolvedValueOnce({
+ vi.mocked(registryService.getInstall).mockResolvedValue({
version: '0.1.0',
authorId: '',
folderHash: 'hash',
@@ -957,7 +1073,7 @@ describe('skillhub/installService', () => {
});
});
- it('rejects local mode uninstall of a market-installed skill while cloud is unavailable', async () => {
+ it('trashes a market install in local mode while cloud is unavailable', async () => {
const finalDir = path.join(TEST_ROOT, 'local-project', '.agents', 'skills', 'local-skill');
fs.mkdirSync(finalDir, { recursive: true });
fs.writeFileSync(path.join(finalDir, 'SKILL.md'), 'content', 'utf-8');
@@ -976,7 +1092,7 @@ describe('skillhub/installService', () => {
updatedAt: 1,
origin: 'installed',
});
- vi.mocked(getAppCapabilities).mockReturnValueOnce({
+ vi.mocked(getAppCapabilities).mockReturnValue({
canUseCindyAccountServices: false,
canUseCindyGateway: false,
canUseDeviceLink: false,
@@ -987,11 +1103,8 @@ describe('skillhub/installService', () => {
const result = await uninstall(finalDir);
- expect(result).toMatchObject({
- success: false,
- errorCode: 'AUTH_REQUIRED',
- });
- expect(fs.existsSync(finalDir)).toBe(true);
+ expect(result).toEqual({ success: true });
+ expect(fs.existsSync(finalDir)).toBe(false);
vi.mocked(getCurrentDataOwnerId).mockReturnValue('user-1');
});
@@ -1016,7 +1129,7 @@ describe('skillhub/installService', () => {
const { registryService } = await import('../registry');
const { uninstall } = await import('../installService');
vi.mocked(getCurrentUserId).mockReturnValue('user-1');
- vi.mocked(registryService.getInstall).mockResolvedValue(null);
+ vi.mocked(registryService.getInstall).mockImplementation(async (_name, installPath) => installPath === logicalDir ? registryEntry : null);
vi.mocked(registryService.readManifest).mockResolvedValue({
schemaVersion: 1,
skillName,
diff --git a/apps/desktop/src/main/skillhub/__tests__/localSkillTarget.test.ts b/apps/desktop/src/main/skillhub/__tests__/localSkillTarget.test.ts
new file mode 100644
index 0000000000..380d1597a8
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/__tests__/localSkillTarget.test.ts
@@ -0,0 +1,62 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterAll, describe, expect, it } from 'vitest';
+import { inspectLocalSkillTarget, isLocalSkillTargetCurrent } from '../localSkillTarget';
+
+const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-local-skill-target-'));
+afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
+function directory(...parts: string[]): string {
+ const dir = path.join(root, ...parts);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), 'test');
+ return dir;
+}
+
+describe('local Skill removal targets', () => {
+ it('accepts an unregistered local Skill and rejects its enclosing discovery root', () => {
+ const dir = directory('.agents', 'skills', 'mine');
+ const target = inspectLocalSkillTarget(dir, [dir]);
+ expect(target?.operationPath).toBe(fs.realpathSync.native(dir));
+ expect(target?.linkOnly).toBe(false);
+ expect(isLocalSkillTargetCurrent(target!)).toBe(true);
+ expect(inspectLocalSkillTarget(path.dirname(dir), [path.dirname(dir)])).toBeNull();
+ });
+
+ it('does not permit deleting a package root or a system Skill', () => {
+ const packageRoot = directory('package');
+ expect(inspectLocalSkillTarget(packageRoot, [packageRoot])).toBeNull();
+ const system = directory('codex-home', 'skills', '.system', 'builtin');
+ expect(inspectLocalSkillTarget(system, [system])).toBeNull();
+ });
+
+ it('detects replacement of a directory after the confirmation snapshot', () => {
+ const dir = directory('.claude', 'skills', 'replace');
+ const target = inspectLocalSkillTarget(dir, [dir])!;
+ fs.renameSync(dir, `${dir}-old`);
+ directory('.claude', 'skills', 'replace');
+ expect(isLocalSkillTargetCurrent(target)).toBe(false);
+ });
+
+ it('treats a standalone Markdown Skill as one file', () => {
+ const file = path.join(root, '.pi', 'skills', 'standalone.md');
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, '---\nname: standalone\n---\nSkill');
+ expect(inspectLocalSkillTarget(file, [file])?.operationPath).toBe(fs.realpathSync.native(file));
+ });
+
+ it('removes only a link into an external checkout and detects retargeting', (ctx) => {
+ const source = directory('external-source');
+ const link = path.join(root, '.agents', 'skills', 'external');
+ fs.mkdirSync(path.dirname(link), { recursive: true });
+ try { fs.symlinkSync(source, link, process.platform === 'win32' ? 'junction' : 'dir'); }
+ catch { ctx.skip(); return; }
+ const target = inspectLocalSkillTarget(source, [link])!;
+ expect(target.linkOnly).toBe(true);
+ expect(target.operationPath).toBe(link);
+ expect(target.sourcePath).toBe(fs.realpathSync.native(source));
+ fs.unlinkSync(link);
+ fs.symlinkSync(directory('other-external'), link, process.platform === 'win32' ? 'junction' : 'dir');
+ expect(isLocalSkillTargetCurrent(target)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 597cb17b6c..f54297f92d 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -1,4 +1,12 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-ipc-management-'));
+afterAll(() => fs.rmSync(fixtureRoot, { recursive: true, force: true }));
+const setCindySkillEnabled = vi.fn(async () => undefined);
+vi.mock('../activationPreferences', () => ({ setCindySkillEnabled }));
const handlers = new Map<string, (...args: unknown[]) => unknown>();
const showOpenDialog = vi.fn();
@@ -603,22 +611,52 @@ describe('registerSkillhubIpc usage handlers', () => {
});
});
- it('refreshes the Codex cwd cache after uninstalling a project skill', async () => {
- installServiceMocks.uninstall.mockResolvedValueOnce({
- success: true,
- projectWorkingDir: '/project',
- });
+ async function scanLocalFixture() {
+ const project = fs.mkdtempSync(path.join(fixtureRoot, 'project-'));
+ const source = path.join(project, '.agents', 'skills', 'local');
+ fs.mkdirSync(source, { recursive: true });
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'local skill');
+ const absolutePath = fs.realpathSync.native(source);
+ getAllowedProjectRoots.mockResolvedValue([project]);
+ scanAllSkills.mockResolvedValue({ skills: [{
+ kind: 'skill', scope: 'project', name: 'local', absolutePath,
+ discoveredPath: source, projectRoot: project,
+ }], sources: [] });
+ const event = { sender: { id: 71, once: vi.fn() } };
+ await handlers.get('skillhub:scan')!(event, { projects: [{ projectRoot: project, hash: 'fixture' }] });
+ return { event, absolutePath, project };
+ }
+
+ it('refreshes the Codex cwd cache after uninstalling a granted project skill', async () => {
+ const { event, absolutePath, project } = await scanLocalFixture();
+ installServiceMocks.uninstall.mockResolvedValueOnce({ success: true, projectWorkingDir: project });
listAgentSkills.mockResolvedValueOnce({ skills: [] });
- const handler = handlers.get('skillhub:uninstall');
+ expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({ success: true });
+ expect(listAgentSkills).toHaveBeenCalledWith('codex', { workingDir: project, forceReload: true });
+ expect(installServiceMocks.uninstall).toHaveBeenCalledWith(absolutePath,
+ expect.objectContaining({ sourcePath: absolutePath, linkOnly: false }), expect.any(Function));
+ });
- const result = await handler?.({}, {
- absolutePath: '/project/.agents/skills/project-skill',
- });
+ it('allows toggling an unregistered local Skill and rejects another renderer', async () => {
+ const { event, absolutePath } = await scanLocalFixture();
+ const handler = handlers.get('skillhub:set-enabled')!;
+ expect(await handler(event, { absolutePath, enabled: false })).toEqual({ cindyEnabled: false });
+ expect(setCindySkillEnabled).toHaveBeenCalledWith(absolutePath, false, expect.any(Function));
+ await expect(handler({ sender: { id: 72 } }, { absolutePath, enabled: false }))
+ .rejects.toThrow('PRECONDITION_FAILED');
+ expect(setCindySkillEnabled).toHaveBeenCalledTimes(1);
+ });
- expect(result).toEqual({ success: true });
- expect(listAgentSkills).toHaveBeenCalledWith('codex', {
- workingDir: '/project',
- forceReload: true,
- });
+ it('rejects owner changes and replaced sources before mutation', async () => {
+ const { event, absolutePath } = await scanLocalFixture();
+ const uninstall = handlers.get('skillhub:uninstall')!;
+ getCurrentDataOwnerId.mockReturnValue('other-owner');
+ await expect(uninstall(event, { absolutePath })).rejects.toThrow('PRECONDITION_FAILED');
+ getCurrentDataOwnerId.mockReturnValue('local-v1');
+ fs.renameSync(absolutePath, `${absolutePath}-old`);
+ fs.mkdirSync(absolutePath);
+ fs.writeFileSync(path.join(absolutePath, 'SKILL.md'), 'replacement');
+ await expect(uninstall(event, { absolutePath })).rejects.toThrow('PRECONDITION_FAILED');
+ expect(installServiceMocks.uninstall).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/skillhub/activationPreferences.ts b/apps/desktop/src/main/skillhub/activationPreferences.ts
new file mode 100644
index 0000000000..0dbd67c796
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/activationPreferences.ts
@@ -0,0 +1,50 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { app } from 'electron';
+import { createLogger } from '../logger';
+import { createOverrideSettingsFile } from '../maker-host/override-settings-file';
+
+/** Device/profile-local user intent; independent of cloud installs and account changes. */
+interface SkillActivationPreferences { disabledPaths: string[] }
+
+export function skillActivationKey(source: string): string {
+ let resolved = path.resolve(source);
+ try { resolved = fs.realpathSync.native(resolved); } catch { /* Allow cleanup after removal. */ }
+ if (path.basename(resolved).toLowerCase() === 'skill.md') resolved = path.dirname(resolved);
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+}
+
+const store = createOverrideSettingsFile<SkillActivationPreferences>({
+ filePath: () => path.join(app.getPath('userData'), 'skillhub', 'activation-preferences.json'),
+ defaults: { disabledPaths: [] },
+ normalize: (raw) => {
+ const values = (raw as Partial<SkillActivationPreferences> | null)?.disabledPaths;
+ return { disabledPaths: Array.isArray(values)
+ ? [...new Set(values.filter((v): v is string => typeof v === 'string' && path.isAbsolute(v)))].sort()
+ : [] };
+ },
+ log: createLogger('skillhub:activation'),
+ label: 'skill activation',
+ logLoadedValue: false,
+ preserveUnreadableFile: true,
+});
+
+export function readDisabledSkillPaths(): readonly string[] {
+ store.invalidateIfChanged();
+ return store.read().disabledPaths;
+}
+
+export function isCindySkillEnabled(source: string): boolean {
+ return !readDisabledSkillPaths().includes(skillActivationKey(source));
+}
+
+export async function setCindySkillEnabled(source: string, enabled: boolean, canMutate: () => boolean = () => true): Promise<void> {
+ const key = skillActivationKey(source);
+ await store.updateAtomic(({ value }) => {
+ if (!canMutate()) throw new Error('Skill mutation context changed');
+ return { disabledPaths: enabled
+ ? value.disabledPaths.filter((item) => item !== key)
+ : [...new Set([...value.disabledPaths, key])].sort(),
+ };
+ });
+}
diff --git a/apps/desktop/src/main/skillhub/installService.ts b/apps/desktop/src/main/skillhub/installService.ts
index 1080dfab61..8dd2ffddb2 100644
--- a/apps/desktop/src/main/skillhub/installService.ts
+++ b/apps/desktop/src/main/skillhub/installService.ts
@@ -5,7 +5,7 @@
* install: Hub broker download info → fetch signed zip → sha256 校验
* → JSZip 解压到 staging → final switch 到目标位置
* → registry.addInstall → best-effort Claude symlink → emit done
- * uninstall: 路径白名单校验 → rm 目标目录 → registry.removeInstall
+ * uninstall: 路径白名单校验 → 系统回收站 → registry.removeInstall
*
* 安装目标:
* - 未传 installPath → 默认 `~/.agents/skills/<name>/`(双引擎共享)
@@ -26,7 +26,9 @@ import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { app, net } from 'electron';
+import { app, net, shell } from 'electron';
+import { isLocalSkillTargetCurrent, type LocalSkillTarget } from './localSkillTarget';
+import { isCindySkillEnabled, setCindySkillEnabled } from './activationPreferences';
import JSZip from 'jszip';
import { skillhubApiFetch } from './hubApi';
import { getCurrentDataOwnerId, getCurrentUserId } from '../authManager';
@@ -44,7 +46,7 @@ import {
prepareSharedProjectSkillLinks,
projectWorkingDirFromSkillPath,
} from '../maker-host/shared-global-skills.js';
-import { clearIgnoredAutoSyncSkill, ignoreAutoSyncSkill, isKnownAutoSyncCandidateSkill } from './autoSyncPreferences';
+import { clearIgnoredAutoSyncSkill, ignoreAutoSyncSkill, listIgnoredAutoSyncSkills, isKnownAutoSyncCandidateSkill } from './autoSyncPreferences';
import { withSkillhubCatalogScope, type SkillhubCatalogScope } from '../../shared/skillhubCatalog';
import { createLogger } from '../logger';
@@ -138,7 +140,7 @@ export type InstallResult =
| { success: false; errorCode: InstallErrorCode; message: string };
export type UninstallResult =
- | ({ success: true } & ProjectSkillMutationMetadata)
+ | ({ success: true; cleanupToken?: string } & ProjectSkillMutationMetadata)
| { success: false; errorCode: InstallErrorCode; message: string };
// ── 内部状态:记录每个 name 当前正在跑的 AbortController ────────────────────────
@@ -717,6 +719,14 @@ export async function install(
return { success: false, errorCode: 'CANCELLED', message: '已取消' };
}
+ if (!rollbackState.backupDir && !isCindySkillEnabled(finalDir)) {
+ try { await setCindySkillEnabled(finalDir, true, () => !checkAbort()); }
+ catch {
+ await rollbackFinalSwitch(finalDir, rollbackState);
+ return { success: false, errorCode: 'WRITE_FAILED', message: 'Could not reset Skill state' };
+ }
+ }
+
// 7) 同步 registry
onProgress({ phase: 'registering', name: p.name });
if (checkAbort()) {
@@ -914,18 +924,13 @@ export async function install(
// ── uninstall ───────────────────────────────────────────────────────────────
-/**
- * 卸载一个 skill。
- *
- * 防御:absolutePath 必须落在受支持的 skill discovery root 下 —— 拒绝删除任意路径。
- * UI 层(F-UI-4)在按钮分流时已确保"未注册的本地技能"不显示卸载按钮,这层是双保险。
- *
- * 鉴权:
- * - origin=imported / learned → 本地产物(导入 / 蒸馏),不要求登录 / SkillHub 云能力
- * - 其它(市场 installed 等)→ 仍要求数据空间 + canUseSkillHubCloud
+/** Move a registered installation or Main-scanned standalone Skill to the system trash.
+ * Local management is available offline. External imports remove only their links.
*/
export async function uninstall(
absolutePath: string,
+ target?: LocalSkillTarget,
+ canMutate: () => boolean = () => true,
): Promise<UninstallResult> {
// 防御:resolve 后验证路径是精确的 skill 根目录(只允许一层 slug,防 traversal)
let resolved: string;
@@ -936,7 +941,7 @@ export async function uninstall(
}
const normResolved = resolved.replace(/\\/g, '/');
// 必须匹配 <prefix>/.{claude,agents,codex}/skills/<slug> 形式,slug 不含 /
- if (!/\/(\.(claude|agents|codex)\/skills|codex-home\/skills(\/\.system)?)\/[^/]+$/.test(normResolved)) {
+ if (!target && !/\/(\.(claude|agents|codex)\/skills|codex-home\/skills)\/[^/.][^/]*$/.test(normResolved)) {
return { success: false, errorCode: 'INTERNAL', message: 'absolutePath 不在合法 skill 目录下' };
}
@@ -950,26 +955,13 @@ export async function uninstall(
return { success: false, errorCode: 'INTERNAL', message: skillLockBusyMessage(skillName) };
}
try {
- // 先读 registry 再判鉴权:本地导入 / 蒸馏产物允许离线卸载。
+ // Keep the exact registry identity for metadata cleanup after trash succeeds.
const registryMatch = await findRegistryInstallForPath(skillName, absolutePath, resolved);
- if (!registryMatch) {
- return { success: false, errorCode: 'INTERNAL', message: '该 skill 无安装记录,拒绝删除' };
+ if (!registryMatch && !target) {
+ return { success: false, errorCode: 'INTERNAL', message: 'No installation record or current local Skill grant' };
}
-
- const origin = registryMatch.entry.origin;
- const isOfflineLocalOrigin = origin === 'imported' || origin === 'learned';
- if (!isOfflineLocalOrigin) {
- const ownerId = getCurrentDataOwnerId();
- if (!ownerId) {
- return { success: false, errorCode: 'AUTH_REQUIRED', message: '无可用数据空间' };
- }
- if (!getAppCapabilities().canUseSkillHubCloud) {
- return {
- success: false,
- errorCode: 'AUTH_REQUIRED',
- message: 'SkillHub 卸载需要 Cindy 云端账号',
- };
- }
+ if (target && (target.sourcePath !== resolved || !isLocalSkillTargetCurrent(target))) {
+ return { success: false, errorCode: 'INTERNAL', message: 'Skill source changed; refresh and retry' };
}
const cloudUserId = getCurrentUserId();
@@ -979,6 +971,8 @@ export async function uninstall(
skillName,
cloudUserId,
registryMatch,
+ target,
+ canMutate,
);
} finally {
releaseLock();
@@ -1043,68 +1037,120 @@ async function uninstallLocked(
resolved: string,
skillName: string,
cloudUserId: string | null,
- registryMatch: RegistryInstallMatch,
+ registryMatch: RegistryInstallMatch | null,
+ target?: LocalSkillTarget,
+ canMutate: () => boolean = () => true,
): Promise<UninstallResult> {
- const { installPath: registryInstallPath, entry: registryEntry } = registryMatch;
-
- if (!(await pathExists(resolved))) {
- // 目录已经不在 → 静默成功,顺便清 registry 残留
- await registryService.removeInstall(skillName, registryInstallPath).catch(() => {});
- if (cloudUserId && await shouldRecordAutoSyncIgnore(skillName, registryEntry, cloudUserId)) {
- await ignoreAutoSyncSkill(skillName, cloudUserId).catch((err) => {
- log.warn('[skillInstall] record auto-sync ignore failed:', err);
- });
- }
- const projectWorkingDir = await reconcileProjectSkillLinksForPaths(resolved, absolutePath);
- return { success: true, ...(projectWorkingDir ? { projectWorkingDir } : {}) };
+ const registryEntry = registryMatch?.entry;
+
+ if (!canMutate()) return { success: false, errorCode: 'CANCELLED', message: 'Skill mutation context changed' };
+ const recordIgnore = !!(cloudUserId && registryEntry && await shouldRecordAutoSyncIgnore(skillName, registryEntry, cloudUserId));
+ const wasIgnored = recordIgnore && (await listIgnoredAutoSyncSkills(cloudUserId!)).has(skillName);
+ // Persist the user's opt-out before touching files, so auto-sync cannot recreate the Skill.
+ if (recordIgnore && !wasIgnored) {
+ try { await ignoreAutoSyncSkill(skillName, cloudUserId!); }
+ catch { return { success: false, errorCode: 'WRITE_FAILED', message: 'Could not save uninstall preference' }; }
}
-
+ const candidates = [...new Set([
+ ...(target?.aliases ?? []), absolutePath,
+ path.join(os.homedir(), '.claude', 'skills', skillName),
+ path.join(os.homedir(), '.codex', 'skills', skillName),
+ path.join(os.homedir(), '.agents', 'skills', skillName),
+ ])];
+ // Capture exact links while their target still exists. Never sweep unrelated broken links.
+ const links = candidates.flatMap((candidate) => {
+ try {
+ return fs.lstatSync(candidate).isSymbolicLink() && fs.realpathSync.native(candidate) === resolved
+ ? [{ path: candidate, value: fs.readlinkSync(candidate), ino: fs.lstatSync(candidate).ino }] : [];
+ } catch { return []; }
+ });
try {
- await fs.promises.rm(resolved, { recursive: true, force: true });
+ const exists = fs.existsSync(resolved);
+ if (!canMutate() || (target && !isLocalSkillTargetCurrent(target))) throw new Error('Skill source changed; refresh and retry');
+ if (exists) await shell.trashItem(target?.operationPath ?? resolved);
} catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- return { success: false, errorCode: 'WRITE_FAILED', message };
+ if (recordIgnore && !wasIgnored) {
+ await clearIgnoredAutoSyncSkill(skillName, cloudUserId!).catch((error) => log.warn('[skillInstall] restore auto-sync preference failed:', error));
+ }
+ return { success: false, errorCode: 'WRITE_FAILED', message: err instanceof Error ? err.message : String(err) };
}
- // 如果原始路径是 symlink 指向已删目录,也一并清掉
- if (resolved !== path.resolve(absolutePath)) {
- await fs.promises.unlink(absolutePath).catch(() => {});
- }
+ const cleanup: UninstallCleanup = {
+ skillName, resolved, operationPath: target?.operationPath ?? resolved, absolutePath,
+ registryMatch, links,
+ };
+ const complete = await finishUninstallCleanup(cleanup, canMutate);
+ const cleanupToken = complete ? undefined : crypto.randomUUID();
+ if (cleanupToken) pendingUninstallCleanup.set(cleanupToken, cleanup);
+ const projectWorkingDir = await reconcileProjectSkillLinksForPaths(resolved, absolutePath);
+ return { success: true, ...(cleanupToken ? { cleanupToken } : {}),
+ ...(projectWorkingDir ? { projectWorkingDir } : {}) };
+}
- // 删 registry 条目。失败仅 warn,因为文件已删,scanner 会孤儿清理。
+interface UninstallCleanup {
+ skillName: string;
+ resolved: string;
+ operationPath: string;
+ absolutePath: string;
+ registryMatch: RegistryInstallMatch | null;
+ links: Array<{ path: string; value: string; ino: number }>;
+}
+
+// Only Main-issued receipts can retry metadata/link cleanup; no second trash operation.
+const pendingUninstallCleanup = new Map<string, UninstallCleanup>();
+
+async function finishUninstallCleanup(cleanup: UninstallCleanup, canMutate: () => boolean): Promise<boolean> {
+ const { skillName, resolved, operationPath, registryMatch, links } = cleanup;
+ if (!canMutate()) return false;
+ // Restore/reinstall wins over a delayed cleanup. Never alter a new installation.
+ if (fs.existsSync(operationPath)) return true;
+ let complete = true;
try {
- await registryService.removeInstall(skillName, registryInstallPath);
+ if (registryMatch) {
+ const current = await registryService.getInstall(skillName, registryMatch.installPath);
+ if (!canMutate()) return false;
+ if (JSON.stringify(current) === JSON.stringify(registryMatch.entry)) {
+ await registryService.removeInstall(skillName, registryMatch.installPath);
+ }
+ }
} catch (err) {
- log.warn('[skillInstall] uninstall registry.removeInstall failed:', err);
+ complete = false;
+ log.warn('[skillInstall] uninstall registry cleanup failed:', err);
}
-
- if (cloudUserId && await shouldRecordAutoSyncIgnore(skillName, registryEntry, cloudUserId)) {
- await ignoreAutoSyncSkill(skillName, cloudUserId).catch((err) => {
- log.warn('[skillInstall] record auto-sync ignore failed:', err);
- });
- }
-
- // best-effort: 清理指向已删目录的 symlink(canonical + agent-link 场景)
- const candidates = [
- path.join(os.homedir(), '.claude', 'skills', skillName),
- path.join(os.homedir(), '.codex', 'skills', skillName),
- path.join(os.homedir(), '.agents', 'skills', skillName),
- ].filter((c) => c !== path.normalize(absolutePath) && c !== resolved);
- for (const c of candidates) {
+ for (const link of links) {
+ if (!canMutate()) return false;
try {
- const st = await fs.promises.lstat(c);
- if (st.isSymbolicLink()) {
- const linkTarget = path.resolve(path.dirname(c), await fs.promises.readlink(c));
- if (!(await pathExists(linkTarget))) {
- await fs.promises.unlink(c);
- }
+ const stat = fs.lstatSync(link.path);
+ if (stat.isSymbolicLink() && stat.ino === link.ino && fs.readlinkSync(link.path) === link.value) {
+ // Keep validation and unlink adjacent; no awaited boundary can replace the link.
+ fs.unlinkSync(link.path);
+ }
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
+ complete = false;
+ log.warn('[skillInstall] uninstall link cleanup failed:', err);
}
- } catch { /* ignore */ }
+ }
}
+ if (!isCindySkillEnabled(resolved)) {
+ await setCindySkillEnabled(resolved, true, canMutate).catch((err) => {
+ complete = false;
+ log.warn('[skillInstall] activation cleanup failed:', err);
+ });
+ }
+ return complete;
+}
- const projectWorkingDir = await reconcileProjectSkillLinksForPaths(resolved, absolutePath);
-
- return { success: true, ...(projectWorkingDir ? { projectWorkingDir } : {}) };
+export async function retryUninstallCleanup(token: string, canMutate: () => boolean): Promise<boolean> {
+ const cleanup = pendingUninstallCleanup.get(token);
+ if (!cleanup) return true;
+ const release = tryAcquireSkillInstallLock(cleanup.skillName, 'market-uninstall');
+ if (!release) return false;
+ try {
+ const complete = await finishUninstallCleanup(cleanup, canMutate);
+ if (complete) pendingUninstallCleanup.delete(token);
+ return complete;
+ } finally { release(); }
}
async function shouldRecordAutoSyncIgnore(skillName: string, registryEntry: StoredInstall, userId: string): Promise<boolean> {
diff --git a/apps/desktop/src/main/skillhub/localSkillTarget.ts b/apps/desktop/src/main/skillhub/localSkillTarget.ts
new file mode 100644
index 0000000000..55979f8afe
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/localSkillTarget.ts
@@ -0,0 +1,53 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+/** Main-owned scan snapshot. Renderer never chooses the physical deletion target. */
+export interface LocalSkillTarget {
+ sourcePath: string;
+ operationPath: string;
+ linkOnly: boolean;
+ identity: string;
+ aliases: string[];
+}
+
+function isStandaloneSkillPath(value: string): boolean {
+ const normalized = path.resolve(value).replace(/\\/g, '/');
+ return /\/(?:\.(?:claude|agents|codex|pi)\/skills|\.pi\/agent\/skills|(?:codex-home|pi-agent-home)\/skills)\/[^/.][^/]*$/.test(normalized);
+}
+
+function targetIdentity(operationPath: string): string {
+ const entry = fs.lstatSync(operationPath);
+ const source = fs.realpathSync.native(operationPath);
+ const physical = fs.statSync(source);
+ return JSON.stringify([source, entry.dev, entry.ino, physical.dev, physical.ino]);
+}
+
+/** Only standalone Skill entities may be trashed; never an enclosing package or discovery root. */
+export function inspectLocalSkillTarget(source: string, discoveryPaths: readonly string[]): LocalSkillTarget | null {
+ try {
+ const sourcePath = fs.realpathSync.native(source);
+ const stat = fs.statSync(sourcePath);
+ if (stat.isDirectory()) {
+ if (!['SKILL.md', 'skill.md'].some((name) => fs.statSync(path.join(sourcePath, name), { throwIfNoEntry: false })?.isFile())) return null;
+ } else if (!stat.isFile() || !sourcePath.toLowerCase().endsWith('.md')) return null;
+ const aliases = [...new Set(discoveryPaths.map((value) => path.resolve(value)))].filter((value) => {
+ try { return isStandaloneSkillPath(value) && fs.realpathSync.native(value) === sourcePath; }
+ catch { return false; }
+ });
+ let operationPath = sourcePath;
+ let linkOnly = false;
+ if (!isStandaloneSkillPath(sourcePath)) {
+ // A link into an external checkout is an import reference, not ownership of that checkout.
+ const externalLink = aliases.find((value) => fs.lstatSync(value).isSymbolicLink());
+ if (!externalLink) return null;
+ operationPath = externalLink;
+ linkOnly = true;
+ }
+ return { sourcePath, operationPath, linkOnly, identity: targetIdentity(operationPath), aliases };
+ } catch { return null; }
+}
+
+export function isLocalSkillTargetCurrent(target: LocalSkillTarget): boolean {
+ try { return targetIdentity(target.operationPath) === target.identity; }
+ catch { return false; }
+}
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index 0e85b28aa4..5cae038315 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -1,3 +1,8 @@
+import fs from 'node:fs';
+import { throwIpcError } from '../utils/ipcValidate';
+import { setCindySkillEnabled } from './activationPreferences';
+import { inspectLocalSkillTarget, isLocalSkillTargetCurrent, type LocalSkillTarget } from './localSkillTarget';
+import { tryAcquireSkillInstallLock } from './installLock';
import { randomUUID } from 'node:crypto';
import path from 'node:path';
import type { Maker } from '@cindy/maker-core';
@@ -109,7 +114,50 @@ async function validateRequestedProjects(
export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const marketService = options.marketService ?? new SkillhubMarketService();
const localImportGrants = new Map<string, LocalImportGrant>();
+ const cleanupGrants = new Map<string, { ownerId: string | null; senderId: number }>();
const scannedSkillRootsBySender = new Map<number, ScannedSkillGrant>();
+ const localSkillsBySender = new Map<number, Array<{
+ skill: import('./scanner').Skill;
+ target: LocalSkillTarget | null;
+ physicalIdentity: string;
+ }>>();
+ const physicalIdentity = (source: string): string => {
+ const st = fs.statSync(source);
+ return JSON.stringify([fs.realpathSync.native(source), st.dev, st.ino]);
+ };
+ const broadcastLocalChange = () => {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) {
+ try { win.webContents.send('skillhub:local-state-changed'); } catch { /* Window closed. */ }
+ }
+ }
+ };
+ const requireLocalSkill = async (event: Electron.IpcMainInvokeEvent, source: string) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof source !== 'string' || !path.isAbsolute(source)) throwIpcError('INVALID_PARAMS', 'Invalid Skill');
+ const ownerId = getCurrentDataOwnerId();
+ const grant = scannedSkillRootsBySender.get(event.sender.id);
+ const record = localSkillsBySender.get(event.sender.id)?.find(({ skill }) => skill.absolutePath === source);
+ if (!record || !ownerId || grant?.ownerId !== ownerId || isAppSessionBoundaryPending()) {
+ throwIpcError('PRECONDITION_FAILED', 'Refresh the Skill list and retry');
+ }
+ if (record.skill.scope === 'project') {
+ const roots = await options.getAllowedProjectRoots();
+ if (!roots.some((root) => projectRootKey(root) === projectRootKey(record.skill.projectRoot))) {
+ throwIpcError('PERMISSION_DENIED', 'Project is no longer available');
+ }
+ }
+ if (getCurrentDataOwnerId() !== ownerId || isAppSessionBoundaryPending()) {
+ throwIpcError('PRECONDITION_FAILED', 'Account changed; refresh and retry');
+ }
+ try {
+ if (physicalIdentity(source) !== record.physicalIdentity) throw new Error('changed');
+ for (const alias of record.skill.discoveryPaths ?? [record.skill.discoveredPath]) {
+ if (physicalIdentity(alias) !== record.physicalIdentity) throw new Error('changed');
+ }
+ } catch { throwIpcError('PRECONDITION_FAILED', 'Skill source changed; refresh and retry'); }
+ return record;
+ };
const scanGenerationBySender = new Map<number, number>();
const scanGrantCleanupRegistered = new WeakSet<object>();
@@ -118,6 +166,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
scanGrantCleanupRegistered.add(event.sender);
event.sender.once('destroyed', () => {
scannedSkillRootsBySender.delete(event.sender.id);
+ localSkillsBySender.delete(event.sender.id);
scanGenerationBySender.delete(event.sender.id);
});
};
@@ -152,6 +201,13 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
}
}
scannedSkillRootsBySender.set(event.sender.id, { ownerId, entries });
+ localSkillsBySender.set(event.sender.id, skills.flatMap((skill) => {
+ if (skill.kind !== 'skill') return [];
+ try {
+ return [{ skill, physicalIdentity: physicalIdentity(skill.absolutePath),
+ target: inspectLocalSkillTarget(skill.absolutePath, skill.discoveryPaths ?? [skill.discoveredPath]) }];
+ } catch { return []; }
+ }));
};
const hasScannedSkillGrant = (
@@ -885,17 +941,59 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
},
);
- // 卸载(删本地文件夹)—— service 内校验路径白名单
+ ipcMain.handle('skillhub:set-enabled', async (event, params: { absolutePath: string; enabled: boolean }) => {
+ if (typeof params?.enabled !== 'boolean') throwIpcError('INVALID_PARAMS', 'Invalid Skill state');
+ const record = await requireLocalSkill(event, params.absolutePath);
+ const { skill } = record;
+ const ownerId = getCurrentDataOwnerId();
+ const canMutate = () => {
+ if (ownerId !== getCurrentDataOwnerId() || isAppSessionBoundaryPending()) return false;
+ try {
+ return physicalIdentity(skill.absolutePath) === record.physicalIdentity
+ && (skill.discoveryPaths ?? [skill.discoveredPath]).every((alias) => physicalIdentity(alias) === record.physicalIdentity);
+ } catch { return false; }
+ };
+ const release = tryAcquireSkillInstallLock(skill.name, 'market-uninstall');
+ if (!release) throwIpcError('PRECONDITION_FAILED', 'Skill is being changed; retry shortly');
+ try {
+ await setCindySkillEnabled(skill.absolutePath, params.enabled, canMutate);
+ } catch { throwIpcError('INTERNAL', 'Could not save Skill state; retry'); }
+ finally { release(); }
+ broadcastLocalChange();
+ return { cindyEnabled: params.enabled };
+ });
+
+ // Main resolves the exact scanned entity; no arbitrary renderer path deletion.
ipcMain.handle(
'skillhub:uninstall',
- async (_event, { absolutePath }: { absolutePath: string }) => {
- const result = await installService.uninstall(absolutePath);
- if (!result.success) return result;
+ async (event, { absolutePath }: { absolutePath: string }) => {
+ const { target } = await requireLocalSkill(event, absolutePath);
+ if (!target || !isLocalSkillTargetCurrent(target)) {
+ throwIpcError('PRECONDITION_FAILED', 'Skill cannot be uninstalled; refresh and retry');
+ }
+ const ownerId = getCurrentDataOwnerId();
+ const result = await installService.uninstall(absolutePath, target,
+ () => ownerId === getCurrentDataOwnerId() && !isAppSessionBoundaryPending());
+ if (!result.success) throwIpcError('INTERNAL', 'Could not move Skill to the trash; retry');
await refreshCodexProjectSkillCache(result.projectWorkingDir);
- return { success: true };
+ broadcastLocalChange();
+ if (result.cleanupToken) cleanupGrants.set(result.cleanupToken, { ownerId, senderId: event.sender.id });
+ return { success: true, ...(result.cleanupToken ? { cleanupToken: result.cleanupToken } : {}) };
},
);
+ ipcMain.handle('skillhub:retry-uninstall-cleanup', async (event, token: string) => {
+ assertTrustedAppRendererEvent(event);
+ const grant = cleanupGrants.get(token);
+ const canMutate = () => !!grant && grant.ownerId === getCurrentDataOwnerId()
+ && grant.senderId === event.sender.id && !isAppSessionBoundaryPending();
+ if (!canMutate()) throwIpcError('PRECONDITION_FAILED', 'Cleanup is no longer available');
+ const complete = await installService.retryUninstallCleanup(token, canMutate);
+ if (complete) cleanupGrants.delete(token);
+ broadcastLocalChange();
+ return { complete };
+ });
+
// ── SkillHub Registry: 一次性回填 authorId 到本地 install 记录 ──
// 历史遗留:之前的 publish 流程在源目录无 install 记录时不会主动新建,
// 导致用户在 ~/.claude/skills/* 手写 + 直接 publish 的 skill 没有 registry,
diff --git a/apps/desktop/src/main/skillhub/scanner.ts b/apps/desktop/src/main/skillhub/scanner.ts
index 799dd8a437..1070f828d2 100644
--- a/apps/desktop/src/main/skillhub/scanner.ts
+++ b/apps/desktop/src/main/skillhub/scanner.ts
@@ -1,3 +1,5 @@
+import { isCindySkillEnabled } from './activationPreferences';
+import { inspectLocalSkillTarget } from './localSkillTarget';
/**
* SkillHub Scanner — 商店层 (registry / market) 视图组装。
*
@@ -38,6 +40,12 @@ export interface SkillFileEntry {
}
export interface Skill {
+ /** Local Cindy override, independent of each engine's native availability. */
+ cindyEnabled?: boolean;
+ canUninstall?: boolean;
+ uninstallLinkOnly?: boolean;
+ /** All lexical discovery aliases; Main owns their validation. */
+ discoveryPaths?: string[];
/**
* Stable id — React key,含 engine 前缀防跨引擎同名冲突。同一 engine 下
* 若 URL 基键重复,会再追加 canonical source path 的不可逆 hash。
@@ -324,6 +332,12 @@ export async function scanAllSkills(
frontmatter: c.frontmatter,
parseError: c.parseError,
registryEntry: null, // 下面 join 阶段填
+ ...(c.kind === 'skill' ? (() => {
+ const discoveryPaths = all.map((item) => item.absolutePath);
+ const target = inspectLocalSkillTarget(realPath, discoveryPaths);
+ return { cindyEnabled: isCindySkillEnabled(realPath), discoveryPaths,
+ canUninstall: target !== null, uninstallLinkOnly: target?.linkOnly ?? false };
+ })() : {}),
...(project ? { projectRoot: project.projectRoot } : {}),
...(projectHash ? { projectHash } : {}),
};
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b7b4e03db0..9adf3860d9 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2945,6 +2945,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
// ~/.claude/{skills,commands,agents},project 来源由调用方传入的 projectRoot 决定。
// 返回商店层 Skill[] 与兼容用 sources[];scan 本身只读。
skillhub: {
+ setEnabled: (params: { absolutePath: string; enabled: boolean }): Promise<{ cindyEnabled: boolean }> =>
+ ipcRenderer.invoke('skillhub:set-enabled', params),
+ onLocalStateChanged: (callback: () => void): (() => void) => {
+ const handler = () => callback();
+ ipcRenderer.on('skillhub:local-state-changed', handler);
+ return () => ipcRenderer.removeListener('skillhub:local-state-changed', handler);
+ },
scan: (params: {
projects?: import('../main/skillhub/scanner').ProjectInput[];
}): Promise<{
@@ -3370,12 +3377,15 @@ contextBridge.exposeInMainWorld('electronAPI', {
cancelInstall: (name: string): Promise<{ success: boolean }> =>
ipcRenderer.invoke('skillhub:cancel-install', { name }),
- // 卸载(删本地文件夹)—— main 会校验目标必须有 registry 记录
+ // Main 校验当前扫描实体后移入系统回收站。
uninstall: (
absolutePath: string,
- ): Promise<{ success: true } | { success: false; errorCode: string; message: string }> =>
+ ): Promise<{ success: true; cleanupToken?: string } | { success: false; errorCode: string; message: string }> =>
ipcRenderer.invoke('skillhub:uninstall', { absolutePath }),
+ retryUninstallCleanup: (token: string): Promise<{ complete: boolean }> =>
+ ipcRenderer.invoke('skillhub:retry-uninstall-cleanup', token),
+
/** 在 main 内选择并检查本地包,成功时签发绑定当前 renderer 的短期导入授权。 */
pickLocal: (): Promise<
| { success: true; canceled: true }
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index dac234a455..35e5cff9c0 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -13,6 +13,7 @@ import {
} from 'react';
import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
+import { buildLocalSkillPathRoute } from '@/features/skillhub/lib/localRoutes';
import { Folder, MessageSquarePlus, Mic, Pen, TriangleAlert, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
@@ -4185,6 +4186,13 @@ export function ChatInput({
useEffect(() => {
reloadSlashCommands();
}, [reloadSlashCommands]);
+
+ useEffect(() => {
+ return window.electronAPI.skillhub?.onLocalStateChanged?.(() => {
+ void reloadSlashCommands({ forceReload: true });
+ });
+ }, [reloadSlashCommands]);
+
useEffect(
() =>
window.electronAPI.maker.onPiPackagesChanged(() => {
@@ -8944,6 +8952,11 @@ export function ChatInput({
focusedIndex={slashFocus}
onFocusedIndexChange={setSlashFocus}
onSelect={(cmd) => insertSlashCommand(cmd)}
+ onOpenSkillDetails={!isRemoteSession && !deviceLinkDeviceId ? (cmd) => {
+ if (cmd.kind !== 'agent-skill' || cmd.source !== 'skill' || !cmd.path) return;
+ draftSaveSchedulerRef.current?.flush();
+ navigate(buildLocalSkillPathRoute(cmd.path), { state: { resetHistory: true } });
+ } : undefined}
onClose={() => {
if (trigger.kind === 'slash') setSuppressedSlashAt(trigger.from);
}}
diff --git a/apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx b/apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx
index e8445b8c12..b73e61b451 100644
--- a/apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx
@@ -15,6 +15,9 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
+import { ArrowUpRight } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Tip } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import {
@@ -45,6 +48,8 @@ interface SlashCommandPaletteProps {
onSelect: (command: UnifiedCommand) => void;
/** Called when user presses Esc or clicks outside. ChatInput owns close. */
onClose: () => void;
+ /** Opens the backing local Skill from the hover information panel. */
+ onOpenSkillDetails?: (command: UnifiedCommand) => void;
/** Reports hover state for the portaled tooltip so ChatInput's blur guard treats it as part of the palette. */
onTooltipHoverChange?: (hovered: boolean) => void;
/** Panel max-height in px. Defaults to 400 (chat view); NewMaker passes a smaller value so the popover doesn't cover the logo. */
@@ -66,6 +71,7 @@ export function SlashCommandPalette({
onFocusedIndexChange,
onSelect,
onClose,
+ onOpenSkillDetails,
onTooltipHoverChange,
maxHeight = 400,
}: SlashCommandPaletteProps) {
@@ -290,8 +296,24 @@ export function SlashCommandPalette({
maxHeight: tooltipPos.maxHeight,
}}
>
- <div className="text-14 font-medium text-[var(--cmd-palette-item-text)]">
- {focusedCmd.name}
+ <div className="flex items-center gap-1 text-14 font-medium text-[var(--cmd-palette-item-text)]">
+ <span className="min-w-0 truncate">{focusedCmd.name}</span>
+ {onOpenSkillDetails && focusedCmd.kind === 'agent-skill'
+ && focusedCmd.source === 'skill' && focusedCmd.path && (
+ <Tip text={t('commandPalette.viewSkillDetails')}>
+ <Button variant="secondary"
+ className="w-8 border-transparent bg-transparent p-0 text-[var(--cmd-palette-item-meta)]"
+ aria-label={t('commandPalette.viewSkillDetails')}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={(event) => {
+ event.stopPropagation();
+ onOpenSkillDetails(focusedCmd);
+ onClose();
+ }}>
+ <ArrowUpRight size={14} aria-hidden />
+ </Button>
+ </Tip>
+ )}
</div>
<div className="mt-[8px] text-13 leading-[1.5] text-[var(--cmd-palette-tooltip-body)]">
{isSlashCommandUnavailable(focusedCmd)
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/SlashCommandPalette.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/SlashCommandPalette.test.tsx
index 7fc869ab67..c52800be2f 100644
--- a/apps/desktop/src/renderer/components/new-chat/__tests__/SlashCommandPalette.test.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/SlashCommandPalette.test.tsx
@@ -36,6 +36,39 @@ const discoveredProjectSkill: UnifiedCommand = {
};
describe('SlashCommandPalette project Skill rows', () => {
+ it('opens details from the portaled information panel without inserting the Skill', () => {
+ const command: UnifiedCommand = { ...discoveredProjectSkill, path: '/repo/.pi/skills/demo/SKILL.md' };
+ const onSelect = vi.fn();
+ const onClose = vi.fn();
+ const onOpenSkillDetails = vi.fn();
+ const { container } = render(<SlashCommandPalette query="" commands={[command]} focusedIndex={0}
+ onFocusedIndexChange={vi.fn()} onSelect={onSelect} onClose={onClose} onOpenSkillDetails={onOpenSkillDetails} />);
+ const details = screen.getByRole('button', { name: 'commandPalette.viewSkillDetails' });
+ expect(container.contains(details)).toBe(false);
+ fireEvent.mouseDown(details);
+ expect(onClose).not.toHaveBeenCalled();
+ fireEvent.click(details);
+ expect(onOpenSkillDetails).toHaveBeenCalledWith(command);
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ { kind: 'agent-builtin', name: 'compact', description: '' },
+ { ...discoveredProjectSkill, source: 'user', path: '/repo/.claude/commands/demo.md' },
+ discoveredProjectSkill,
+ ] as UnifiedCommand[])('does not offer Skill details for commands without a backing Skill: $name', (command) => {
+ render(<SlashCommandPalette query="" commands={[command]} focusedIndex={0}
+ onFocusedIndexChange={vi.fn()} onSelect={vi.fn()} onClose={vi.fn()} onOpenSkillDetails={vi.fn()} />);
+ expect(screen.queryByRole('button', { name: 'commandPalette.viewSkillDetails' })).toBeNull();
+ });
+
+ it('does not expose a local destination when the host omits navigation for remote Skills', () => {
+ render(<SlashCommandPalette query="" commands={[{ ...discoveredProjectSkill, path: '/remote/demo/SKILL.md' }]}
+ focusedIndex={0} onFocusedIndexChange={vi.fn()} onSelect={vi.fn()} onClose={vi.fn()} />);
+ expect(screen.queryByRole('button', { name: 'commandPalette.viewSkillDetails' })).toBeNull();
+ });
+
it('keeps a discovered Skill disabled and non-actionable', () => {
const onSelect = vi.fn();
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
index 9c9134a563..f0c768bdd8 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
@@ -1,3 +1,4 @@
+import { LocalSkillControls } from './components/LocalSkillControls';
/**
* SkillhubDetailView — route for /skillhub/{kind}/{global|project}/[hash]/:name.
*
@@ -16,7 +17,7 @@
*/
import * as Dialog from '@radix-ui/react-dialog';
-import { AlertCircle, AlertTriangle, ArrowLeft, ArrowUp, Bot, CheckCircle, ChevronDown, ChevronRight, Clock3, FileText, Folder, FolderOpen, Globe, type LucideIcon, Package, Pencil, Save, Search, SquareTerminal, Trash2, Upload, X } from 'lucide-react';
+import { AlertCircle, AlertTriangle, ArrowLeft, ArrowUp, Bot, CheckCircle, ChevronDown, ChevronRight, Clock3, FileText, Folder, FolderOpen, Globe, type LucideIcon, Package, Pencil, Save, Search, SquareTerminal, Upload, X } from 'lucide-react';
import { type CSSProperties, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
@@ -974,7 +975,12 @@ export function SkillhubDetailView() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const location = useLocation();
- const { skills, bootstrapped } = useSkillhub();
+ const { skills, bootstrapped, loading: skillsLoading } = useSkillhub();
+ const commandPath = searchParams.get('path');
+ useEffect(() => {
+ // The palette can discover a newly added Skill before the SkillHub cache does.
+ if (commandPath) void refreshSkillhub();
+ }, [commandPath]);
const { createSession } = useCCSessions();
// 入口来源:market 卡片会带 state.from。详情页返回不走浏览器式历史,
// 而是退出到 SkillHub 一级页:market 来源回 market,其它入口回 local 欢迎页。
@@ -1301,7 +1307,6 @@ export function SkillhubDetailView() {
const detailAction = detailActionState?.status ?? null;
const isOutdated = detailActionState?.isOutdated ?? false;
const isMineDirty = detailActionState?.isMineDirty ?? false;
- const showUninstall = detailActionState?.showUninstall ?? false;
const showForeignDirtyBanner = detailActionState?.showForeignDirtyBanner ?? false;
const [scanResult, setScanResult] = useState<ScanResultPayload | null>(null);
@@ -1354,36 +1359,6 @@ export function SkillhubDetailView() {
// 跟 SkillhubMarketListView 走同一条 IPC,保持后端逻辑唯一。
const [marketActionRunning, setMarketActionRunning] = useState(false);
- const handleUninstallInstalled = useCallback(async () => {
- if (!entry?.absolutePath) return;
- const ok = await confirm({
- title: t('skillhub.detail.uninstallDialog.title', { name: entry.name }),
- description: t('skillhub.detail.uninstallDialog.description', { path: entry.absolutePath }),
- confirmText: t('skillhub.detail.uninstallDialog.confirm'),
- cancelText: t('skillhub.detail.uninstallDialog.cancel'),
- });
- if (!ok) return;
- setMarketActionRunning(true);
- try {
- const res = await window.electronAPI.skillhub.uninstall(entry.absolutePath);
- if (res.success) {
- toast.success(t('skillhub.detail.uninstalledToast', { name: entry.name }));
- // 卸载后当前 entry 已经不存在,detail view 渲染会失败 → 跳到 local
- // 欢迎页(它会自己 pick 上一次选中的本地技能;若该技能就是刚卸载的,
- // welcome 会清掉 lastEntryId 然后展示空态)。原来跳到 market 不合理 ——
- // 用户从 local 树点进 detail 时不应该被甩到 market。
- clearLastEntryId();
- clearHistory();
- void refreshSkillhub();
- navigate('/skillhub/local');
- } else {
- toast.error(t('skillhub.detail.uninstallFailed', { message: res.message }));
- }
- } finally {
- setMarketActionRunning(false);
- }
- }, [entry, confirm, navigate, t]);
-
const handleUpdateInstalled = useCallback(async (
latestVersion: string,
options?: { confirmLocalChanges?: boolean },
@@ -1806,7 +1781,7 @@ export function SkillhubDetailView() {
if (!entry) {
return (
<div className="flex h-full w-full flex-col items-center justify-center gap-2 text-sm text-[var(--cmd-palette-item-meta)]">
- {bootstrapped ? (
+ {bootstrapped && !skillsLoading ? (
<>
<p>{t('skillhub.detail.notFound')}</p>
<button
@@ -2037,25 +2012,12 @@ export function SkillhubDetailView() {
{/* skill 按钮组 — detailAction.status 保证市场状态/动作互斥 */}
{isSkill && detailState && (
<>
- {/* D1: 卸载 — origin=installed(市场)或 imported(本地导入) */}
- {showUninstall && (
- <button
- type="button"
- onClick={() => { void handleUninstallInstalled(); }}
- disabled={marketActionRunning}
- className={cn(
- 'flex h-9 shrink-0 items-center gap-2 rounded-full border px-[18px]',
- 'text-sm font-medium',
- 'border-[var(--confirm-btn-secondary-border)] bg-transparent text-[var(--settings-btn-secondary-text)]',
- 'hover:bg-[var(--surface-hover)]',
- 'disabled:opacity-50 disabled:cursor-not-allowed',
- 'transition-colors',
- )}
- >
- <Trash2 size={14} className="shrink-0" />
- <span>{t('skillhub.detail.uninstall')}</span>
- </button>
- )}
+ {entry && <LocalSkillControls skill={entry} disabled={marketActionRunning || editMode}
+ onUninstalled={() => {
+ clearLastEntryId();
+ clearHistory();
+ navigate('/skillhub/local');
+ }} />}
{/* 编辑入口 */}
{!editButtonState.hidden && (
<Tip text={editButtonState.tip}>
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
index 0fe974434d..3f4164a3df 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
@@ -14,7 +14,6 @@ import { CATEGORY_ALL } from '../../../shared/skillhubCategory';
import {
Bot,
ChevronRight,
- Download,
Package,
SquareTerminal,
Upload,
@@ -49,9 +48,9 @@ import {
type HomeMarketFilter,
} from './lib/homeMarketFilter';
import { deriveSkillSource } from './lib/skillSource';
-import { skillPublisherLabel } from './lib/publisherLabel';
import { InstallTargetPicker, type InstallTargetSkill } from './components/InstallTargetPicker';
import { SkillCategoryFilterBar } from './components/SkillCategoryFilterBar';
+import { HomeMarketCard } from './components/HomeMarketCard';
import { SkillIcon } from './components/SkillIcon';
import { SkillTagList } from './components/SkillTagList';
import { SkillhubMarketPreviewPanel } from './SkillhubMarketPreviewPanel';
@@ -385,44 +384,7 @@ export function SkillhubHomeView({
) : (
<div className={cn('plugin-motion-stagger', PLUGIN_MANAGEMENT_CARD_GRID_CLASS)}>
{catalogItems.map((s) => (
- <button
- key={s.name}
- type="button"
- onClick={() => openCatalogSkill(s)}
- className={cn(
- 'group flex min-h-[100px] flex-col gap-1.5 rounded-[12px] border-[0.5px] border-[var(--border-default)]',
- 'bg-[var(--surface-elevated)] p-3 text-left shadow-[var(--plugin-card-shadow)]',
- 'transition-[background-color,border-color,transform] duration-150 ease-out',
- 'hover:-translate-y-0.5 hover:border-[var(--text-tertiary)]',
- 'active:translate-y-0 active:scale-[0.992]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- )}
- >
- <div className="flex items-center gap-2">
- <SkillIcon url={s.icon} />
- <span className="min-w-0 flex-1 truncate text-sm font-medium text-[var(--msg-assistant-text)]">
- {s.displayName || s.name}
- </span>
- <SkillTagList tags={s.tags} maxVisible={1} className="shrink-0" />
- {s.installedLocally && (
- <span className="shrink-0 rounded-full bg-[var(--chat-input-chip-bg)] px-1.5 py-0.5 text-10 text-[var(--cmd-palette-item-meta)]">
- {t('skillhub.home.installed')}
- </span>
- )}
- </div>
- {s.description && (
- <p className="line-clamp-2 text-xs text-[var(--cmd-palette-item-meta)]">
- {s.description}
- </p>
- )}
- <div className="flex items-center gap-2 text-11 text-[var(--cmd-palette-item-meta)]">
- <span className="min-w-0 truncate">{skillPublisherLabel(s)}</span>
- <span className="inline-flex shrink-0 items-center gap-0.5">
- <Download size={11} />
- {s.downloads}
- </span>
- </div>
- </button>
+ <HomeMarketCard key={skillhubCatalogKey(s.name, s.catalogScope)} skill={s} onClick={openCatalogSkill} />
))}
{marketResponseCurrent && marketHasMore ? (
<div className="col-span-full flex justify-center pt-1">
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx
index e960b4e6b5..49bdcc185e 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { Download, FileText, GraduationCap, X } from 'lucide-react';
import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
+import { Button } from '@/components/ui/button';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { useNavigate } from 'react-router-dom';
@@ -29,6 +30,7 @@ import {
publishedStatusLabelKey,
} from './lib/publishedStatus';
import { MarketPreviewTree } from './components/MarketPreviewTree';
+import { MarketLocalSkills } from './components/MarketLocalSkills';
import { ManageMenu, type MarketCardManageAction } from './components/MarketCard';
import { ScanResultDialog } from './ScanResultDialog';
import type { ScanResultPayload } from './PublishDialog';
@@ -49,7 +51,7 @@ interface SkillhubMarketPreviewPanelProps {
* 结构:
* Hero 头部 — 标题行(标题+可见性 chip | 操作按钮),元信息行,描述(满宽)
* 正文 — 左栏(FILES 树) + 右侧 Markdown
- * 遮罩盖整个内容区,sidebar 保持可见可点(本地安装位置只看 sidebar 的 MarketSelectionPanel)。
+ * 遮罩盖整个内容区,sidebar 保持可见可点;头部显示本地安装位置及管理操作。
*/
export function SkillhubMarketPreviewPanel({
skill,
@@ -184,8 +186,8 @@ export function SkillhubMarketPreviewPanel({
<div className="flex h-full min-h-0 flex-col">
{/* Hero 头部 — 仅标题行与操作同排,元信息/描述满宽 */}
<header className="shrink-0 border-b border-[var(--cmd-palette-border)] px-6 pb-5 pt-5">
- <div className="flex items-center justify-between gap-4">
- <div className="flex min-w-0 items-center gap-2.5">
+ <div className="flex items-center gap-3">
+ <div className="flex min-w-24 flex-1 items-center gap-2.5 overflow-hidden">
<h2 className="truncate text-lg font-semibold leading-tight">
{skill.displayName || skill.name}
</h2>
@@ -228,10 +230,10 @@ export function SkillhubMarketPreviewPanel({
) : null}
</div>
- <div className="flex shrink-0 items-center gap-2">
+ <div className="flex min-w-0 items-center gap-2 overflow-x-auto py-1">
{primaryAction === 'clone' ? (
- <button
- type="button"
+ <Button
+ variant="secondary"
onClick={() => {
// Learn = 以该 skill 为参考蒸馏本地技能(不安装原件)。
// 不预创建会话:把 `/learn hub:<slug> ` 预填进系统原生的
@@ -249,42 +251,35 @@ export function SkillhubMarketPreviewPanel({
onClose();
navigate('/cc-agent/new');
}}
- className={cn(
- 'flex shrink-0 items-center gap-1.5 rounded-full border border-[var(--border-default)] transition-colors',
- 'text-[var(--text-secondary)] hover:bg-[var(--surface-chip)]',
- )}
- style={{ height: '32px', padding: '0 14px', fontSize: '13px', fontWeight: 500 }}
+ className="gap-1.5 px-3.5"
>
<GraduationCap size={14} className="shrink-0" />
<span className="leading-none">{t('learn.hub.learnButton')}</span>
- </button>
+ </Button>
) : null}
{primaryAction === 'clone' && onClone ? (
- <button
- type="button"
+ <Button
+ variant="cta"
onClick={() => onClone(skill)}
- className={cn(
- 'flex shrink-0 items-center gap-1.5 rounded-full transition-colors',
- 'bg-[var(--lightbox-cta-bg)] text-[var(--lightbox-cta-fg)] hover:bg-[var(--lightbox-cta-hover)]',
- )}
- style={{ height: '32px', padding: '0 14px', fontSize: '13px', fontWeight: 500 }}
+ className="gap-1.5 px-3.5"
>
<Download size={14} className="shrink-0" />
<span className="leading-none">{t('skillhub.marketCard.clone')}</span>
- </button>
+ </Button>
) : null}
{primaryAction === 'manage' && onManageAction ? (
<ManageMenu skill={skill} onAction={onManageAction} />
) : null}
- <button
- type="button"
- onClick={onClose}
- aria-label={t('diffPanel.shell.closeAria')}
- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--surface-chip)]"
- >
- <X size={16} />
- </button>
+ <MarketLocalSkills key={`${skill.catalogScope}:${skill.name}`} skill={skill} />
</div>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label={t('diffPanel.shell.closeAria')}
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--surface-chip)]"
+ >
+ <X size={16} />
+ </button>
</div>
<p className="mt-1 truncate text-xs text-[var(--cmd-palette-item-meta)]">
diff --git a/apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx b/apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx
new file mode 100644
index 0000000000..420a2f5135
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx
@@ -0,0 +1,53 @@
+import { Download } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { cn } from '@/lib/utils';
+import type { MarketSkill } from '../hooks/useMarketList';
+import { skillPublisherLabel } from '../lib/publisherLabel';
+import { SkillIcon } from './SkillIcon';
+import { SkillTagList } from './SkillTagList';
+
+export function HomeMarketCard({ skill: s, onClick }: {
+ skill: MarketSkill;
+ onClick: (skill: MarketSkill) => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <button
+ type="button"
+ onClick={() => onClick(s)}
+ className={cn(
+ 'group flex min-h-[100px] flex-col gap-1.5 rounded-[12px] border-[0.5px] border-[var(--border-default)]',
+ 'bg-[var(--surface-elevated)] p-3 text-left shadow-[var(--plugin-card-shadow)]',
+ 'transition-[background-color,border-color,transform] duration-150 ease-out',
+ 'hover:-translate-y-0.5 hover:border-[var(--text-tertiary)]',
+ 'active:translate-y-0 active:scale-[0.992]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <SkillIcon url={s.icon} />
+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-[var(--msg-assistant-text)]">
+ {s.displayName || s.name}
+ </span>
+ <SkillTagList tags={s.tags} maxVisible={1} className="shrink-0" />
+ {s.installedLocally && (
+ <span className="shrink-0 rounded-full bg-[var(--chat-input-chip-bg)] px-1.5 py-0.5 text-10 text-[var(--cmd-palette-item-meta)]">
+ {t('skillhub.home.installed')}
+ </span>
+ )}
+ </div>
+ {s.description && (
+ <p className="line-clamp-2 text-xs text-[var(--cmd-palette-item-meta)]">
+ {s.description}
+ </p>
+ )}
+ <div className="flex items-center gap-2 text-11 text-[var(--cmd-palette-item-meta)]">
+ <span className="min-w-0 truncate">{skillPublisherLabel(s)}</span>
+ <span className="inline-flex shrink-0 items-center gap-0.5">
+ <Download size={11} />
+ {s.downloads}
+ </span>
+ </div>
+ </button>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx b/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
new file mode 100644
index 0000000000..8657ba0a61
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
@@ -0,0 +1,127 @@
+import { useRef, useState } from 'react';
+import { MoreHorizontal, Trash2 } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { Switch } from '@/components/ui/switch';
+import { Button } from '@/components/ui/button';
+import { Tip } from '@/components/ui/tooltip';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
+import { extractIpcError } from '@/utils/ipcError';
+import { toast } from '@/lib/toast';
+import { refresh } from '../hooks/useSkillhub';
+
+/** Local management for Skill details, independent of cloud ownership. */
+export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
+ skill: SkillhubSkill;
+ disabled?: boolean;
+ onUninstalled?: () => void;
+}) {
+ const { t } = useTranslation();
+ const { confirm } = useConfirmDialog();
+ const busyRef = useRef(false);
+ const [busy, setBusy] = useState(false);
+ const [pendingEnabled, setPendingEnabled] = useState<boolean | null>(null);
+ if (skill.kind !== 'skill') return null;
+ const enabled = pendingEnabled ?? skill.cindyEnabled !== false;
+ const reportError = (error: unknown, operation: 'toggleFailed' | 'uninstallFailed') => {
+ const code = extractIpcError(error)?.code;
+ toast.error(t(`skillhub.management.${code === 'PRECONDITION_FAILED' || code === 'PERMISSION_DENIED' ? 'refreshRequired' : operation}`));
+ };
+ const toggle = async (value: boolean) => {
+ if (busyRef.current || disabled) return;
+ busyRef.current = true;
+ setBusy(true);
+ setPendingEnabled(value);
+ try {
+ await window.electronAPI.skillhub.setEnabled({ absolutePath: skill.absolutePath, enabled: value });
+ await refresh();
+ toast.success(t(value ? 'skillhub.management.enabledToast' : 'skillhub.management.disabledToast', { name: skill.name }));
+ } catch (error) { reportError(error, 'toggleFailed'); }
+ finally {
+ setPendingEnabled(null);
+ busyRef.current = false;
+ setBusy(false);
+ }
+ };
+ const uninstall = async () => {
+ if (busyRef.current || disabled || !skill.canUninstall) return;
+ busyRef.current = true;
+ setBusy(true);
+ try {
+ const accepted = await confirm({
+ title: t('skillhub.detail.uninstallDialog.title', { name: skill.name }),
+ description: [
+ t(skill.uninstallLinkOnly ? 'skillhub.management.unlinkDescription' : 'skillhub.management.trashDescription'),
+ t(skill.scope === 'project' ? 'skillhub.management.projectScope' : 'skillhub.management.globalScope', {
+ project: skill.projectRoot ?? '',
+ }),
+ t('skillhub.management.sharedImpact'),
+ ].join('\n\n'),
+ confirmText: t('skillhub.detail.uninstallDialog.confirm'),
+ cancelText: t('skillhub.detail.uninstallDialog.cancel'),
+ });
+ if (!accepted) return;
+ const result = await window.electronAPI.skillhub.uninstall(skill.absolutePath);
+ if (!result.success) {
+ toast.error(t('skillhub.management.uninstallFailed'));
+ return;
+ }
+ if (result.cleanupToken) {
+ const token = result.cleanupToken;
+ let retrying = false;
+ const showCleanup = () => {
+ const id = toast.warning(t('skillhub.management.cleanupIncomplete'), {
+ duration: 0,
+ action: { label: t('skillhub.management.retryCleanup'), onClick: () => {
+ if (retrying) return;
+ retrying = true;
+ void window.electronAPI.skillhub.retryUninstallCleanup(token).then(({ complete }) => {
+ if (complete) {
+ toast.dismiss(id);
+ toast.success(t('skillhub.management.cleanupComplete'));
+ void refresh();
+ }
+ }).catch((error: unknown) => reportError(error, 'uninstallFailed'))
+ .finally(() => { retrying = false; });
+ } },
+ });
+ };
+ showCleanup();
+ } else {
+ toast.success(t('skillhub.detail.uninstalledToast', { name: skill.name }));
+ }
+ onUninstalled?.();
+ await refresh();
+ } catch (error) { reportError(error, 'uninstallFailed'); }
+ finally { busyRef.current = false; setBusy(false); }
+ };
+
+ return (
+ <div className="flex shrink-0 items-center gap-2" onClick={(event) => event.stopPropagation()}>
+ <Tip text={`${skill.absolutePath}\n${t('skillhub.management.activationHint')}`}>
+ {/* Keep Tooltip's open/closed data-state off the Switch's checked/unchecked root. */}
+ <span className="inline-flex">
+ <Switch checked={enabled} disabled={busy || disabled}
+ aria-label={t('skillhub.management.enabledLabel', { name: skill.name })}
+ onCheckedChange={(value) => { void toggle(value); }} />
+ </span>
+ </Tip>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" disabled={busy || disabled}
+ aria-label={t('skillhub.management.moreLabel', { name: skill.name })}
+ className="w-8 p-0">
+ <MoreHorizontal size={14} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="rounded-xl border-[var(--border-default)] bg-[var(--surface-elevated)] p-1.5 shadow-none">
+ <DropdownMenuItem disabled={!skill.canUninstall} onSelect={() => { void uninstall(); }}
+ className="gap-2 rounded-lg text-13">
+ <Trash2 size={14} />{t('skillhub.detail.uninstall')}
+ </DropdownMenuItem>
+ {!skill.canUninstall && <p className="max-w-56 px-2 py-1 text-11 text-[var(--text-secondary)]">{t('skillhub.management.managedElsewhere')}</p>}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx b/apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx
new file mode 100644
index 0000000000..32b43cc405
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx
@@ -0,0 +1,63 @@
+import { useState } from 'react';
+import { ChevronDown } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
+import { useTranslation } from 'react-i18next';
+import { skillhubCatalogKey } from '../../../../shared/skillhubCatalog';
+import { useSkillhub } from '../hooks/useSkillhub';
+import type { MarketSkill } from '../hooks/useMarketList';
+import { LocalSkillControls } from './LocalSkillControls';
+
+/** Match the market's installed-state policy, but retain every scanned location. */
+export function MarketLocalSkills({ skill }: {
+ skill: Pick<MarketSkill, 'name' | 'isMine' | 'catalogScope'>;
+}) {
+ const { t } = useTranslation();
+ const { skills } = useSkillhub();
+ const [selectedPath, setSelectedPath] = useState<string | null>(null);
+ const copies = skills.filter((local) => {
+ if (local.kind !== 'skill' || local.name !== skill.name) return false;
+ return local.registryEntry
+ ? skillhubCatalogKey(local.name, local.registryEntry.catalogScope)
+ === skillhubCatalogKey(skill.name, skill.catalogScope)
+ : skill.isMine;
+ });
+ if (copies.length === 0) return null;
+
+ const selected = copies.find((local) => local.absolutePath === selectedPath) ?? copies[0]!;
+ const scopeLabel = (local: SkillhubSkill) => t(local.scope === 'project'
+ ? 'skillhub.detail.scopeProject' : 'skillhub.detail.scopeGlobal');
+
+ return (
+ <div className="flex h-8 shrink-0 items-center gap-2 border-l border-[var(--border-default)] pl-3">
+ {copies.length > 1 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" className="w-40 gap-1.5 px-3"
+ aria-label={t('skillhub.sidebar.marketInstalledHeading')} title={selected.absolutePath}>
+ <span className="truncate">{scopeLabel(selected)}</span>
+ <ChevronDown size={14} className="shrink-0" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end"
+ className="w-[var(--radix-dropdown-menu-trigger-width)] min-w-0 rounded-xl border-[var(--border-default)] bg-[var(--surface-elevated)] p-1.5 shadow-none">
+ <DropdownMenuRadioGroup value={selected.absolutePath} onValueChange={setSelectedPath}>
+ {copies.map((local) => (
+ <DropdownMenuRadioItem key={local.absolutePath} value={local.absolutePath}
+ className="rounded-lg text-13 focus:bg-[var(--surface-hover)] data-[state=checked]:bg-[var(--surface-chip)]">
+ <span className="min-w-0">
+ <span className="block">{scopeLabel(local)}{' · '}
+ {local.registryEntry ? `v${local.registryEntry.version}` : t('skillhub.sidebar.marketLocalCopy')}
+ </span>
+ <span className="block break-all text-11 text-[var(--text-secondary)]">{local.absolutePath}</span>
+ </span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ <LocalSkillControls key={selected.absolutePath} skill={selected} />
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/__tests__/LocalSkillControls.test.tsx b/apps/desktop/src/renderer/features/skillhub/components/__tests__/LocalSkillControls.test.tsx
new file mode 100644
index 0000000000..429b049f37
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/components/__tests__/LocalSkillControls.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ confirm: vi.fn(), setEnabled: vi.fn(), uninstall: vi.fn(), retry: vi.fn(), refresh: vi.fn(),
+ success: vi.fn(), error: vi.fn(), warning: vi.fn(), dismiss: vi.fn(),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => ({ confirm: mocks.confirm }) }));
+vi.mock('../../hooks/useSkillhub', () => ({ refresh: mocks.refresh }));
+vi.mock('@/lib/toast', () => ({ toast: {
+ success: mocks.success, error: mocks.error, warning: mocks.warning, dismiss: mocks.dismiss,
+} }));
+import { LocalSkillControls } from '../LocalSkillControls';
+
+const skill = { name: 'example', kind: 'skill', absolutePath: '/fixture/.agents/skills/example',
+ scope: 'global', cindyEnabled: true, canUninstall: true } as SkillhubSkill;
+
+async function chooseUninstall() {
+ fireEvent.keyDown(screen.getByRole('button', { name: 'skillhub.management.moreLabel' }), { key: 'Enter' });
+ const item = await screen.findByRole('menuitem', { name: 'skillhub.detail.uninstall' });
+ await act(async () => { fireEvent.click(item); });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.confirm.mockResolvedValue(true);
+ mocks.refresh.mockResolvedValue(undefined);
+ mocks.setEnabled.mockResolvedValue({ cindyEnabled: false });
+ mocks.uninstall.mockResolvedValue({ success: true });
+ mocks.retry.mockResolvedValue({ complete: true });
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { skillhub: {
+ setEnabled: mocks.setEnabled, uninstall: mocks.uninstall, retryUninstallCleanup: mocks.retry,
+ } } });
+});
+afterEach(cleanup);
+
+describe('Local Skill management', () => {
+ it.each([true, false])('preserves Switch styling state with the real tooltip (enabled=%s)', async (enabled) => {
+ render(<LocalSkillControls skill={{ ...skill, cindyEnabled: enabled }} />);
+ const control = screen.getByRole('switch');
+ expect(control.getAttribute('data-state')).toBe(enabled ? 'checked' : 'unchecked');
+ fireEvent.focus(control);
+ await screen.findByRole('tooltip');
+ expect(control.getAttribute('data-state')).toBe(enabled ? 'checked' : 'unchecked');
+ fireEvent.blur(control);
+ expect(control.getAttribute('data-state')).toBe(enabled ? 'checked' : 'unchecked');
+ });
+
+ it('blocks repeated toggles while saving, rolls back on error, and does not open details', async () => {
+ let reject!: (error: Error) => void;
+ mocks.setEnabled.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ const openDetails = vi.fn();
+ render(<div onClick={openDetails}><LocalSkillControls skill={skill} /></div>);
+ const control = screen.getByRole('switch') as HTMLButtonElement;
+ fireEvent.click(control);
+ expect(control.getAttribute('aria-checked')).toBe('false');
+ expect(control.disabled).toBe(true);
+ fireEvent.click(control);
+ expect(mocks.setEnabled).toHaveBeenCalledTimes(1);
+ expect(openDetails).not.toHaveBeenCalled();
+ await act(async () => { reject(new Error('disk full')); });
+ expect(control.getAttribute('aria-checked')).toBe('true');
+ expect(control.disabled).toBe(false);
+ expect(mocks.error).toHaveBeenCalledWith('skillhub.management.toggleFailed');
+ });
+
+ it('refreshes cards after a successful enable', async () => {
+ render(<LocalSkillControls skill={{ ...skill, cindyEnabled: false }} />);
+ fireEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(mocks.success).toHaveBeenCalledWith('skillhub.management.enabledToast'));
+ expect(mocks.setEnabled).toHaveBeenCalledWith({ absolutePath: skill.absolutePath, enabled: true });
+ expect(mocks.refresh).toHaveBeenCalledOnce();
+ });
+
+ it('does not uninstall when confirmation is cancelled', async () => {
+ mocks.confirm.mockResolvedValueOnce(false);
+ render(<LocalSkillControls skill={skill} />);
+ await chooseUninstall();
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledOnce());
+ expect(mocks.uninstall).not.toHaveBeenCalled();
+ });
+
+ it('explains external link and project scope before uninstalling', async () => {
+ const onUninstalled = vi.fn();
+ render(<LocalSkillControls skill={{ ...skill, scope: 'project', projectRoot: '/project', uninstallLinkOnly: true }} onUninstalled={onUninstalled} />);
+ await chooseUninstall();
+ await waitFor(() => expect(onUninstalled).toHaveBeenCalledOnce());
+ expect(mocks.confirm.mock.calls[0][0].description).toBe([
+ 'skillhub.management.unlinkDescription', 'skillhub.management.projectScope', 'skillhub.management.sharedImpact',
+ ].join('\n\n'));
+ expect(mocks.uninstall).toHaveBeenCalledWith(skill.absolutePath);
+ });
+
+ it('keeps package-owned uninstall unavailable', async () => {
+ render(<LocalSkillControls skill={{ ...skill, canUninstall: false }} />);
+ fireEvent.keyDown(screen.getByRole('button', { name: 'skillhub.management.moreLabel' }), { key: 'Enter' });
+ const item = await screen.findByRole('menuitem');
+ expect(item.getAttribute('aria-disabled')).toBe('true');
+ fireEvent.click(item);
+ expect(mocks.confirm).not.toHaveBeenCalled();
+ expect(screen.getByText('skillhub.management.managedElsewhere')).toBeTruthy();
+ });
+
+ it('offers a cleanup retry with the Main receipt after partial cleanup', async () => {
+ mocks.uninstall.mockResolvedValueOnce({ success: true, cleanupToken: 'receipt' });
+ render(<LocalSkillControls skill={skill} />);
+ await chooseUninstall();
+ await waitFor(() => expect(mocks.warning).toHaveBeenCalledOnce());
+ await act(async () => { mocks.warning.mock.calls[0][1].action.onClick(); });
+ expect(mocks.retry).toHaveBeenCalledWith('receipt');
+ expect(mocks.uninstall).toHaveBeenCalledOnce();
+ expect(mocks.success).toHaveBeenCalledWith('skillhub.management.cleanupComplete');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/components/__tests__/MarketLocalSkills.test.tsx b/apps/desktop/src/renderer/features/skillhub/components/__tests__/MarketLocalSkills.test.tsx
new file mode 100644
index 0000000000..5a688ba072
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/components/__tests__/MarketLocalSkills.test.tsx
@@ -0,0 +1,125 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ skills: [] as SkillhubSkill[], refresh: vi.fn(), confirm: vi.fn(),
+ setEnabled: vi.fn(), uninstall: vi.fn(),
+ t: (key: string) => key,
+}));
+vi.mock('../../hooks/useSkillhub', () => ({
+ useSkillhub: () => ({ skills: mocks.skills }), refresh: mocks.refresh,
+}));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => ({ confirm: mocks.confirm }) }));
+vi.mock('@/components/chat/MarkdownRenderer', () => ({ MarkdownRenderer: () => null }));
+vi.mock('../../ScanResultDialog', () => ({ ScanResultDialog: () => null }));
+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('react-i18next', async (importOriginal) => ({ ...await importOriginal<typeof import('react-i18next')>(), useTranslation: () => ({
+ t: mocks.t, i18n: { language: 'en' },
+}) }));
+
+import type { MarketSkill } from '../../hooks/useMarketList';
+import { MarketCard } from '../MarketCard';
+import { HomeMarketCard } from '../HomeMarketCard';
+import { MarketLocalSkills } from '../MarketLocalSkills';
+import { SkillhubMarketPreviewPanel } from '../../SkillhubMarketPreviewPanel';
+
+const market: MarketSkill = {
+ name: 'gws-calendar', latestVersion: '1.0.2', isMine: false, catalogScope: 'market',
+ authorName: 'Publisher', visibility: 'PUBLIC', tags: [], downloads: 0, installedLocally: true,
+ displayName: 'gws-calendar', description: 'Calendar', authorId: 'publisher',
+ authorAvatarUrl: null, avatarInitial: 'P', canManage: false,
+ visibleDeptIds: [], categories: [], githubUrl: null, publishedAt: '2026-09-01T00:00:00Z',
+ relativeTime: 'today', installedVersion: '1.0.2',
+ installedAbsolutePath: '/fixture/.agents/skills/gws-calendar', hasAnyInstall: true,
+ latestPublishedFromDeviceId: null, cardState: 'installed-latest',
+};
+const local = {
+ name: market.name, kind: 'skill', absolutePath: '/fixture/.agents/skills/gws-calendar',
+ scope: 'global', registryEntry: { catalogScope: 'market', version: '1.0.2' },
+ cindyEnabled: true, canUninstall: true,
+} as SkillhubSkill;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.skills = [local];
+ mocks.refresh.mockResolvedValue([]);
+ mocks.confirm.mockResolvedValue(true);
+ mocks.setEnabled.mockResolvedValue({ cindyEnabled: false });
+ mocks.uninstall.mockResolvedValue({ success: true });
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { skillhub: {
+ setEnabled: mocks.setEnabled, uninstall: mocks.uninstall,
+ getPublishedFiles: vi.fn().mockResolvedValue({ success: true, files: [] }),
+ } } });
+});
+afterEach(cleanup);
+
+describe.each(['home', 'card'] as const)('market %s list', (surface) => {
+ it('opens Skill details and does not expose local management controls', () => {
+ const onClick = vi.fn();
+ render(surface === 'home'
+ ? <HomeMarketCard skill={market} onClick={onClick} />
+ : <MarketCard skill={market} primaryAction="none" onClone={vi.fn()} onClick={onClick} />);
+ expect(screen.queryByRole('switch')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'skillhub.management.moreLabel' })).toBeNull();
+ fireEvent.click(screen.getByText(market.name));
+ expect(onClick).toHaveBeenCalledWith(market);
+ });
+});
+
+describe('market Skill details', () => {
+ it('shows gws-calendar 1.0.2 controls and targets the scanned local copy', async () => {
+ render(<MemoryRouter><SkillhubMarketPreviewPanel skill={market} open onClose={vi.fn()}
+ primaryAction="clone" onClone={vi.fn()} /></MemoryRouter>);
+ expect(screen.queryByText('skillhub.sidebar.marketInstalledHeading')).toBeNull();
+ const clone = screen.getByRole('button', { name: 'skillhub.marketCard.clone' });
+ expect(clone.parentElement?.contains(screen.getByRole('switch'))).toBe(true);
+ expect(screen.getByRole('switch').getAttribute('data-state')).toBe('checked');
+ fireEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(mocks.refresh).toHaveBeenCalledOnce());
+ expect(mocks.setEnabled).toHaveBeenCalledWith({ absolutePath: local.absolutePath, enabled: false });
+ fireEvent.keyDown(screen.getByRole('button', { name: 'skillhub.management.moreLabel' }), { key: 'Enter' });
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'skillhub.detail.uninstall' }));
+ await waitFor(() => expect(mocks.uninstall).toHaveBeenCalledWith(local.absolutePath));
+ });
+});
+
+describe('market installed location matching', () => {
+ it('selects a local copy in the toolbar and falls back after that copy is removed', async () => {
+ const project = { ...local, scope: 'project', projectRoot: '/project',
+ absolutePath: '/project/.agents/skills/gws-calendar', cindyEnabled: false } as SkillhubSkill;
+ mocks.skills = [local, project];
+ const { rerender } = render(<MarketLocalSkills skill={market} />);
+ expect(screen.getAllByRole('switch')).toHaveLength(1);
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');
+ fireEvent.keyDown(screen.getByRole('button', { name: 'skillhub.sidebar.marketInstalledHeading' }), { key: 'Enter' });
+ fireEvent.click(await screen.findByRole('menuitemradio', { name: new RegExp(project.absolutePath) }));
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false');
+ fireEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(mocks.setEnabled).toHaveBeenCalledWith({ absolutePath: project.absolutePath, enabled: true }));
+ mocks.skills = [local];
+ rerender(<MarketLocalSkills skill={market} />);
+ expect(screen.getAllByRole('switch')).toHaveLength(1);
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');
+ mocks.skills = [];
+ rerender(<MarketLocalSkills skill={market} />);
+ expect(screen.queryByRole('switch')).toBeNull();
+ });
+
+ it('does not manage same-name copies from another catalog or unregistered third-party copies', () => {
+ mocks.skills = [
+ { ...local, registryEntry: { ...local.registryEntry!, catalogScope: 'team' } },
+ { ...local, absolutePath: '/untracked', registryEntry: null },
+ { ...local, absolutePath: '/native', registryEntry: { ...local.registryEntry!, catalogScope: undefined } },
+ ];
+ render(<MarketLocalSkills skill={market} />);
+ expect(screen.queryByRole('switch')).toBeNull();
+ });
+
+ it('includes an owned unregistered copy and keeps package-owned copies toggleable', () => {
+ mocks.skills = [{ ...local, registryEntry: null, canUninstall: false }];
+ render(<MarketLocalSkills skill={{ ...market, isMine: true }} />);
+ expect(screen.getByRole('switch')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts
index 8fdc8e7c83..357f764b67 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts
@@ -189,7 +189,7 @@ export interface LocalSkillEntry {
version: string | null;
absolutePath: string;
/** 该本地 skill 是否有 registry 记录(registryEntry !== null)。
- false = 用户手写的本地 skill,从未与市场交互,不允许卸载。 */
+ false = 用户手写的本地 skill,从未与市场交互。卸载能力由本地扫描决定。 */
hasRegistryEntry: boolean;
}
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
index fd65bf54b5..a4cb790a0e 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
@@ -224,8 +224,12 @@ export function setSkillhubDataOwner(dataOwnerId: string | null): void {
// ── Auth change listener — reset store on every data-owner boundary ─────────
let authListenerUnsubscribe: (() => void) | null = null;
+let localStateListenerUnsubscribe: (() => void) | null = null;
function ensureAuthListener(): void {
+ if (!localStateListenerUnsubscribe && window.electronAPI.skillhub.onLocalStateChanged) {
+ localStateListenerUnsubscribe = window.electronAPI.skillhub.onLocalStateChanged(() => { void refresh(); });
+ }
if (authListenerUnsubscribe) return;
authListenerUnsubscribe = window.electronAPI.onAuthStateChange((authState) => {
setSkillhubDataOwner(authState.dataOwnerId);
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/localRoutes.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/localRoutes.test.ts
index 38aecb4ac4..02d85234ec 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/localRoutes.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/localRoutes.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
buildLocalSkillRoute,
+ buildLocalSkillPathRoute,
findLocalSkillByPath,
findLocalSkillRouteEntry,
} from '../localRoutes';
@@ -22,6 +23,26 @@ function entry(overrides: Partial<Entry> = {}): Entry {
}
describe('local SkillHub routes', () => {
+ it('opens the exact source from a slash Skill entrypoint, including discovery aliases', () => {
+ const target = entry({ absolutePath: '/shared/a & b', discoveryPaths: ['/repo/.claude/skills/demo'] });
+ const other = entry({ scope: 'global', absolutePath: '/home/.agents/skills/demo' });
+ for (const path of ['/shared/a & b/SKILL.md', '/repo/.claude/skills/demo/skill.md']) {
+ const url = new URL(buildLocalSkillPathRoute(path), 'https://cindy.local');
+ expect(url.pathname).toBe('/skillhub/local/by-path');
+ expect(url.searchParams.get('path')).toBe(path);
+ expect(findLocalSkillRouteEntry([other, target], {}, url.searchParams)).toBe(target);
+ }
+ });
+
+ it('supports Windows entrypoints and standalone Skill files without guessing by name', () => {
+ const windows = entry({ absolutePath: 'C:\\Skills\\Demo' });
+ const standalone = entry({ absolutePath: '/package/skills', mdPath: '/package/skills/demo.md' });
+ const resolve = (path: string) => findLocalSkillRouteEntry([windows, standalone], {}, new URLSearchParams({ path }));
+ expect(resolve('c:/skills/demo/SKILL.md')).toBe(windows);
+ expect(resolve('/package/skills/demo.md')).toBe(standalone);
+ expect(resolve('/missing/demo/SKILL.md')).toBeNull();
+ });
+
it('finds a renamed skill by its lexical discovered path when absolutePath is realpathed', () => {
const renamed = entry({
absolutePath: '/shared/skills/renamed',
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts
index 6556e044f6..959865e648 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts
@@ -84,7 +84,9 @@ describe('market route scope', () => {
expect(homeSource).toContain("t('skillhub.home.catalogMore')");
expect(homeSource).toContain('headerActions={(');
expect(homeSource).toContain('plugin-management-action-trigger');
- expect(homeSource).toContain('<SkillIcon url={s.icon} />');
+ expect(homeSource).toContain('<HomeMarketCard');
+ const homeCardSource = readFileSync(resolve(skillhubDir, 'components/HomeMarketCard.tsx'), 'utf8');
+ expect(homeCardSource).toContain('<SkillIcon url={s.icon} />');
expect(homeSource).not.toContain('<SkillSectionHeading');
expect(homeSource).not.toContain("label={t('skillhub.home.globalScope')}");
});
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts b/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts
index 7386df62f4..364e59939a 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts
@@ -5,7 +5,9 @@ interface LocalSkillRouteEntry {
scope: SkillhubScope;
name: string;
absolutePath: string;
+ mdPath?: string;
discoveredPath?: string;
+ discoveryPaths?: string[];
projectHash?: string;
sourceKey?: string;
requiresSourceKey?: boolean;
@@ -26,6 +28,18 @@ interface LocalSkillRouteParams {
name?: string;
}
+/** Resolve a palette's SKILL.md path after the SkillHub scanner has loaded. */
+export function buildLocalSkillPathRoute(path: string): string {
+ return `/skillhub/local/by-path?${new URLSearchParams({ path }).toString()}`;
+}
+
+function skillDirectoryPath(path: string): string {
+ const windows = /^[a-z]:[\\/]|^\\\\/i.test(path);
+ const normalized = (windows ? path.replace(/\\/g, '/') : path)
+ .replace(/\/+$/, '').replace(/\/skill\.md$/i, '');
+ return windows ? normalized.toLowerCase() : normalized;
+}
+
/** Builds a local detail URL while preserving the legacy pathname contract. */
export function buildLocalSkillRoute(entry: LocalSkillRouteEntry): string {
const name = encodeURIComponent(entry.name);
@@ -45,6 +59,13 @@ export function findLocalSkillRouteEntry<T extends LocalSkillRouteEntry>(
searchParams: Pick<URLSearchParams, 'get'>,
): T | null {
const { kind, projectHash, name } = params;
+ const commandPath = searchParams.get('path');
+ if (!kind && !name && commandPath) {
+ const target = skillDirectoryPath(commandPath);
+ return skills.find((skill) => skill.kind === 'skill' && [
+ skill.absolutePath, skill.mdPath, skill.discoveredPath, ...(skill.discoveryPaths ?? []),
+ ].some((path) => path && skillDirectoryPath(path) === target)) ?? null;
+ }
if (!kind || !name) return null;
const decodedName = decodeURIComponent(name);
const engine = searchParams.get('engine');
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 69ef0d612e..dcb70dd7b8 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -10661,6 +10661,7 @@
}
},
"commandPalette": {
+ "viewSkillDetails": "View skill details",
"projectSkillNotLoaded": "This Pi task hasn't loaded this project Skill. New tasks will automatically try to load it."
},
"skillhub": {
@@ -10819,11 +10820,11 @@
"market": "Back to Market",
"skillhub": "Back to SkillHub"
},
- "uninstall": "Uninstall",
+ "uninstall": "Uninstall Skill",
"uninstallDialog": {
- "title": "Uninstall {{name}}?",
- "description": "Will remove the local folder\n{{path}}\nThis cannot be undone.",
- "confirm": "Confirm uninstall",
+ "title": "Uninstall “{{name}}”?",
+ "description": "Local files and edits will move to the trash and can be restored.\n\nOther Agents sharing this skill will also be affected. Published versions and installations elsewhere are unaffected.",
+ "confirm": "Uninstall",
"cancel": "Cancel"
},
"uninstalledToast": "{{name}} uninstalled",
@@ -11221,6 +11222,26 @@
"marketEdit": {
"saved": "Market info saved",
"displayNameRequired": "Display name is required"
+ },
+ "management": {
+ "disabled": "Disabled",
+ "enabledLabel": "Enable Skill “{{name}}”",
+ "moreLabel": "Manage Skill “{{name}}”",
+ "activationHint": "Controls Skill loading in Cindy only. Takes effect when starting or restarting an Agent.",
+ "enabledToast": "Skill “{{name}}” enabled. Start or restart the Agent to apply.",
+ "disabledToast": "Skill “{{name}}” disabled. Start or restart the Agent to apply.",
+ "toggleFailed": "Could not save the Skill setting. Try again.",
+ "uninstallFailed": "Could not move the Skill to the trash. Check file permissions and try again.",
+ "refreshRequired": "The Skill is being changed or its source has changed. Refresh the list and try again.",
+ "globalScope": "Installation: global Skill",
+ "projectScope": "Project: {{project}}",
+ "trashDescription": "Local files and edits will move to the trash and can be restored.",
+ "unlinkDescription": "Only the local skill entry will be removed. Original files and edits will be kept.",
+ "sharedImpact": "Other Agents sharing this skill will also be affected. Published versions and installations elsewhere are unaffected.",
+ "managedElsewhere": "This Skill belongs to another package or shared directory. Remove it at its source.",
+ "cleanupIncomplete": "The skill was removed, but some local records or links could not be cleaned up.",
+ "retryCleanup": "Retry cleanup",
+ "cleanupComplete": "Cleanup completed"
}
},
"makerExperimental": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 1a300664be..c9ead36be6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -10645,6 +10645,7 @@
}
},
"commandPalette": {
+ "viewSkillDetails": "スキルの詳細を見る",
"projectSkillNotLoaded": "現在の Pi タスクでは、このプロジェクト Skill はまだ読み込まれていません。新しいタスクでは自動的に読み込みを試みます。"
},
"skillhub": {
@@ -10803,10 +10804,10 @@
"market": "Market に戻る",
"skillhub": "SkillHub に戻る"
},
- "uninstall": "アンインストール",
+ "uninstall": "スキルをアンインストール",
"uninstallDialog": {
- "title": "{{name}} をアンインストールしますか?",
- "description": "ローカルフォルダを削除します\n{{path}}\nこの操作は取り消せません。",
+ "title": "「{{name}}」をアンインストールしますか?",
+ "description": "ローカルファイルと編集内容をゴミ箱に移動します。復元できます。\n\nこのスキルを共有する他の Agent にも影響します。公開済みバージョンや別の場所のインストールには影響しません。",
"confirm": "アンインストール",
"cancel": "キャンセル"
},
@@ -11205,6 +11206,26 @@
"marketEdit": {
"saved": "マーケット表示情報を保存しました",
"displayNameRequired": "表示名を入力してください"
+ },
+ "management": {
+ "disabled": "無効",
+ "enabledLabel": "スキル「{{name}}」を有効にする",
+ "moreLabel": "スキル「{{name}}」を管理",
+ "activationHint": "Cindy 内のスキルの読み込みにのみ適用されます。Agent の起動または再起動後に反映されます。",
+ "enabledToast": "スキル「{{name}}」を有効にしました。Agent の起動または再起動後に反映されます",
+ "disabledToast": "スキル「{{name}}」を無効にしました。Agent の起動または再起動後に反映されます",
+ "toggleFailed": "スキルの設定を保存できませんでした。もう一度お試しください",
+ "uninstallFailed": "スキルをゴミ箱に移動できませんでした。ファイルのアクセス権を確認して再試行してください",
+ "refreshRequired": "スキルの変更中、または読み込み元が変更されています。一覧を更新して再試行してください",
+ "globalScope": "インストール先: グローバルスキル",
+ "projectScope": "プロジェクト: {{project}}",
+ "trashDescription": "ローカルファイルと編集内容をゴミ箱に移動します。復元できます。",
+ "unlinkDescription": "ローカルのスキル登録のみを削除します。元のファイルと編集内容は保持されます。",
+ "sharedImpact": "このスキルを共有する他の Agent にも影響します。公開済みバージョンや別の場所のインストールには影響しません。",
+ "managedElsewhere": "このスキルは別のパッケージまたは共有ディレクトリで管理されています。提供元で削除してください",
+ "cleanupIncomplete": "スキルは削除されましたが、一部のローカル記録またはリンクを整理できませんでした。",
+ "retryCleanup": "整理を再試行",
+ "cleanupComplete": "整理が完了しました"
}
},
"makerExperimental": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1588a647d3..52ffb483c0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -10645,6 +10645,7 @@
}
},
"commandPalette": {
+ "viewSkillDetails": "스킬 상세 보기",
"projectSkillNotLoaded": "현재 Pi 작업에는 이 프로젝트 Skill이 아직 로드되지 않았습니다. 새 작업에서는 자동으로 로드를 시도합니다."
},
"skillhub": {
@@ -10803,11 +10804,11 @@
"market": "Market 으로 돌아가기",
"skillhub": "SkillHub 로 돌아가기"
},
- "uninstall": "제거",
+ "uninstall": "스킬 제거",
"uninstallDialog": {
- "title": "{{name}} 을 제거하시겠습니까?",
- "description": "로컬 폴더를 삭제합니다\n{{path}}\n이 작업은 되돌릴 수 없습니다.",
- "confirm": "제거 확인",
+ "title": "“{{name}}”을 제거하시겠습니까?",
+ "description": "로컬 파일과 수정 내용을 휴지통으로 옮깁니다. 복원할 수 있습니다.\n\n이 스킬을 공유하는 다른 Agent도 영향을 받습니다. 게시된 버전과 다른 위치에 설치된 스킬에는 영향을 주지 않습니다.",
+ "confirm": "제거",
"cancel": "취소"
},
"uninstalledToast": "{{name}} 이 제거되었습니다",
@@ -11205,6 +11206,26 @@
"marketEdit": {
"saved": "마켓 표시 정보가 저장되었습니다",
"displayNameRequired": "표시 이름을 입력하세요"
+ },
+ "management": {
+ "disabled": "비활성화됨",
+ "enabledLabel": "스킬 “{{name}}” 활성화",
+ "moreLabel": "스킬 “{{name}}” 관리",
+ "activationHint": "Cindy 내 스킬 로드에만 적용됩니다. Agent를 시작하거나 다시 시작하면 반영됩니다.",
+ "enabledToast": "스킬 “{{name}}”이 활성화되었습니다. Agent를 시작하거나 다시 시작하면 반영됩니다",
+ "disabledToast": "스킬 “{{name}}”이 비활성화되었습니다. Agent를 시작하거나 다시 시작하면 반영됩니다",
+ "toggleFailed": "스킬 설정을 저장하지 못했습니다. 다시 시도하세요",
+ "uninstallFailed": "스킬을 휴지통으로 옮기지 못했습니다. 파일 권한을 확인한 후 다시 시도하세요",
+ "refreshRequired": "스킬이 변경 중이거나 원본 위치가 변경되었습니다. 목록을 새로 고친 후 다시 시도하세요",
+ "globalScope": "설치 위치: 전역 스킬",
+ "projectScope": "프로젝트: {{project}}",
+ "trashDescription": "로컬 파일과 수정 내용을 휴지통으로 옮깁니다. 복원할 수 있습니다.",
+ "unlinkDescription": "로컬 스킬 등록만 제거합니다. 원본 파일과 수정 내용은 유지됩니다.",
+ "sharedImpact": "이 스킬을 공유하는 다른 Agent도 영향을 받습니다. 게시된 버전과 다른 위치에 설치된 스킬에는 영향을 주지 않습니다.",
+ "managedElsewhere": "이 스킬은 다른 패키지 또는 공유 디렉터리에서 관리됩니다. 원본 위치에서 제거하세요",
+ "cleanupIncomplete": "스킬은 제거되었지만 일부 로컬 기록이나 링크를 정리하지 못했습니다.",
+ "retryCleanup": "정리 다시 시도",
+ "cleanupComplete": "정리 완료"
}
},
"makerExperimental": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index ecdf3cfb99..a6a161cdd1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -10645,6 +10645,7 @@
}
},
"commandPalette": {
+ "viewSkillDetails": "查看技能详情",
"projectSkillNotLoaded": "当前 Pi 任务尚未加载此项目 Skill,新任务会自动尝试加载"
},
"skillhub": {
@@ -10803,11 +10804,11 @@
"market": "返回 Market",
"skillhub": "返回 SkillHub"
},
- "uninstall": "卸载",
+ "uninstall": "卸载技能",
"uninstallDialog": {
- "title": "卸载 {{name}}?",
- "description": "将删除本地文件夹\n{{path}}\n此操作不可撤销。",
- "confirm": "确认卸载",
+ "title": "卸载「{{name}}」?",
+ "description": "本地文件及修改将移入回收站,可恢复。\n\n共用此技能的其他 Agent 也会受影响。云端发布和其他安装位置不受影响。",
+ "confirm": "卸载",
"cancel": "取消"
},
"uninstalledToast": "{{name}} 已卸载",
@@ -11205,6 +11206,26 @@
"marketEdit": {
"saved": "市场展示信息已保存",
"displayNameRequired": "显示名不能为空"
+ },
+ "management": {
+ "disabled": "已禁用",
+ "enabledLabel": "启用技能「{{name}}」",
+ "moreLabel": "管理技能「{{name}}」",
+ "activationHint": "仅控制 Cindy 内的技能加载,新开或重启 Agent 后生效",
+ "enabledToast": "已启用技能「{{name}}」,新开或重启 Agent 后生效",
+ "disabledToast": "已禁用技能「{{name}}」,新开或重启 Agent 后生效",
+ "toggleFailed": "无法保存技能开关,请重试",
+ "uninstallFailed": "无法将技能移入回收站,请检查文件权限后重试",
+ "refreshRequired": "技能正在变更或来源已改变,请刷新列表后重试",
+ "globalScope": "安装位置:全局技能",
+ "projectScope": "项目:{{project}}",
+ "trashDescription": "本地文件及修改将移入回收站,可恢复。",
+ "unlinkDescription": "仅移除本地技能入口,原文件及修改会保留。",
+ "sharedImpact": "共用此技能的其他 Agent 也会受影响。云端发布和其他安装位置不受影响。",
+ "managedElsewhere": "此技能由其他包或共享目录管理,需在其来源处移除",
+ "cleanupIncomplete": "技能已移除,但部分本地记录或链接未清理完成。",
+ "retryCleanup": "重试清理",
+ "cleanupComplete": "清理完成"
}
},
"makerExperimental": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 17e0a594ec..a7c75da91e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -10645,6 +10645,7 @@
}
},
"commandPalette": {
+ "viewSkillDetails": "查看技能詳情",
"projectSkillNotLoaded": "目前的 Pi 任務尚未載入此專案 Skill,新任務會自動嘗試載入"
},
"skillhub": {
@@ -10803,11 +10804,11 @@
"market": "返回 Market",
"skillhub": "返回 SkillHub"
},
- "uninstall": "解除安裝",
+ "uninstall": "解除安裝技能",
"uninstallDialog": {
- "title": "解除安裝 {{name}}?",
- "description": "將刪除本地資料夾\n{{path}}\n此操作不可撤銷。",
- "confirm": "確認解除安裝",
+ "title": "解除安裝「{{name}}」?",
+ "description": "本機檔案及修改將移至垃圾桶,可還原。\n\n共用此技能的其他 Agent 也會受影響。雲端發布和其他安裝位置不受影響。",
+ "confirm": "解除安裝",
"cancel": "取消"
},
"uninstalledToast": "{{name}} 已解除安裝",
@@ -11205,6 +11206,26 @@
"marketEdit": {
"saved": "市場展示資訊已儲存",
"displayNameRequired": "顯示名不能為空"
+ },
+ "management": {
+ "disabled": "已停用",
+ "enabledLabel": "啟用技能「{{name}}」",
+ "moreLabel": "管理技能「{{name}}」",
+ "activationHint": "僅控制 Cindy 內的技能載入,開啟或重新啟動 Agent 後生效",
+ "enabledToast": "已啟用技能「{{name}}」,開啟或重新啟動 Agent 後生效",
+ "disabledToast": "已停用技能「{{name}}」,開啟或重新啟動 Agent 後生效",
+ "toggleFailed": "無法儲存技能開關,請重試",
+ "uninstallFailed": "無法將技能移至系統垃圾桶,請檢查檔案權限後重試",
+ "refreshRequired": "技能正在變更或來源已改變,請重新整理清單後重試",
+ "globalScope": "安裝位置:全域技能",
+ "projectScope": "專案:{{project}}",
+ "trashDescription": "本機檔案及修改將移至垃圾桶,可還原。",
+ "unlinkDescription": "僅移除本機技能入口,原始檔案及修改會保留。",
+ "sharedImpact": "共用此技能的其他 Agent 也會受影響。雲端發布和其他安裝位置不受影響。",
+ "managedElsewhere": "此技能由其他套件或共用目錄管理,需在其來源處移除",
+ "cleanupIncomplete": "技能已移除,但部分本機記錄或連結尚未清理完成。",
+ "retryCleanup": "重試清理",
+ "cleanupComplete": "清理完成"
}
},
"makerExperimental": {
diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsx
index d9a8e0e439..6b74056ad3 100644
--- a/apps/desktop/src/renderer/router.tsx
+++ b/apps/desktop/src/renderer/router.tsx
@@ -156,6 +156,7 @@ export const router = createHashRouter([
index: true,
element: <SkillhubHomeView />,
},
+ { path: 'by-path', element: <SkillhubDetailView /> },
{ path: ':kind/global/:name', element: <SkillhubDetailView /> },
{
path: ':kind/project/:projectHash/:name',
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index b4644f9aea..5aab64a422 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3162,6 +3162,8 @@ interface ElectronAPI {
// ── SkillHub (xdt-maker-技能中心 v0.2) ──
skillhub: {
+ setEnabled: (params: { absolutePath: string; enabled: boolean }) => Promise<{ cindyEnabled: boolean }>;
+ onLocalStateChanged: (callback: () => void) => () => void;
scan: (params: { projects?: SkillhubProjectInput[] }) => Promise<{
success: boolean;
error?: string;
@@ -3499,7 +3501,9 @@ interface ElectronAPI {
cancelInstall: (name: string) => Promise<{ success: boolean }>;
uninstall: (
absolutePath: string,
- ) => Promise<{ success: true } | { success: false; errorCode: string; message: string }>;
+ ) => Promise<{ success: true; cleanupToken?: string } | { success: false; errorCode: string; message: string }>;
+ retryUninstallCleanup: (token: string) => Promise<{ complete: boolean }>;
+
/** 在 main 内选择并检查本地包,成功时签发绑定当前 renderer 的短期导入授权。 */
pickLocal: () => Promise<
| { success: true; canceled: true }
@@ -6637,6 +6641,10 @@ interface SkillhubFileEntry {
}
interface SkillhubSkill {
+ cindyEnabled?: boolean;
+ canUninstall?: boolean;
+ uninstallLinkOnly?: boolean;
+ discoveryPaths?: string[];
id: string;
/** URL 匹配键 — 不含 engine,和路由格式一致,用于侧栏选中高亮。 */
urlKey: string;
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 90e87ce84c..ad7d7d4c09 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -7,6 +7,8 @@
* - 持有依赖注入的 deps,但具体使用由子类决定
*/
+import { isSkillDisabled } from './shared/skill-activation.js';
+
import type {
AgentEvent,
InteractionDecision,
@@ -575,6 +577,8 @@ export interface PiSubagentRunnerLaunchRequest {
}
export interface AgentDeps {
+ /** Cindy-only local Skill overrides. Freeze at native runtime startup; never apply to SSH. */
+ getDisabledSkillPaths?: () => readonly string[];
/** Optional low-I/O, provider-neutral turn change recorder supplied by the host. */
turnChangeCapture?: TurnChangeCaptureHooks;
auth: AuthAdapter;
@@ -2317,6 +2321,14 @@ export abstract class BaseAgent {
return [];
}
+ /** Filter only the palette projection; management discovery retains disabled sources. */
+ filterActiveSkillCommands(result: ListAgentSkillsResult, remoteHostId?: string): ListAgentSkillsResult {
+ const disabled = remoteHostId ? [] : this.deps.getDisabledSkillPaths?.() ?? [];
+ if (disabled.length === 0) return result;
+ return { ...result, skills: result.skills.filter((skill) => !skill.path || !isSkillDisabled(skill.path, disabled)) };
+ }
+
+
/**
* Agent 用户/项目目录扫描出的 skill 列表 —— ChatInput `/` palette 的
* 'agent-skill' 类目。
@@ -2325,6 +2337,7 @@ export abstract class BaseAgent {
* app-server skills/list。子类自己负责缓存策略与未授权静默处理。
* 默认无实现, 不暴露任何 skill。
*/
+
async listAgentSkills(opts: ListAgentSkillsOptions): Promise<ListAgentSkillsResult> {
void opts;
return { skills: [] };
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 6ab7656236..3f6acbf26c 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -173,6 +173,7 @@ import type {
MemoryResetResult,
} from '../../types/memory.js';
import type { McpProviderContext } from '../../interfaces/mcp-provider.js';
+import { claudeDisabledSkillOverrides } from '../shared/skill-activation.js';
import { scanClaudeCustomizations } from './customization-scanner.js';
import {
REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS,
@@ -2366,6 +2367,13 @@ export class ClaudeCodeAgent extends BaseAgent {
// (eg. summarized reasoning UI 本地有 remote 没)。getter 让 memOverride /
// mutableFastMode 读最新值 (setMemory / setFastMode 运行时改) 而不是 buildQuery
// 时快照。装配逻辑(含 apiKeyHelper 恒置空的鉴权防线)在 flag-settings.ts。
+ const disabledSkillPaths = opts.remoteHostId || opts.botRuntimeProfile || reviewMode
+ ? [] : [...(this.deps.getDisabledSkillPaths?.() ?? [])];
+ const disabledSkillOverrides = disabledSkillPaths.length > 0
+ ? claudeDisabledSkillOverrides((await scanClaudeCustomizations({
+ workingDirs: [opts.workingDir], kinds: ['skill'],
+ })).items, disabledSkillPaths)
+ : {};
const buildSettings = (): Settings => {
const settings = buildClaudeFlagSettings({
showThinkingSummaries,
@@ -2383,6 +2391,9 @@ export class ClaudeCodeAgent extends BaseAgent {
botSkillPolicy: reviewMode ? undefined : opts.botRuntimeProfile?.skillPolicy,
capabilityRouting: reviewMode ? undefined : this.deps.capabilityRouting,
});
+ if (Object.keys(disabledSkillOverrides).length > 0) {
+ settings.skillOverrides = { ...settings.skillOverrides, ...disabledSkillOverrides };
+ }
if (!reviewMode) return settings;
return {
...settings,
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index d1b570946b..c177eaa634 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -41,6 +41,7 @@ import {
type SendOptions,
type TurnPermissionPolicy,
} from '../base-agent.js';
+import { skillEntryPath } from '../shared/skill-activation.js';
import type { AgentCredentialMode } from '../../interfaces/auth-adapter.js';
import type {
Capabilities,
@@ -4821,6 +4822,28 @@ export class CodexAgent extends BaseAgent {
reviewMode ? undefined : opts.botRuntimeProfile?.skillPolicy,
),
);
+ const disabledSkillPaths = opts.remoteHostId || opts.botRuntimeProfile || reviewMode
+ ? [] : this.deps.getDisabledSkillPaths?.() ?? [];
+ if (disabledSkillPaths.length > 0) {
+ try {
+ const response = await host.request<{ config?: Record<string, unknown> }>(
+ Method.ConfigRead, { cwd: opts.workingDir, includeLayers: false },
+ { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },
+ );
+ assertCurrentHost('Local Skill configuration');
+ const nativeSkills = asRecord(response.config?.skills).config;
+ capabilityRoutingConfig = mergeCodexSkillConfigOverrides(
+ mergeCodexSkillConfigOverrides(
+ Array.isArray(nativeSkills) ? { 'skills.config': nativeSkills } : {},
+ capabilityRoutingConfig,
+ ),
+ { 'skills.config': disabledSkillPaths.map((source) => ({ path: skillEntryPath(source), enabled: false })) },
+ );
+ } catch (error) {
+ releaseHostBindingLeaseIfNeeded();
+ throw new Error(`Cannot prepare local Skill configuration: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
capabilityRoutingConfig = {
...capabilityRoutingConfig,
...botMcpConfig,
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
index 58c44c5bcc..9d8d0d8210 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
@@ -16,6 +16,7 @@ import {
readFileSync,
realpathSync,
rmSync,
+ symlinkSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
@@ -25,6 +26,7 @@ import { StringDecoder } from 'node:string_decoder';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, it } from 'vitest';
+import { applyPiDisabledSkillSettings, piDisabledDiscoveryPaths } from '../skill-activation.js';
import { scanPiCustomizations } from '../customization-scanner.js';
import { capturePiRuntimeCapabilityManifest } from '../runtime-capabilities.js';
@@ -651,6 +653,36 @@ describe('Pi RPC resource-discovery harness lifecycle', () => {
});
describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts', () => {
+ it('applies session-local Skill exclusions without removing native package resources', async () => {
+ const fixture = await createFixture('pi-rpc-skill-exclusions-');
+ const hiddenGlobal = path.join(fixture.configHome, 'skills', 'global-skill', 'SKILL.md');
+ const packageRoot = path.join(fixture.root, 'native-package');
+ writeSkill(path.join(packageRoot, 'skills', 'package-on'), 'package-on');
+ writeSkill(path.join(packageRoot, 'skills', 'package-off'), 'package-off');
+ writeFileSync(path.join(packageRoot, 'package.json'), JSON.stringify({ name: 'fixture-native', pi: { skills: ['./skills'] } }));
+ const external = path.join(fixture.root, 'external', 'alias-source');
+ writeSkill(external, 'alias-source');
+ symlinkSync(external, path.join(fixture.configHome, 'skills', 'alias-link'), process.platform === 'win32' ? 'junction' : 'dir');
+ const settingsPath = path.join(fixture.configHome, 'settings.json');
+ writeFileSync(settingsPath, JSON.stringify(applyPiDisabledSkillSettings({ packages: [packageRoot] }, piDisabledDiscoveryPaths([
+ hiddenGlobal, external, path.join(packageRoot, 'skills', 'package-off', 'SKILL.md'),
+ ], [path.join(fixture.configHome, 'skills')]))));
+ const options = { binaryPath: PI_BINARY, cwd: fixture.workingDir,
+ configHome: fixture.configHome, sessionDir: fixture.sessionDir, approve: false };
+ const disabled = await runGetCommands(options);
+ const names = disabled.commands.map((command) => command.name);
+ expect(names).not.toContain('skill:global-skill');
+ expect(names).not.toContain('skill:package-off');
+ expect(names).not.toContain('skill:alias-source');
+ expect(names).toContain('skill:package-on');
+ expect(existsSync(hiddenGlobal)).toBe(true);
+ writeFileSync(settingsPath, JSON.stringify({ packages: [packageRoot] }));
+ const enabled = await runGetCommands(options);
+ expect(enabled.commands.map((command) => command.name)).toEqual(expect.arrayContaining([
+ 'skill:global-skill', 'skill:package-off', 'skill:package-on',
+ ]));
+ });
+
it('records isolated global skills and omits unapproved project resources', async () => {
const fixture = await createFixture('pi-rpc-no-trust-');
const result = await runGetCommands({
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index dceb8267e6..336d56c60c 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -129,6 +129,7 @@ import {
toolAutoReviewAction,
type AutoReviewDecision,
} from '../shared/auto-review-decision.js';
+import { applyPiDisabledSkillSettings, filterPiDisabledProjectSkills, piDisabledDiscoveryPaths } from './skill-activation.js';
import type { ReviewableAction } from '../shared/auto-review.js';
import { buildMemoryScopeKey } from '../../memory/storage.js';
import { MAKER_MEMORY_RULES } from '../../memory/system-prompt.js';
@@ -1675,7 +1676,20 @@ export class PiAgent extends BaseAgent {
? Promise.resolve(null)
: readOrNull(stableUserSettingsPath),
]);
- return mergePiUserSettingsPassthrough(built, sessionContent, stableContent);
+ const merged = mergePiUserSettingsPassthrough(built, sessionContent, stableContent);
+ // Preserve the session-frozen native Skill exclusions across model/settings rewrites.
+ // Never import controller/global Skill configuration into a remote runtime.
+ if (sessionContent) {
+ try {
+ const previous = JSON.parse(sessionContent) as { skills?: unknown };
+ if (Array.isArray(previous.skills)) {
+ return JSON.stringify(applyPiDisabledSkillSettings(JSON.parse(merged),
+ previous.skills.filter((item): item is string => typeof item === 'string' && item.startsWith('-')).map((item) => item.slice(1)),
+ ), null, 2) + '\n';
+ }
+ } catch { /* Malformed prior runtime settings do not replace the rebuilt settings. */ }
+ }
+ return merged;
}
private async writePiRuntimeSettings(
@@ -3031,6 +3045,8 @@ export class PiAgent extends BaseAgent {
// snapshot. Freeze it once per new runtime, then assemble only its eligible
// skills. Missing/throwing authorities and paths fail closed; never infer
// approval from permission mode, MCP/plugin state, or caller vendor options.
+ const disabledSkillPaths = opts.remoteHostId || opts.botRuntimeProfile || reviewMode
+ ? [] : [...(this.deps.getDisabledSkillPaths?.() ?? [])];
let projectResourceAssembly = unavailablePiProjectResourceAssembly(
reviewMode ? 'review-mode-project-resources-disabled' : 'approval-resolver-unavailable',
);
@@ -3042,6 +3058,7 @@ export class PiAgent extends BaseAgent {
...(opts.remoteHostId ? { remoteHostId: opts.remoteHostId } : {}),
});
projectResourceAssembly = await assembleApprovedPiProjectResources(trustInput, opts.workingDir);
+ projectResourceAssembly = filterPiDisabledProjectSkills(projectResourceAssembly, disabledSkillPaths);
projectResourceAssembly = await stageApprovedPiProjectResources(projectResourceAssembly, configHome);
} catch {
projectResourceAssembly = unavailablePiProjectResourceAssembly('approval-resolver-failed');
@@ -3120,6 +3137,15 @@ export class PiAgent extends BaseAgent {
}
}
+ if (disabledSkillPaths.length > 0) {
+ const settingsPath = path.join(configHome, 'settings.json');
+ const settings = JSON.parse(await fs.readFile(settingsPath, 'utf8'));
+ await fs.writeFile(settingsPath, JSON.stringify(applyPiDisabledSkillSettings(settings, piDisabledDiscoveryPaths(disabledSkillPaths, [
+ path.join(configHome, 'skills'), path.join(os.homedir(), '.agents', 'skills'),
+ ...managedPackageResources.skills.map((skill) => skill.path),
+ ])), null, 2) + '\n', { mode: 0o600 });
+ }
+
const nativePackageRoots = nativePackagePaths.map((entry) => (
typeof entry === 'string' ? entry : entry.source
));
diff --git a/packages/maker-core/src/agents/pi/skill-activation.ts b/packages/maker-core/src/agents/pi/skill-activation.ts
new file mode 100644
index 0000000000..7952fb8a09
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/skill-activation.ts
@@ -0,0 +1,78 @@
+import path from 'node:path';
+import fs from 'node:fs';
+import { canonicalSkillPath, isSkillDisabled, skillEntryPath } from '../shared/skill-activation.js';
+import type { PiProjectResourceAssemblySnapshot } from './project-resource-assembly.js';
+
+/** Remove explicitly disabled sources while keeping all provenance arrays aligned. */
+export function filterPiDisabledProjectSkills(
+ assembly: PiProjectResourceAssemblySnapshot,
+ disabled: readonly string[],
+): PiProjectResourceAssemblySnapshot {
+ if (disabled.length === 0) return assembly;
+ const indices = new Set(assembly.skillPaths.flatMap((source, index) =>
+ isSkillDisabled(source, disabled) ? [] : [index]));
+ return Object.freeze({
+ ...assembly,
+ skillPaths: Object.freeze(assembly.skillPaths.filter((_, index) => indices.has(index))),
+ launchSkillPaths: Object.freeze(assembly.launchSkillPaths.filter((_, index) => indices.has(index))),
+ launchSkillDigests: Object.freeze(assembly.launchSkillDigests.filter((_, index) => indices.has(index))),
+ launchSkillSourceFingerprints: Object.freeze(assembly.launchSkillSourceFingerprints.filter((_, index) => indices.has(index))),
+ });
+}
+
+/** Resolve only disabled identities to Pi's lexical discovery paths (including symlinks).
+ * This does not select what may load: native Pi remains the resource loader.
+ */
+export function piDisabledDiscoveryPaths(disabled: readonly string[], roots: readonly string[]): string[] {
+ const result = new Set(disabled);
+ const visit = (entry: string, ancestors: Set<string>) => {
+ try {
+ const key = canonicalSkillPath(entry);
+ if (isSkillDisabled(entry, disabled)) { result.add(entry); return; }
+ if (!fs.statSync(entry).isDirectory() || ancestors.has(key)) return;
+ if (fs.existsSync(path.join(entry, 'SKILL.md')) || fs.existsSync(path.join(entry, 'skill.md'))) return;
+ const next = new Set([...ancestors, key]);
+ for (const child of fs.readdirSync(entry)) {
+ if (!child.startsWith('.')) visit(path.join(entry, child), next);
+ }
+ } catch { /* Missing/unreadable discovery roots are handled by native Pi. */ }
+ };
+ if (disabled.length > 0) for (const root of roots) visit(root, new Set());
+ return [...result];
+}
+
+/** Pi filters ordinary resources and package resources independently. Preserve native package filters. */
+export function applyPiDisabledSkillSettings(
+ settings: Record<string, unknown>,
+ disabled: readonly string[],
+): Record<string, unknown> {
+ if (disabled.length === 0) return settings;
+ const entryPaths = [...new Set(disabled.flatMap((source) => [
+ skillEntryPath(source), skillEntryPath(canonicalSkillPath(source)),
+ ]))];
+ const packages = Array.isArray(settings.packages) ? settings.packages.map((entry: unknown) => {
+ const spec = typeof entry === 'string' ? { source: entry } : entry;
+ if (!spec || typeof spec !== 'object' || !('source' in spec)
+ || typeof spec.source !== 'string' || !path.isAbsolute(spec.source)) return entry;
+ const root = spec.source;
+ const exclusions = entryPaths.flatMap((file) => {
+ const relative = path.relative(root, file);
+ return relative && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)
+ ? [`-${relative.split(path.sep).join('/')}`,
+ ...(path.basename(relative).toLowerCase() === 'skill.md'
+ ? [`-${path.dirname(relative).split(path.sep).join('/')}`] : [])] : [];
+ });
+ if (exclusions.length === 0) return entry;
+ const configured = 'skills' in spec ? spec.skills : undefined;
+ // An explicit empty array already disables all package Skills. Never widen it.
+ if (Array.isArray(configured) && configured.length === 0) return entry;
+ return { ...spec, skills: [...(Array.isArray(configured) ? configured : ['**/*']), ...exclusions] };
+ }) : undefined;
+ return {
+ ...settings,
+ skills: [...(Array.isArray(settings.skills) ? settings.skills : []), ...entryPaths.flatMap((file) => [
+ `-${file}`, ...(path.basename(file).toLowerCase() === 'skill.md' ? [`-${path.dirname(file)}`] : []),
+ ])],
+ ...(packages ? { packages } : {}),
+ };
+}
diff --git a/packages/maker-core/src/agents/shared/skill-activation.integration.test.ts b/packages/maker-core/src/agents/shared/skill-activation.integration.test.ts
new file mode 100644
index 0000000000..7d272614d7
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/skill-activation.integration.test.ts
@@ -0,0 +1,113 @@
+/** Native configuration contract, with disposable HOME and no model requests or user credentials. */
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { afterEach, describe, expect, it } from 'vitest';
+import { claudeDisabledSkillOverrides, skillEntryPath } from './skill-activation.js';
+
+const repo = fileURLToPath(new URL('../../../../..', import.meta.url));
+const suffix = process.platform === 'win32' ? '.exe' : '';
+const binary = (name: string) => path.join(repo, 'apps', `${name}-bin`, `${process.platform}-${process.arch}`, `${name === 'claude-code' ? 'claude' : name}${suffix}`);
+const roots: string[] = [];
+afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
+function fixture() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-native-skill-policy-'));
+ roots.push(root);
+ const home = path.join(root, 'home');
+ const cwd = path.join(root, 'project');
+ fs.mkdirSync(home); fs.mkdirSync(cwd);
+ return { root, home, cwd };
+}
+function writeSkill(dir: string, name: string) {
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: Disposable test Skill\n---\nTest only.\n`);
+}
+function rpc(args: { binary: string; args: string[]; cwd: string; env: NodeJS.ProcessEnv; initial: unknown;
+ onMessage: (value: any, send: (request: unknown) => void) => unknown | undefined }): Promise<any> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(args.binary, args.args, { cwd: args.cwd, env: args.env, stdio: ['pipe', 'pipe', 'pipe'] });
+ let result: unknown;
+ let failure: Error | undefined;
+ let buffer = '';
+ let stderr = '';
+ const timer = setTimeout(() => { failure = new Error('Native Skill discovery timed out'); child.kill('SIGKILL'); }, 15_000);
+ const send = (request: unknown) => child.stdin.write(JSON.stringify(request) + '\n');
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-1000); });
+ child.stdout.on('data', (chunk) => {
+ buffer += chunk.toString();
+ let newline: number;
+ while ((newline = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);
+ if (!line.trim() || result !== undefined) continue;
+ try {
+ result = args.onMessage(JSON.parse(line), send);
+ if (result !== undefined) child.kill();
+ } catch (error) { failure = error as Error; child.kill(); }
+ }
+ });
+ child.on('error', (error) => { failure = error; });
+ child.on('close', () => {
+ clearTimeout(timer);
+ if (failure || result === undefined) reject(failure ?? new Error(`Native discovery exited: ${stderr}`));
+ else resolve(result);
+ });
+ send(args.initial);
+ });
+}
+function safeEnv(home: string): NodeJS.ProcessEnv {
+ return { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, TEMP: os.tmpdir(), TMP: os.tmpdir(), HOME: home, USERPROFILE: home };
+}
+
+describe('pinned native Skill activation', () => {
+ it.skipIf(!fs.existsSync(binary('claude-code')))('Claude disables by directory identity even when the frontmatter name differs', async () => {
+ const { home, cwd } = fixture();
+ const source = path.join(home, '.claude', 'skills', 'directory-name');
+ writeSkill(source, 'native-name');
+ const env = { ...safeEnv(home), CLAUDE_CONFIG_DIR: path.join(home, '.claude'),
+ ANTHROPIC_API_KEY: 'fixture-only', ANTHROPIC_BASE_URL: 'http://127.0.0.1:9', CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1' };
+ const commands = async (disabled: string[]) => rpc({ binary: binary('claude-code'), cwd, env,
+ args: ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--settings', JSON.stringify({
+ apiKeyHelper: '', skillOverrides: claudeDisabledSkillOverrides([
+ { engine: 'claude-code', kind: 'skill', scope: 'global', name: 'directory-name', absolutePath: source },
+ ], disabled),
+ })],
+ initial: { type: 'control_request', request_id: 'init', request: { subtype: 'initialize' } },
+ onMessage: (data) => data.type === 'control_response' ? data.response.response.commands.map((item: { name: string }) => item.name) : undefined,
+ });
+ expect(await commands([])).toContain('native-name');
+ expect(await commands([source])).not.toContain('native-name');
+ expect(await commands([])).toContain('native-name');
+ expect(fs.existsSync(path.join(source, 'SKILL.md'))).toBe(true);
+ });
+
+ it.skipIf(!fs.existsSync(binary('codex')))('Codex matches physical Skill identity through a shared discovery link', async () => {
+ const { root, home, cwd } = fixture();
+ const config = path.join(root, 'codex-home');
+ fs.mkdirSync(config);
+ const source = path.join(root, 'external', 'source');
+ writeSkill(source, 'native-name');
+ const alias = path.join(home, '.agents', 'skills', 'alias');
+ fs.mkdirSync(path.dirname(alias), { recursive: true });
+ fs.symlinkSync(source, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ const skills = async (disabled: boolean) => {
+ fs.writeFileSync(path.join(config, 'config.toml'), disabled
+ ? `[skills]\nconfig = [{ path = ${JSON.stringify(skillEntryPath(source))}, enabled = false }]\n` : '');
+ return rpc({ binary: binary('codex'), args: ['app-server'], cwd, env: { ...safeEnv(home), CODEX_HOME: config },
+ initial: { id: 1, method: 'initialize', params: { clientInfo: { name: 'cindy_test', version: '1' }, capabilities: { experimentalApi: true } } },
+ onMessage: (data, send) => {
+ if (data.error) throw new Error(JSON.stringify(data.error));
+ if (data.id === 1) {
+ send({ method: 'initialized', params: {} });
+ send({ id: 2, method: 'skills/list', params: { cwds: [cwd], forceReload: true } });
+ }
+ return data.id === 2 ? data.result.data.flatMap((group: { skills: unknown[] }) => group.skills) : undefined;
+ },
+ });
+ };
+ expect(await skills(true)).toEqual(expect.arrayContaining([expect.objectContaining({ name: 'native-name', enabled: false })]));
+ expect(await skills(false)).toEqual(expect.arrayContaining([expect.objectContaining({ name: 'native-name', enabled: true })]));
+ expect(fs.readlinkSync(alias)).toBe(source);
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/skill-activation.test.ts b/packages/maker-core/src/agents/shared/skill-activation.test.ts
new file mode 100644
index 0000000000..b71322880c
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/skill-activation.test.ts
@@ -0,0 +1,53 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterAll, describe, expect, it } from 'vitest';
+import { canonicalSkillPath, claudeDisabledSkillOverrides, isSkillDisabled, skillEntryPath } from './skill-activation.js';
+import { filterPiDisabledProjectSkills } from '../pi/skill-activation.js';
+import type { AgentCustomization } from '../../types/customizations.js';
+
+const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-skill-activation-'));
+afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
+
+function skill(name: string, scope = 'global'): AgentCustomization {
+ const absolutePath = path.join(root, scope, name);
+ fs.mkdirSync(absolutePath, { recursive: true });
+ fs.writeFileSync(path.join(absolutePath, 'SKILL.md'), `---\nname: ${name}\ndescription: test\n---\nTest`);
+ return { engine: 'claude-code', kind: 'skill', scope, name, absolutePath };
+}
+
+describe('Cindy-only Skill activation', () => {
+ it('matches SKILL.md and directory identities without disabling an independent same-name copy', () => {
+ const global = skill('example');
+ const project = skill('example', 'project');
+ expect(isSkillDisabled(skillEntryPath(global.absolutePath), [global.absolutePath])).toBe(true);
+ expect(isSkillDisabled(project.absolutePath, [global.absolutePath])).toBe(false);
+ expect(canonicalSkillPath(skillEntryPath(global.absolutePath))).toBe(canonicalSkillPath(global.absolutePath));
+ });
+
+ it('uses the winning Claude source, leaving a same-name project Skill enabled', () => {
+ const global = skill('same');
+ const project = skill('same', 'project');
+ expect(claudeDisabledSkillOverrides([global, project], [global.absolutePath])).toEqual({});
+ expect(claudeDisabledSkillOverrides([project, global], [project.absolutePath])).toEqual({ same: 'off' });
+ expect(claudeDisabledSkillOverrides([global], [global.absolutePath])).toEqual({ same: 'off' });
+ expect(claudeDisabledSkillOverrides([global], [])).toEqual({});
+ });
+
+ it('keeps Pi source and staged provenance aligned when excluding a project Skill', () => {
+ const a = skill('one', 'pi');
+ const b = skill('two', 'pi');
+ const assembly = {
+ decision: null, skillPaths: [a.absolutePath, b.absolutePath],
+ launchSkillPaths: ['launch-one', 'launch-two'], launchSkillDigests: ['one-hash', 'two-hash'],
+ launchSkillSourceFingerprints: ['one-source', 'two-source'],
+ diagnostic: { status: 'unavailable' as const, reason: 'fixture', approvalRevision: null, requestedSkillCount: 2 },
+ };
+ const filtered = filterPiDisabledProjectSkills(assembly, [a.absolutePath]);
+ expect(filtered.skillPaths).toEqual([b.absolutePath]);
+ expect(filtered.launchSkillPaths).toEqual(['launch-two']);
+ expect(filtered.launchSkillDigests).toEqual(['two-hash']);
+ expect(filtered.launchSkillSourceFingerprints).toEqual(['two-source']);
+ expect(assembly.skillPaths).toHaveLength(2);
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/skill-activation.ts b/packages/maker-core/src/agents/shared/skill-activation.ts
new file mode 100644
index 0000000000..e7e6db90e0
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/skill-activation.ts
@@ -0,0 +1,41 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import type { AgentCustomization } from '../../types/customizations.js';
+
+/** Physical Skill identity, shared by discovery aliases and SKILL.md references. */
+export function canonicalSkillPath(value: string): string {
+ let resolved = path.resolve(value);
+ try { resolved = fs.realpathSync.native(resolved); } catch { /* Removed source: retain its identity. */ }
+ if (path.basename(resolved).toLowerCase() === 'skill.md') resolved = path.dirname(resolved);
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+}
+
+export function isSkillDisabled(source: string, disabledPaths: readonly string[]): boolean {
+ const key = canonicalSkillPath(source);
+ return disabledPaths.some((candidate) => canonicalSkillPath(candidate) === key);
+}
+
+/** Claude addresses the winning source by name; project sources override global ones. */
+export function claudeDisabledSkillOverrides(
+ items: readonly AgentCustomization[],
+ disabledPaths: readonly string[],
+): Record<string, 'off'> {
+ const winners = new Map<string, AgentCustomization>();
+ for (const item of items) {
+ if (item.kind !== 'skill') continue;
+ const previous = winners.get(item.name);
+ if (!previous || item.scope === 'project') winners.set(item.name, item);
+ }
+ return Object.fromEntries([...winners.values()]
+ .filter((item) => isSkillDisabled(item.absolutePath, disabledPaths))
+ .map((item) => [item.name, 'off' as const]));
+}
+
+/** Native Codex/Pi configuration needs the entry file, not just its containing directory. */
+export function skillEntryPath(source: string): string {
+ try {
+ if (fs.statSync(source).isFile()) return source;
+ const lower = path.join(source, 'skill.md');
+ return fs.existsSync(lower) ? lower : path.join(source, 'SKILL.md');
+ } catch { return path.join(source, 'SKILL.md'); }
+}
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index 39b5b64994..2b63efb3d8 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -126,6 +126,7 @@ function createAgent(
extraDirs: { supported: false },
},
startSession,
+ filterActiveSkillCommands: (result: unknown) => result,
async dispose() {},
} as unknown as BaseAgent;
}
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index ef19bf0d1c..69b9955875 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -1292,10 +1292,14 @@ export class Maker {
&& sessionMeta.reviewMode !== true
&& !sessionMeta.remoteHostId
));
- const result = await this.requireAgent(agentKind).listAgentSkills({
+ const agent = this.requireAgent(agentKind);
+ const filter = (result: ListAgentSkillsResult) => agent.filterActiveSkillCommands(
+ result, agentOpts.remoteHostId ?? sessionMeta?.remoteHostId ?? undefined,
+ );
+ const result = filter(await agent.listAgentSkills({
...agentOpts,
includeManagedPiPackages,
- });
+ }));
if (agentKind !== 'pi' || !sessionId) return result;
const session = this.getSession(sessionId);
if (
@@ -1305,7 +1309,7 @@ export class Maker {
) {
return result;
}
- return mergePiRuntimeSkillStatuses(result, session.getRuntimeCapabilities());
+ return filter(await mergePiRuntimeSkillStatuses(result, session.getRuntimeCapabilities()));
}
/** ChatInput `@` palette entries, routed by agent kind. */