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。

fix(skillhub): 保存停用发现入口并限制插件技能启停

xd-bobof6bb66961638
diff --git a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
index f2ef6114ae..149bb1a8e3 100644
--- a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
@@ -27,6 +27,44 @@ describe('Skill activation preferences', () => {
await reloaded.setCindySkillEnabled(b, true);
expect(reloaded.readDisabledSkillPaths()).toEqual([]);
});
+ it('persists lexical aliases across restart, bypasses wide Pi scans, and drops retargeted aliases', async () => {
+ const prefs = await import('../activationPreferences');
+ const source = path.join(root, 'external');
+ const other = path.join(root, 'other');
+ const discovery = path.join(root, '.agents', 'skills');
+ const alias = path.join(discovery, 'z-alias');
+ fs.mkdirSync(source);
+ fs.mkdirSync(other);
+ fs.mkdirSync(discovery, { recursive: true });
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'fixture');
+ fs.symlinkSync(source, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ await prefs.setCindySkillEnabled(source, false, () => true, [alias]);
+ vi.resetModules();
+ const reloaded = await import('../activationPreferences');
+ const { piDisabledDiscoveryPaths, applyPiDisabledSkillSettings } = await import(
+ '../../../../../../packages/maker-core/src/agents/pi/skill-activation');
+ const close = vi.fn();
+ const scan = vi.spyOn(fs, 'opendirSync').mockReturnValue({
+ readSync: () => ({ name: '.irrelevant' }), closeSync: close,
+ } as unknown as fs.Dir);
+ const clock = vi.spyOn(performance, 'now').mockReturnValue(0);
+ try {
+ const disabled = piDisabledDiscoveryPaths(reloaded.readDisabledSkillPaths(), [discovery]);
+ const settings = applyPiDisabledSkillSettings({}, disabled);
+ expect(settings.skills).toContain(`-${alias}`);
+ expect(close).toHaveBeenCalled();
+ } finally { scan.mockRestore(); clock.mockRestore(); }
+ fs.unlinkSync(alias);
+ fs.symlinkSync(other, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ expect(reloaded.readDisabledSkillPaths()).not.toContain(alias);
+ expect(reloaded.isCindySkillEnabled(other)).toBe(true);
+ fs.unlinkSync(alias);
+ fs.symlinkSync(source, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ await reloaded.setCindySkillEnabled(source, true);
+ expect(reloaded.readDisabledSkillPaths()).not.toContain(alias);
+ expect(reloaded.isCindySkillEnabled(source)).toBe(true);
+ });
+
it.each(['success', 'enabled-source', 'content-failure', 'preference-failure', 'owner-changed'])('migrates disabled state with a local rename (%s)', async (scenario) => {
const { renameLocalSkill } = await import('../scanner');
const { setCindySkillEnabled, readDisabledSkillPaths, skillActivationKey } = await import('../activationPreferences');
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 7509c1d62d..3e44e00b11 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -677,6 +677,12 @@ describe('registerSkillhubIpc usage handlers', () => {
.rejects.toThrow('PERMISSION_DENIED');
});
+ it('persists discovered aliases across scopes when disabling a physical Skill', async () => {
+ const { absolutePath, aliases, event } = await scanSharedAliases(false);
+ await handlers.get('skillhub:set-enabled')!(event, { absolutePath, skillId: 'entry-2', enabled: false });
+ expect(setCindySkillEnabled).toHaveBeenCalledWith(absolutePath, false, expect.any(Function), aliases);
+ });
+
it('captures differently named discovery links across scopes for physical Skill removal', async () => {
const { absolutePath, aliases, event } = await scanSharedAliases(true);
installServiceMocks.uninstall.mockResolvedValueOnce({ success: true });
@@ -699,7 +705,7 @@ describe('registerSkillhubIpc usage handlers', () => {
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));
+ expect(setCindySkillEnabled).toHaveBeenCalledWith(absolutePath, false, expect.any(Function), expect.any(Array));
await expect(handler({ sender: { id: 72 } }, { absolutePath, enabled: false }))
.rejects.toThrow('PRECONDITION_FAILED');
expect(setCindySkillEnabled).toHaveBeenCalledTimes(1);
@@ -747,6 +753,9 @@ describe('registerSkillhubIpc usage handlers', () => {
await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath: source }))
.rejects.toThrow('PRECONDITION_FAILED');
expect(installServiceMocks.uninstall).not.toHaveBeenCalled();
+ await expect(handlers.get('skillhub:set-enabled')!(event, { absolutePath: source, enabled: false }))
+ .rejects.toThrow('PRECONDITION_FAILED');
+ expect(setCindySkillEnabled).not.toHaveBeenCalled();
expect(fs.existsSync(alias)).toBe(true);
getManagedSkillRoots.mockReturnValue([]);
});
diff --git a/apps/desktop/src/main/skillhub/activationPreferences.ts b/apps/desktop/src/main/skillhub/activationPreferences.ts
index 90437affcb..70814e6aff 100644
--- a/apps/desktop/src/main/skillhub/activationPreferences.ts
+++ b/apps/desktop/src/main/skillhub/activationPreferences.ts
@@ -5,7 +5,10 @@ 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[] }
+interface SkillActivationPreferences {
+ disabledPaths: string[];
+ discoveryPaths?: Record<string, string[]>;
+}
export function skillActivationKey(source: string): string {
let resolved = path.resolve(source);
@@ -21,7 +24,12 @@ const store = createOverrideSettingsFile<SkillActivationPreferences>({
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()
- : [] };
+ : [],
+ discoveryPaths: Object.fromEntries(Object.entries((raw as SkillActivationPreferences | null)?.discoveryPaths ?? {})
+ .filter(([source, aliases]) => path.isAbsolute(source) && Array.isArray(aliases))
+ .map(([source, aliases]) => [source, aliases.filter((alias): alias is string =>
+ typeof alias === 'string' && path.isAbsolute(alias))])),
+ };
},
log: createLogger('skillhub:activation'),
label: 'skill activation',
@@ -31,18 +39,28 @@ const store = createOverrideSettingsFile<SkillActivationPreferences>({
export function readDisabledSkillPaths(): readonly string[] {
store.invalidateIfChanged();
- return store.read().disabledPaths;
+ const value = store.read();
+ return [...new Set(value.disabledPaths.flatMap((source) => [source,
+ ...(value.discoveryPaths?.[source] ?? []).filter((alias) => {
+ try { return fs.existsSync(alias) && skillActivationKey(alias) === source; }
+ catch { return false; }
+ }),
+ ]))];
}
export function isCindySkillEnabled(source: string): boolean {
return !readDisabledSkillPaths().includes(skillActivationKey(source));
}
-export async function setCindySkillEnabled(source: string, enabled: boolean, canMutate: () => boolean = () => true): Promise<void> {
+export async function setCindySkillEnabled(source: string, enabled: boolean, canMutate: () => boolean = () => true, discoveryPaths: readonly string[] = []): Promise<void> {
const key = skillActivationKey(source);
await store.updateAtomic(({ value }) => {
if (!canMutate()) throw new Error('Skill mutation context changed');
- return { disabledPaths: enabled
+ const aliases = { ...value.discoveryPaths };
+ delete aliases[key];
+ if (!enabled) aliases[key] = [...new Set([...(value.discoveryPaths?.[key] ?? []), ...discoveryPaths])]
+ .filter((alias) => path.isAbsolute(alias) && skillActivationKey(alias) === key);
+ return { discoveryPaths: aliases, disabledPaths: enabled
? value.disabledPaths.filter((item) => item !== key)
: [...new Set([...value.disabledPaths, key])].sort(),
};
@@ -61,6 +79,10 @@ export async function renameSkillWithActivation(
const newKey = skillActivationKey(destination);
const disabledPaths = value.disabledPaths.filter((key) => key !== oldKey && key !== newKey);
if (value.disabledPaths.includes(oldKey)) disabledPaths.push(newKey);
- return { disabledPaths: [...new Set(disabledPaths)].sort() };
+ const discoveryPaths = { ...value.discoveryPaths };
+ delete discoveryPaths[oldKey];
+ delete discoveryPaths[newKey];
+ if (value.disabledPaths.includes(oldKey)) discoveryPaths[newKey] = [destination];
+ return { disabledPaths: [...new Set(disabledPaths)].sort(), discoveryPaths };
});
}
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index df31c4140c..f4c26753d9 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -979,9 +979,16 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
if (typeof params?.enabled !== 'boolean') throwIpcError('INVALID_PARAMS', 'Invalid Skill state');
const record = await requireLocalSkill(event, params.absolutePath, params.skillId);
const { skill } = record;
+ if (skill.managedByPlugin || isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())) {
+ throwIpcError('PRECONDITION_FAILED', 'Manage this Skill in its plugin');
+ }
+ const discoveryPaths = (localSkillsBySender.get(event.sender.id) ?? [])
+ .filter((item) => item.physicalIdentity === record.physicalIdentity)
+ .flatMap((item) => item.skill.discoveryPaths ?? [item.skill.discoveredPath]);
const ownerId = getCurrentDataOwnerId();
const canMutate = () => {
- if (ownerId !== getCurrentDataOwnerId() || isAppSessionBoundaryPending()) return false;
+ if (ownerId !== getCurrentDataOwnerId() || isAppSessionBoundaryPending()
+ || isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())) return false;
try {
return physicalIdentity(skill.absolutePath) === record.physicalIdentity
&& (skill.discoveryPaths ?? [skill.discoveredPath]).every((alias) => physicalIdentity(alias) === record.physicalIdentity);
@@ -990,7 +997,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
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);
+ await setCindySkillEnabled(skill.absolutePath, params.enabled, canMutate, discoveryPaths);
} catch { throwIpcError('INTERNAL', 'Could not save Skill state; retry'); }
finally { release(); }
broadcastLocalChange();
diff --git a/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx b/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
index 32ede8a7ff..ff7ad23b56 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
@@ -28,7 +28,7 @@ export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
toast.error(t(`skillhub.management.${code === 'PRECONDITION_FAILED' || code === 'PERMISSION_DENIED' ? 'refreshRequired' : operation}`));
};
const toggle = async (value: boolean) => {
- if (busyRef.current || disabled) return;
+ if (busyRef.current || disabled || skill.managedByPlugin) return;
busyRef.current = true;
setBusy(true);
setPendingEnabled(value);
@@ -98,10 +98,10 @@ export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
return (
<div className="flex shrink-0 items-center gap-2" onClick={(event) => event.stopPropagation()}>
- <Tip text={`${skill.absolutePath}\n${t('skillhub.management.activationHint')}`}>
+ <Tip text={`${skill.absolutePath}\n${t(skill.managedByPlugin ? 'skillhub.management.managedByPlugin' : '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}
+ <Switch checked={enabled} disabled={busy || disabled || skill.managedByPlugin}
aria-label={t('skillhub.management.enabledLabel', { name: skill.name })}
onCheckedChange={(value) => { void toggle(value); }} />
</span>
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
index 2bf890da9e..b5d6c0069a 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/__tests__/LocalSkillControls.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/__tests__/LocalSkillControls.test.tsx
@@ -116,6 +116,10 @@ describe('Local Skill management', () => {
it('directs plugin-owned Skills to plugin management without allowing uninstall', async () => {
render(<LocalSkillControls skill={{ ...skill, canUninstall: false, managedByPlugin: true }} />);
+ const control = screen.getByRole('switch') as HTMLButtonElement;
+ expect(control.disabled).toBe(true);
+ fireEvent.click(control);
+ expect(mocks.setEnabled).not.toHaveBeenCalled();
fireEvent.keyDown(screen.getByRole('button', { name: 'skillhub.management.moreLabel' }), { key: 'Enter' });
const item = await screen.findByRole('menuitem');
expect(item.getAttribute('aria-disabled')).toBe('true');
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index bca6943194..92c16ed6ab 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -77,7 +77,9 @@ provider/model/contextWindow,因为 Pi 会用进程初始 CLI route 重建
未配置 Pi 百分比时不写 `reserveTokens`,沿用 Pi 默认 16384。
-Skill 停用适配保留用户指定的物理路径,再尽力解析发现目录中的符号链接别名;该额外扫描
+Skill 停用适配同时保存物理身份与管理页已扫描的词法发现入口;启动前只采用仍指向该
+物理身份的入口,直接加入 Pi 排除配置,不依赖重新遍历宽目录。旧偏好没有发现入口时
+仍保留物理路径,并尽力解析发现目录中的符号链接别名;该额外扫描
共享 2048 个条目、16 层深度和 100ms 的遍历预算,先检查各发现根的直接入口,再逐层
进入子目录,避免无关子树抢先耗尽预算;目录流逐项读取并在退出时关闭。
预算耗尽后保留已解析路径,不继续扫描;原生 Pi 仍负责资源加载,不能因 Cindy 的扫描
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 49f543afe3..0ec020fec6 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -40,6 +40,9 @@
- Desktop 本地技能管理用扫描条目 `id` 区分不同 scope / 项目中的同源记录;启停与卸载
的本地 IPC 可选携带 `skillId`,Main 同时匹配路径、当前发送窗口的扫描记录和项目授权,
缺省字段保留旧调用行为,不向 device-link 新开放管理能力。启停偏好仍按物理身份共享;
+ `activation-preferences.json` 的可选 `discoveryPaths` 按物理路径保存已扫描的绝对发现
+ 路径数组;缺省兼容旧偏好。启动时复核指向,启用时删除该身份的入口记录,重命名时
+ 同事务迁移到新入口。插件托管技能只能在所属插件管理,详情禁用开关,Main 拒绝独立启停。
物理卸载的清理快照汇总已扫描 scope 的同源发现链接,外部导入只移除所选 scope 的入口。
源目录形状不能单独证明归属:同一分组必须有直接、非符号链接的发现入口,才可按独立
实体卸载;检查覆盖入口、发现根及引擎配置目录各级,拒绝其中的符号链接,保留发现