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(pi): align customization scanner paths (#2134)

nanacoa3b9c7b6c819
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 45d4dc0843..356e429deb 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -383,6 +383,7 @@ import {
} from './hook-control';
import { startAccountIntegrationsAfterOwnerDbReady } from './accountIntegrationStartup';
import { registerSkillhubIpc } from './skillhub/registerIpc';
+import { listAllowedSkillhubProjectRoots } from './skillhub/allowedProjectRoots';
import { SkillhubMarketService } from './skillhub/marketService';
import { skillhubAutoSyncService } from './skillhub/autoSyncService';
import { rehydrateCloseSuppression } from './maker-host/rehydrateCloseSuppression.js';
@@ -4788,7 +4789,10 @@ const registerIpcHandlers = () => {
},
);
- registerSkillhubIpc({ getMaker: getMakerCore });
+ registerSkillhubIpc({
+ getMaker: getMakerCore,
+ getAllowedProjectRoots: listAllowedSkillhubProjectRoots,
+ });
disposeSkillhubAutoSyncAuthListener = authManager.onAuthStateChange((state) => {
if (!state.isAuthenticated) return;
void skillhubAutoSyncService.runOnceAfterLogin();
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 617f94c6e3..d8eacc4216 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -5647,7 +5647,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
async (_e, agentKind: unknown, params: unknown) => {
try {
const kind = requireAgentKind(agentKind);
- const skillParams = (params ?? {}) as { workingDir?: string; forceReload?: boolean };
+ const skillParams = (params ?? {}) as {
+ workingDir?: string;
+ forceReload?: boolean;
+ sessionId?: string;
+ };
const linksChanged = await prepareProjectSkillLinksFailSoft(skillParams?.workingDir);
if (kind === 'codex' && linksChanged) {
skillParams.forceReload = true;
diff --git a/apps/desktop/src/main/skillhub/__tests__/allowedProjectRoots.test.ts b/apps/desktop/src/main/skillhub/__tests__/allowedProjectRoots.test.ts
new file mode 100644
index 0000000000..72dbec3a0c
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/__tests__/allowedProjectRoots.test.ts
@@ -0,0 +1,18 @@
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+import { deriveAllowedSkillhubProjectRoots } from '../allowedProjectRoots';
+
+describe('deriveAllowedSkillhubProjectRoots', () => {
+ it('matches renderer grouping by folding managed and conventional worktrees to the base repo', () => {
+ const repo = path.resolve('/repo');
+ const normalizedRepo = repo.replaceAll(path.sep, '/');
+
+ expect(deriveAllowedSkillhubProjectRoots([
+ path.join(repo, '.cindy-worktrees', 'managed-task'),
+ path.join(repo, '.worktrees', 'user-task'),
+ repo,
+ null,
+ ])).toEqual([normalizedRepo]);
+ });
+});
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index d43d88f0c4..0eb1b898e4 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -32,9 +32,8 @@ vi.mock('../../security/trustedAppRenderer.js', () => ({
assertTrustedAppRendererEvent,
}));
-vi.mock('../../authManager', () => ({
- getCurrentDataOwnerId: vi.fn(() => 'local-v1'),
-}));
+const getCurrentDataOwnerId = vi.fn((): string | null => 'local-v1');
+vi.mock('../../authManager', () => ({ getCurrentDataOwnerId }));
const ensureReady = vi.fn();
const getRawDb = vi.fn(() => ({ id: 'db' }));
@@ -44,14 +43,24 @@ vi.mock('../../localDb', () => ({
}));
const readSkillRawFile = vi.fn();
+const readSkillContent = vi.fn();
+const listSkillFolderChildren = vi.fn();
+const readSkillSiblingFile = vi.fn();
+const renameLocalSkill = vi.fn();
+const scanAllSkills = vi.fn();
+const writeSkillFile = vi.fn();
+const resolveExistingSkillPathForGrant = vi.fn();
+const isExistingSkillPathGranted = vi.fn();
vi.mock('../scanner', () => ({
- listSkillFolderChildren: vi.fn(),
- readSkillContent: vi.fn(),
+ isExistingSkillPathGranted,
+ listSkillFolderChildren,
+ readSkillContent,
readSkillRawFile,
- readSkillSiblingFile: vi.fn(),
- renameLocalSkill: vi.fn(),
- scanAllSkills: vi.fn(),
- writeSkillFile: vi.fn(),
+ readSkillSiblingFile,
+ renameLocalSkill,
+ resolveExistingSkillPathForGrant,
+ scanAllSkills,
+ writeSkillFile,
}));
vi.mock('../folderHash', () => ({
@@ -78,6 +87,7 @@ vi.mock('../importLocalSkill', () => importLocalSkillMocks);
const publish = vi.fn();
const cancel = vi.fn();
const listAgentSkills = vi.fn();
+const getAllowedProjectRoots = vi.fn();
const marketService = {
deletePublished: vi.fn(),
getPublishedFiles: vi.fn(),
@@ -92,17 +102,219 @@ describe('registerSkillhubIpc usage handlers', () => {
beforeEach(async () => {
handlers.clear();
vi.clearAllMocks();
+ getCurrentDataOwnerId.mockReturnValue('local-v1');
ensureReady.mockResolvedValue({ ready: true });
requestLocalSkillUsageAnalyticsRefresh.mockReturnValue(null);
showOpenDialog.mockResolvedValue({ canceled: true, filePaths: [] });
+ getAllowedProjectRoots.mockResolvedValue(['/repo', '/old', '/new']);
+ resolveExistingSkillPathForGrant.mockImplementation((candidate: string) => (
+ candidate.includes('/authorized/demo') ? '/physical/demo' : null
+ ));
+ isExistingSkillPathGranted.mockImplementation((candidate: string, roots: Set<string>) => (
+ roots.has('/physical/demo') && candidate.includes('/authorized/demo')
+ ));
const { registerSkillhubIpc } = await import('../registerIpc');
registerSkillhubIpc({
getMaker: () => ({ listAgentSkills }) as never,
+ getAllowedProjectRoots,
marketService: marketService as never,
publishService: { publish, cancel } as never,
});
});
+ it('binds SkillHub file access to the trusted renderer latest scan', async () => {
+ const destroyedCallbacks: Array<() => void> = [];
+ const sender = {
+ id: 11,
+ once: vi.fn((event: string, callback: () => void) => {
+ if (event === 'destroyed') destroyedCallbacks.push(callback);
+ }),
+ };
+ scanAllSkills.mockResolvedValueOnce({
+ skills: [{
+ absolutePath: '/physical/demo',
+ discoveredPath: '/repo/.pi/skills/authorized/demo',
+ scope: 'project',
+ projectRoot: '/repo',
+ }],
+ sources: [],
+ });
+ readSkillContent.mockResolvedValue({ success: true, content: 'demo' });
+ listSkillFolderChildren.mockResolvedValue({ success: true, entries: [] });
+ readSkillSiblingFile.mockResolvedValue({ success: true, content: 'notes' });
+ readSkillRawFile.mockResolvedValue({ success: true, content: 'raw' });
+ writeSkillFile.mockResolvedValue({ success: true });
+ renameLocalSkill.mockResolvedValue({ success: true, newAbsolutePath: '/renamed' });
+
+ const scanResult = await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });
+
+ expect(assertTrustedAppRendererEvent).toHaveBeenCalledWith({ sender });
+ expect(resolveExistingSkillPathForGrant).toHaveBeenCalledWith(
+ '/repo/.pi/skills/authorized/demo',
+ );
+ expect(scanResult).toMatchObject({ success: true });
+ expect(sender.once).toHaveBeenCalledWith('destroyed', expect.any(Function));
+
+ const calls = [
+ ['skillhub:read-skill', { mdPath: '/repo/.pi/skills/authorized/demo/SKILL.md' }, readSkillContent],
+ ['skillhub:list-children', { dirPath: '/repo/.pi/skills/authorized/demo' }, listSkillFolderChildren],
+ ['skillhub:read-sibling-file', { filePath: '/repo/.pi/skills/authorized/demo/notes.md' }, readSkillSiblingFile],
+ ['skillhub:read-raw', { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' }, readSkillRawFile],
+ ['skillhub:write-file', { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md', content: '# Demo' }, writeSkillFile],
+ ['skillhub:rename-local', { absolutePath: '/repo/.pi/skills/authorized/demo', newName: 'renamed' }, renameLocalSkill],
+ ] as const;
+ for (const [channel, params, delegated] of calls) {
+ await handlers.get(channel)?.({ sender }, params);
+ expect(delegated).toHaveBeenCalledWith(params);
+ }
+
+ const wrongSender = await handlers.get('skillhub:read-raw')?.(
+ { sender: { id: 22 } },
+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },
+ );
+ expect(wrongSender).toMatchObject({ success: false, error: expect.stringContaining('latest SkillHub scan') });
+
+ const unscannedPath = await handlers.get('skillhub:write-file')?.(
+ { sender },
+ { filePath: '/other/.pi/skills/unscanned/SKILL.md', content: '# Injected' },
+ );
+ expect(unscannedPath).toMatchObject({ success: false, error: expect.stringContaining('latest SkillHub scan') });
+
+ scanAllSkills.mockRejectedValueOnce(new Error('scan failed'));
+ await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });
+ const afterFailedRescan = await handlers.get('skillhub:read-skill')?.(
+ { sender },
+ { mdPath: '/repo/.pi/skills/authorized/demo/SKILL.md' },
+ );
+ expect(afterFailedRescan).toMatchObject({ success: false });
+
+ destroyedCallbacks[0]?.();
+ const afterDestroy = await handlers.get('skillhub:read-skill')?.(
+ { sender },
+ { mdPath: '/repo/.pi/skills/authorized/demo/SKILL.md' },
+ );
+ expect(afterDestroy).toMatchObject({ success: false });
+ });
+
+ it('revokes project scan grants after the last active project session disappears', async () => {
+ const sender = { id: 12, once: vi.fn() };
+ scanAllSkills.mockResolvedValueOnce({
+ skills: [{
+ absolutePath: '/physical/demo',
+ discoveredPath: '/repo/.pi/skills/authorized/demo',
+ scope: 'project',
+ projectRoot: '/repo',
+ }],
+ sources: [],
+ });
+ readSkillRawFile.mockResolvedValue({ success: true, content: 'raw' });
+
+ await handlers.get('skillhub:scan')?.(
+ { sender },
+ { projects: [{ projectRoot: '/repo', hash: 'repo' }] },
+ );
+ await expect(handlers.get('skillhub:read-raw')?.(
+ { sender },
+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },
+ )).resolves.toMatchObject({ success: true });
+
+ getAllowedProjectRoots.mockResolvedValue([]);
+ await expect(handlers.get('skillhub:read-raw')?.(
+ { sender },
+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },
+ )).resolves.toMatchObject({ success: false });
+ expect(readSkillRawFile).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not let an older concurrent scan overwrite the latest sender grant', async () => {
+ let resolveOlder!: (value: unknown) => void;
+ let resolveNewer!: (value: unknown) => void;
+ const older = new Promise((resolve) => { resolveOlder = resolve; });
+ const newer = new Promise((resolve) => { resolveNewer = resolve; });
+ scanAllSkills
+ .mockReturnValueOnce(older)
+ .mockReturnValueOnce(newer);
+ resolveExistingSkillPathForGrant.mockImplementation((candidate: string) => {
+ if (candidate.includes('/old-skill')) return '/physical/old-skill';
+ if (candidate.includes('/new-skill')) return '/physical/new-skill';
+ return null;
+ });
+ isExistingSkillPathGranted.mockImplementation((candidate: string, roots: Set<string>) => (
+ (candidate.includes('/old-skill') && roots.has('/physical/old-skill'))
+ || (candidate.includes('/new-skill') && roots.has('/physical/new-skill'))
+ ));
+ readSkillRawFile.mockResolvedValue({ success: true, content: 'raw' });
+ const sender = { id: 33, once: vi.fn() };
+ const scan = handlers.get('skillhub:scan');
+
+ const olderRequest = scan?.({ sender }, { projects: [{ projectRoot: '/old', hash: 'old' }] });
+ const newerRequest = scan?.({ sender }, { projects: [{ projectRoot: '/new', hash: 'new' }] });
+ resolveNewer({
+ skills: [{ absolutePath: '/physical/new-skill', discoveredPath: '/new/.pi/skills/new-skill' }],
+ sources: [],
+ });
+ await newerRequest;
+ resolveOlder({
+ skills: [{ absolutePath: '/physical/old-skill', discoveredPath: '/old/.pi/skills/old-skill' }],
+ sources: [],
+ });
+ await olderRequest;
+
+ await expect(handlers.get('skillhub:read-raw')?.(
+ { sender },
+ { filePath: '/new/.pi/skills/new-skill/SKILL.md' },
+ )).resolves.toMatchObject({ success: true });
+ await expect(handlers.get('skillhub:read-raw')?.(
+ { sender },
+ { filePath: '/old/.pi/skills/old-skill/SKILL.md' },
+ )).resolves.toMatchObject({ success: false });
+ });
+
+ it('revokes a sender scan grant when the active data owner changes', async () => {
+ const sender = { id: 34, once: vi.fn() };
+ scanAllSkills.mockResolvedValueOnce({
+ skills: [{
+ absolutePath: '/physical/demo',
+ discoveredPath: '/repo/.pi/skills/authorized/demo',
+ }],
+ sources: [],
+ });
+ readSkillRawFile.mockResolvedValue({ success: true, content: 'raw' });
+
+ await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });
+ await expect(handlers.get('skillhub:read-raw')?.(
+ { sender },
+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },
+ )).resolves.toMatchObject({ success: true });
+
+ getCurrentDataOwnerId.mockReturnValue('local-v2');
+ await expect(handlers.get('skillhub:read-raw')?.(
+ { sender },
+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },
+ )).resolves.toMatchObject({ success: false });
+
+ getCurrentDataOwnerId.mockReturnValue('local-v1');
+ await expect(handlers.get('skillhub:read-raw')?.(
+ { sender },
+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },
+ )).resolves.toMatchObject({ success: false });
+ });
+
+ it('rejects renderer-provided project roots outside Main-owned active projects', async () => {
+ const sender = { id: 44, once: vi.fn() };
+
+ const result = await handlers.get('skillhub:scan')?.(
+ { sender },
+ { projects: [{ projectRoot: '/arbitrary', hash: 'bad' }] },
+ );
+
+ expect(result).toMatchObject({
+ success: false,
+ error: expect.stringContaining('not owned'),
+ });
+ expect(scanAllSkills).not.toHaveBeenCalled();
+ });
+
it('issues a sender-bound grant for the file selected and inspected in main', async () => {
showOpenDialog.mockResolvedValueOnce({
canceled: false,
diff --git a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts
index 42d6a64e3a..0f5e59f5e8 100644
--- a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts
@@ -11,10 +11,13 @@ vi.mock('../registry', () => ({
}));
import {
+ isExistingSkillPathGranted,
listSkillFolderChildren,
readSkillContent,
readSkillRawFile,
readSkillSiblingFile,
+ renameLocalSkill,
+ resolveExistingSkillPathForGrant,
scanAllSkills,
writeSkillFile,
} from '../scanner';
@@ -100,6 +103,169 @@ describe('scanAllSkills', () => {
});
});
+ it('gives same-name project skills from different physical sources distinct stable ids', async () => {
+ const projectRoot = path.resolve('/repo');
+ const piSkill = path.join(projectRoot, '.pi', 'skills', 'demo');
+ const agentsSkill = path.join(projectRoot, '.agents', 'skills', 'demo');
+ const items = [piSkill, agentsSkill].map((absolutePath) => ({
+ engine: 'pi' as const,
+ kind: 'skill' as const,
+ scope: 'repo' as const,
+ name: 'demo',
+ absolutePath,
+ mdPath: path.join(absolutePath, 'SKILL.md'),
+ workingDir: projectRoot,
+ runtimeStatus: 'discovered' as const,
+ files: [],
+ }));
+ const maker = {
+ listCustomizations: vi
+ .fn()
+ .mockResolvedValueOnce({ errors: [], items: [items[0]] })
+ .mockResolvedValueOnce({ errors: [], items })
+ .mockResolvedValueOnce({ errors: [], items: [items[0]] })
+ .mockResolvedValueOnce({ errors: [], items: items.toReversed() }),
+ } as unknown as Maker;
+
+ const params = { projects: [{ projectRoot, hash: 'abcd1234' }] };
+ const singleBefore = await scanAllSkills(params, maker);
+ const first = await scanAllSkills(params, maker);
+ const singleAfter = await scanAllSkills(params, maker);
+ const reversed = await scanAllSkills(params, maker);
+
+ expect(singleBefore.skills[0].id).toBe(singleAfter.skills[0].id);
+ expect(singleBefore.skills[0].sourceKey).toBeDefined();
+
+ expect(first.skills).toHaveLength(2);
+ expect(new Set(first.skills.map((skill) => skill.urlKey))).toEqual(
+ new Set(['skill:project:abcd1234:demo']),
+ );
+ expect(new Set(first.skills.map((skill) => skill.id))).toHaveLength(2);
+ expect(first.skills.every((skill) => /^[a-f0-9]{64}$/.test(skill.sourceKey ?? ''))).toBe(true);
+ expect(first.skills.every((skill) => skill.requiresSourceKey === true)).toBe(true);
+ expect(new Set(reversed.skills.map((skill) => skill.id))).toEqual(
+ new Set(first.skills.map((skill) => skill.id)),
+ );
+ });
+
+ it('keeps a shared ancestor skill in every project that discovered it', async () => {
+ const firstRoot = path.resolve('/repo/apps/first');
+ const secondRoot = path.resolve('/repo/apps/second');
+ const sharedSkill = path.resolve('/repo/.agents/skills/shared-skill');
+ const maker = {
+ listCustomizations: vi.fn(async () => ({
+ errors: [],
+ items: [firstRoot, secondRoot].map((workingDir) => ({
+ engine: 'pi' as const,
+ kind: 'skill' as const,
+ scope: 'repo',
+ name: 'shared-skill',
+ absolutePath: sharedSkill,
+ mdPath: path.join(sharedSkill, 'SKILL.md'),
+ workingDir,
+ runtimeStatus: 'discovered' as const,
+ files: [],
+ })),
+ })),
+ } as unknown as Maker;
+
+ const result = await scanAllSkills({
+ projects: [
+ { projectRoot: firstRoot, hash: 'first123' },
+ { projectRoot: secondRoot, hash: 'second456' },
+ ],
+ }, maker);
+
+ expect(result.skills).toHaveLength(2);
+ expect(result.skills.map((skill) => skill.projectHash).sort()).toEqual([
+ 'first123',
+ 'second456',
+ ]);
+ expect(result.skills.map((skill) => skill.projectRoot).sort()).toEqual([
+ firstRoot,
+ secondRoot,
+ ].sort());
+ });
+
+ it('maps a canonical scanner workingDir back to the original symlink project root', async () => {
+ const projectRoot = path.resolve('/workspace/project-link');
+ const canonicalRoot = path.resolve('/workspace/project-real');
+ const skillDir = path.join(canonicalRoot, '.pi', 'skills', 'pi-demo');
+ const realpathSyncSpy = vi.spyOn(fs, 'realpathSync').mockImplementation((value) => {
+ const candidate = String(value);
+ if (candidate === projectRoot) return canonicalRoot;
+ return candidate;
+ });
+ const maker = {
+ listCustomizations: vi.fn(async () => ({
+ errors: [],
+ items: [{
+ engine: 'pi',
+ kind: 'skill',
+ scope: 'repo',
+ name: 'pi-demo',
+ absolutePath: skillDir,
+ mdPath: path.join(skillDir, 'SKILL.md'),
+ workingDir: canonicalRoot,
+ runtimeStatus: 'discovered',
+ files: [],
+ }],
+ })),
+ } as unknown as Maker;
+
+ const result = await scanAllSkills({
+ projects: [{ projectRoot, hash: 'linked123' }],
+ }, maker);
+
+ expect(result.skills[0]).toMatchObject({
+ scope: 'project',
+ projectRoot,
+ projectHash: 'linked123',
+ });
+ realpathSyncSpy.mockRestore();
+ });
+
+ it('keeps lexical aliases of one physical project assigned to their own project entries', async () => {
+ const projectRoot = path.resolve('/workspace/project-real');
+ const linkedRoot = path.resolve('/workspace/project-link');
+ const skillDir = path.join(projectRoot, '.pi', 'skills', 'pi-demo');
+ const realpathSyncSpy = vi.spyOn(fs, 'realpathSync').mockImplementation((value) => {
+ const candidate = String(value);
+ if (candidate === linkedRoot) return projectRoot;
+ return candidate;
+ });
+ const maker = {
+ listCustomizations: vi.fn(async () => ({
+ errors: [],
+ items: [projectRoot, linkedRoot].map((workingDir) => ({
+ engine: 'pi' as const,
+ kind: 'skill' as const,
+ scope: 'repo' as const,
+ name: 'pi-demo',
+ absolutePath: skillDir,
+ mdPath: path.join(skillDir, 'SKILL.md'),
+ workingDir,
+ runtimeStatus: 'discovered' as const,
+ files: [],
+ })),
+ })),
+ } as unknown as Maker;
+
+ const result = await scanAllSkills({
+ projects: [
+ { projectRoot, hash: 'real1234' },
+ { projectRoot: linkedRoot, hash: 'link5678' },
+ ],
+ }, maker);
+
+ expect(result.skills.map((skill) => skill.projectHash).sort()).toEqual(['link5678', 'real1234']);
+ expect(result.skills.map((skill) => skill.projectRoot).sort()).toEqual([
+ linkedRoot,
+ projectRoot,
+ ].sort());
+ realpathSyncSpy.mockRestore();
+ });
+
it('ignores non-absolute projectRoot values before calling maker', async () => {
const maker = {
listCustomizations: vi.fn(async () => ({ errors: [], items: [] })),
@@ -178,6 +344,61 @@ describe('scanAllSkills', () => {
realpathSyncSpy.mockRestore();
});
+ it('preserves Pi discovery status on per-engine badges', async () => {
+ const projectRoot = path.resolve('/repo');
+ const skillDir = path.join(projectRoot, '.pi', 'skills', 'pi-demo');
+ const maker = {
+ listCustomizations: vi.fn(async () => ({
+ errors: [],
+ items: [{
+ engine: 'pi',
+ kind: 'skill',
+ scope: 'repo',
+ name: 'pi-demo',
+ absolutePath: skillDir,
+ mdPath: path.join(skillDir, 'SKILL.md'),
+ workingDir: projectRoot,
+ runtimeStatus: 'discovered',
+ files: [],
+ }],
+ })),
+ } as unknown as Maker;
+
+ const result = await scanAllSkills({
+ projects: [{ projectRoot, hash: 'pi123456' }],
+ }, maker);
+
+ expect(result.skills[0]).toMatchObject({
+ engine: 'pi',
+ scope: 'project',
+ projectRoot,
+ linkedEngines: [{ engine: 'pi', label: 'Pi', runtimeStatus: 'discovered' }],
+ });
+ });
+
+ it('allows SkillHub detail reads from project .pi/skills', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-pi-skill-'));
+ tempRoots.push(root);
+ const skillDir = path.join(root, '.pi', 'skills', 'pi-demo');
+ const skillMd = path.join(skillDir, 'SKILL.md');
+ fs.mkdirSync(skillDir, { recursive: true });
+ fs.writeFileSync(skillMd, '---\nname: pi-demo\n---\n\n# Pi Demo\n', 'utf-8');
+
+ await expect(readSkillContent({ mdPath: skillMd })).resolves.toMatchObject({
+ success: true,
+ content: '\n# Pi Demo\n',
+ });
+ await expect(listSkillFolderChildren({ dirPath: skillDir })).resolves.toMatchObject({
+ success: true,
+ entries: [{ name: 'SKILL.md', kind: 'file' }],
+ });
+ await expect(readSkillRawFile({ filePath: skillMd })).resolves.toMatchObject({ success: true });
+ await expect(writeSkillFile({ filePath: skillMd, content: '# Updated Pi Demo\n' })).resolves.toEqual({
+ success: true,
+ });
+ expect(fs.readFileSync(skillMd, 'utf-8')).toBe('# Updated Pi Demo\n');
+ });
+
it('filters sensitive entries from the initial skill files snapshot', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-scan-files-'));
tempRoots.push(root);
@@ -220,9 +441,145 @@ describe('scanAllSkills', () => {
});
describe('skill file access', () => {
+ it.skipIf(process.platform === 'win32')('rejects writing through a final file symlink', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-write-file-link-'));
+ tempRoots.push(root);
+ const skillDir = path.join(root, '.agents', 'skills', 'linked-file');
+ const outsideMd = path.join(root, 'outside.md');
+ const exposedMd = path.join(skillDir, 'SKILL.md');
+ fs.mkdirSync(skillDir, { recursive: true });
+ fs.writeFileSync(outsideMd, '# Outside\n', 'utf-8');
+ fs.symlinkSync(outsideMd, exposedMd, 'file');
+
+ await expect(writeSkillFile({
+ filePath: exposedMd,
+ content: '# Changed\n',
+ })).resolves.toEqual({
+ success: false,
+ error: 'refusing to write through a symbolic link',
+ });
+ expect(fs.readFileSync(outsideMd, 'utf-8')).toBe('# Outside\n');
+ expect(fs.lstatSync(exposedMd).isSymbolicLink()).toBe(true);
+ });
+
+ it('rejects renaming a skill directory symlink without mutating its target', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-pi-rename-link-'));
+ tempRoots.push(root);
+ const projectRoot = path.join(root, 'project');
+ const skillRoot = path.join(projectRoot, '.pi', 'skills');
+ const targetSkill = path.join(skillRoot, 'target');
+ const aliasSkill = path.join(skillRoot, 'alias');
+ fs.mkdirSync(targetSkill, { recursive: true });
+ fs.writeFileSync(path.join(targetSkill, 'SKILL.md'), '---\nname: target\n---\n# Target\n', 'utf-8');
+ fs.symlinkSync(targetSkill, aliasSkill, process.platform === 'win32' ? 'junction' : 'dir');
+
+ const maker = {
+ listCustomizations: vi.fn(async () => ({
+ errors: [],
+ items: [{
+ engine: 'pi',
+ kind: 'skill',
+ scope: 'repo',
+ name: 'target',
+ absolutePath: aliasSkill,
+ mdPath: path.join(aliasSkill, 'SKILL.md'),
+ workingDir: projectRoot,
+ runtimeStatus: 'discovered',
+ files: [],
+ }],
+ })),
+ } as unknown as Maker;
+ const scanned = await scanAllSkills({
+ projects: [{ projectRoot, hash: 'pi-alias' }],
+ }, maker);
+ expect(scanned.skills[0]).toMatchObject({
+ absolutePath: fs.realpathSync(targetSkill),
+ discoveredPath: aliasSkill,
+ });
+
+ await expect(renameLocalSkill({
+ absolutePath: scanned.skills[0].discoveredPath,
+ newName: 'renamed-alias',
+ })).resolves.toMatchObject({ success: false });
+ expect(fs.existsSync(aliasSkill)).toBe(true);
+ expect(fs.existsSync(path.join(skillRoot, 'renamed-alias'))).toBe(false);
+ expect(fs.readFileSync(path.join(targetSkill, 'SKILL.md'), 'utf-8')).toBe(
+ '---\nname: target\n---\n# Target\n',
+ );
+ });
+
+ it.skipIf(process.platform === 'win32')('rejects renaming a skill whose SKILL.md is a symlink', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-pi-rename-md-link-'));
+ tempRoots.push(root);
+ const skillRoot = path.join(root, 'project', '.pi', 'skills');
+ const skillDir = path.join(skillRoot, 'linked-md');
+ const outsideMd = path.join(root, 'outside.md');
+ fs.mkdirSync(skillDir, { recursive: true });
+ fs.writeFileSync(outsideMd, '---\nname: outside\n---\n# Outside\n', 'utf-8');
+ fs.symlinkSync(outsideMd, path.join(skillDir, 'SKILL.md'), 'file');
+
+ await expect(renameLocalSkill({
+ absolutePath: skillDir,
+ newName: 'renamed-linked-md',
+ })).resolves.toMatchObject({ success: false });
+ expect(fs.existsSync(skillDir)).toBe(true);
+ expect(fs.existsSync(path.join(skillRoot, 'renamed-linked-md'))).toBe(false);
+ expect(fs.readFileSync(outsideMd, 'utf-8')).toBe('---\nname: outside\n---\n# Outside\n');
+ });
+
+ it('rejects project .pi skill symlinks that escape the physical skill root', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-pi-escape-'));
+ tempRoots.push(root);
+ const projectRoot = path.join(root, 'project');
+ const outsideSkill = path.join(root, 'outside-skill');
+ const exposedSkill = path.join(projectRoot, '.pi', 'skills', 'escape');
+ fs.mkdirSync(outsideSkill, { recursive: true });
+ fs.mkdirSync(path.dirname(exposedSkill), { recursive: true });
+ fs.writeFileSync(path.join(outsideSkill, 'SKILL.md'), '# Outside\n', 'utf-8');
+ fs.writeFileSync(path.join(outsideSkill, 'notes.txt'), 'private\n', 'utf-8');
+ fs.symlinkSync(outsideSkill, exposedSkill, process.platform === 'win32' ? 'junction' : 'dir');
+
+ const exposedSkillMd = path.join(exposedSkill, 'SKILL.md');
+ const exposedNotes = path.join(exposedSkill, 'notes.txt');
+ await expect(readSkillContent({ mdPath: exposedSkillMd })).resolves.toMatchObject({ success: false });
+ await expect(listSkillFolderChildren({ dirPath: exposedSkill })).resolves.toMatchObject({ success: false });
+ await expect(readSkillSiblingFile({ filePath: exposedNotes })).resolves.toMatchObject({ success: false });
+ await expect(readSkillRawFile({ filePath: exposedSkillMd })).resolves.toMatchObject({ success: false });
+ await expect(writeSkillFile({ filePath: exposedSkillMd, content: '# Changed\n' })).resolves.toMatchObject({ success: false });
+ expect(fs.readFileSync(path.join(outsideSkill, 'SKILL.md'), 'utf-8')).toBe('# Outside\n');
+ });
+
+ it('anchors project .pi skill boundaries before nested marker segments', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-pi-nested-marker-'));
+ tempRoots.push(root);
+ const projectRoot = path.join(root, 'project');
+ const outsideRoot = path.join(root, 'outside');
+ const nestedSkill = path.join(outsideRoot, '.pi', 'skills', 'escape');
+ const exposedRoot = path.join(projectRoot, '.pi', 'skills', 'alias');
+ fs.mkdirSync(nestedSkill, { recursive: true });
+ fs.mkdirSync(path.dirname(exposedRoot), { recursive: true });
+ fs.writeFileSync(path.join(nestedSkill, 'SKILL.md'), '# Outside\n', 'utf-8');
+ fs.symlinkSync(outsideRoot, exposedRoot, process.platform === 'win32' ? 'junction' : 'dir');
+
+ const exposedSkill = path.join(exposedRoot, '.pi', 'skills', 'escape');
+ const exposedSkillMd = path.join(exposedSkill, 'SKILL.md');
+ await expect(readSkillContent({ mdPath: exposedSkillMd })).resolves.toMatchObject({ success: false });
+ await expect(listSkillFolderChildren({ dirPath: exposedSkill })).resolves.toMatchObject({ success: false });
+ await expect(writeSkillFile({
+ filePath: exposedSkillMd,
+ content: '# Changed\n',
+ })).resolves.toMatchObject({ success: false });
+ expect(fs.readFileSync(path.join(nestedSkill, 'SKILL.md'), 'utf-8')).toBe('# Outside\n');
+ });
+
it('follows a supported skill path symlink across detail, files panel, and editor access', async () => {
const { actualSkillMd, exposedDir, exposedPricingJson, exposedSkillMd } = createSymlinkedSkill();
+ const grantedRoot = resolveExistingSkillPathForGrant(exposedDir);
+ expect(grantedRoot).toBe(fs.realpathSync.native(exposedDir));
+ expect(isExistingSkillPathGranted(exposedSkillMd, new Set([grantedRoot!]))).toBe(true);
+ expect(isExistingSkillPathGranted(actualSkillMd, new Set([grantedRoot!]))).toBe(false);
+
await expect(readSkillContent({ mdPath: exposedSkillMd })).resolves.toMatchObject({
success: true,
content: '\n# Lark Drive\n\nOriginal content\n',
diff --git a/apps/desktop/src/main/skillhub/allowedProjectRoots.ts b/apps/desktop/src/main/skillhub/allowedProjectRoots.ts
new file mode 100644
index 0000000000..3eef421916
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/allowedProjectRoots.ts
@@ -0,0 +1,37 @@
+import { and, eq, inArray, isNotNull, isNull } from 'drizzle-orm';
+
+import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../shared/sessionSource.js';
+import { normalizeWorkingDirForGrouping } from '../../shared/workingDir.js';
+import { getDbClient } from '../localDb/client/current';
+import { sessions } from '../localDb/schema';
+
+export function deriveAllowedSkillhubProjectRoots(
+ workingDirs: readonly (string | null)[],
+): string[] {
+ return [...new Set(
+ workingDirs
+ .map((workingDir) => normalizeWorkingDirForGrouping(workingDir))
+ .filter((workingDir): workingDir is string => workingDir !== null),
+ )];
+}
+
+/**
+ * Project roots that Main currently owns through active local project sessions.
+ * Renderer-provided SkillHub scan requests must be a subset of this catalogue.
+ */
+export async function listAllowedSkillhubProjectRoots(): Promise<string[]> {
+ const rows = await getDbClient().drizzle
+ .select({ workingDir: sessions.workingDir })
+ .from(sessions)
+ .where(
+ and(
+ inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES),
+ eq(sessions.status, 'active'),
+ eq(sessions.workspaceKind, 'project'),
+ isNotNull(sessions.workingDir),
+ isNull(sessions.remoteHostId),
+ ),
+ );
+
+ return deriveAllowedSkillhubProjectRoots(rows.map((row) => row.workingDir));
+}
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index 539add2007..15e79d87c1 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -1,4 +1,5 @@
import { randomUUID } from 'node:crypto';
+import path from 'node:path';
import type { Maker } from '@cindy/maker-core';
import { BrowserWindow, dialog, ipcMain } from 'electron';
import { getCurrentDataOwnerId } from '../authManager';
@@ -6,6 +7,7 @@ import { isAppSessionBoundaryPending } from '../appSessionState';
import { ensureReady as ensureLocalDbReady, getRawDb } from '../localDb';
import { createLogger } from '../logger';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
import { computeFolderHashDetailed } from './folderHash';
import { type MdKind, parseAndValidateFrontmatter } from './frontmatterValidation';
import * as importLocalSkill from './importLocalSkill';
@@ -15,7 +17,17 @@ import type { PublishParams } from './publishService';
import { SkillPublishService } from './publishService';
import { reconcileMineRegistry } from './reconcileMineRegistry';
import { registryService } from './registry';
-import { listSkillFolderChildren, readSkillContent, readSkillRawFile, readSkillSiblingFile, renameLocalSkill, scanAllSkills, writeSkillFile } from './scanner';
+import {
+ isExistingSkillPathGranted,
+ listSkillFolderChildren,
+ readSkillContent,
+ readSkillRawFile,
+ readSkillSiblingFile,
+ renameLocalSkill,
+ resolveExistingSkillPathForGrant,
+ scanAllSkills,
+ writeSkillFile,
+} from './scanner';
import { computeSnapshotDiff, snapshotExists } from './snapshot';
import {
getLocalSkillUsageDiagnosisContext,
@@ -33,12 +45,56 @@ interface LocalImportGrant {
expiresAt: number;
}
+interface ScannedSkillGrant {
+ ownerId: string;
+ entries: Array<{
+ root: string;
+ projectRootKey?: string;
+ }>;
+}
+
export interface RegisterSkillhubIpcOptions {
getMaker: () => Maker;
+ getAllowedProjectRoots: () => Promise<readonly string[]>;
marketService?: SkillhubMarketService;
publishService?: SkillPublishService;
}
+function projectRootKey(value: unknown): string | null {
+ if (typeof value !== 'string' || value.includes('\0') || value.includes('\uFFFD')) return null;
+ const normalized = normalizeWorkingDirForStorage(value);
+ if (!normalized || !path.isAbsolute(normalized)) return null;
+ try {
+ const resolved = path.resolve(normalized);
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+ } catch {
+ return null;
+ }
+}
+
+async function validateRequestedProjects(
+ requestedProjects: import('./scanner').ProjectInput[] | undefined,
+ getAllowedProjectRoots: RegisterSkillhubIpcOptions['getAllowedProjectRoots'],
+): Promise<import('./scanner').ProjectInput[]> {
+ const projects = requestedProjects ?? [];
+ if (projects.length === 0) return [];
+
+ const allowedKeys = new Set(
+ (await getAllowedProjectRoots())
+ .map(projectRootKey)
+ .filter((key): key is string => key !== null),
+ );
+ const validated: import('./scanner').ProjectInput[] = [];
+ for (const project of projects) {
+ const key = projectRootKey(project.projectRoot);
+ if (!key || !allowedKeys.has(key)) {
+ throw new Error('projectRoot is not owned by an active local project session');
+ }
+ validated.push(project);
+ }
+ return validated;
+}
+
/**
* Registers all SkillHub IPC channels.
*
@@ -48,6 +104,89 @@ export interface RegisterSkillhubIpcOptions {
export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const marketService = options.marketService ?? new SkillhubMarketService();
const localImportGrants = new Map<string, LocalImportGrant>();
+ const scannedSkillRootsBySender = new Map<number, ScannedSkillGrant>();
+ const scanGenerationBySender = new Map<number, number>();
+ const scanGrantCleanupRegistered = new WeakSet<object>();
+
+ const ensureScanGrantCleanup = (event: Electron.IpcMainInvokeEvent) => {
+ if (scanGrantCleanupRegistered.has(event.sender)) return;
+ scanGrantCleanupRegistered.add(event.sender);
+ event.sender.once('destroyed', () => {
+ scannedSkillRootsBySender.delete(event.sender.id);
+ scanGenerationBySender.delete(event.sender.id);
+ });
+ };
+
+ const rememberScannedSkillRoots = (
+ event: Electron.IpcMainInvokeEvent,
+ ownerId: string,
+ skills: import('./scanner').Skill[],
+ ) => {
+ const entries: ScannedSkillGrant['entries'] = [];
+ const seenEntries = new Set<string>();
+ for (const skill of skills) {
+ const skillProjectRootKey = skill.scope === 'project'
+ ? projectRootKey(skill.projectRoot)
+ : undefined;
+ if (skill.scope === 'project' && !skillProjectRootKey) continue;
+ // discoveredPath preserves an allowed lexical alias when absolutePath was
+ // canonicalized through a parent-directory symlink.
+ for (const candidate of [skill.discoveredPath, skill.absolutePath]) {
+ const root = resolveExistingSkillPathForGrant(candidate);
+ if (root) {
+ const entryKey = `${root}\0${skillProjectRootKey ?? ''}`;
+ if (!seenEntries.has(entryKey)) {
+ seenEntries.add(entryKey);
+ entries.push({
+ root,
+ ...(skillProjectRootKey ? { projectRootKey: skillProjectRootKey } : {}),
+ });
+ }
+ break;
+ }
+ }
+ }
+ scannedSkillRootsBySender.set(event.sender.id, { ownerId, entries });
+ };
+
+ const hasScannedSkillGrant = (
+ event: Electron.IpcMainInvokeEvent,
+ targetPath: string,
+ ): Promise<boolean> => {
+ assertTrustedAppRendererEvent(event);
+ const grant = scannedSkillRootsBySender.get(event.sender.id);
+ const ownerId = getCurrentDataOwnerId();
+ if (
+ !grant
+ || !ownerId
+ || isAppSessionBoundaryPending()
+ || grant.ownerId !== ownerId
+ ) {
+ if (grant) scannedSkillRootsBySender.delete(event.sender.id);
+ return Promise.resolve(false);
+ }
+ const matchingEntries = grant.entries.filter(({ root }) => (
+ isExistingSkillPathGranted(targetPath, new Set([root]))
+ ));
+ if (matchingEntries.length === 0) return Promise.resolve(false);
+ if (matchingEntries.some(({ projectRootKey: key }) => !key)) return Promise.resolve(true);
+
+ return options.getAllowedProjectRoots()
+ .then((roots) => {
+ const allowedKeys = new Set(
+ roots.map(projectRootKey).filter((key): key is string => key !== null),
+ );
+ return matchingEntries.some(({ projectRootKey: key }) => (
+ key !== undefined && allowedKeys.has(key)
+ ));
+ })
+ .catch(() => false);
+ };
+
+ const scanGrantDenied = () => ({
+ success: false as const,
+ error: 'path was not granted by this renderer\'s latest SkillHub scan',
+ });
const sweepLocalImportGrants = () => {
const now = Date.now();
@@ -121,11 +260,34 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
ipcMain.handle(
'skillhub:scan',
async (
- _event,
+ event,
params: { projects?: import('./scanner').ProjectInput[] },
) => {
+ assertTrustedAppRendererEvent(event);
+ ensureScanGrantCleanup(event);
+ const scanGeneration = (scanGenerationBySender.get(event.sender.id) ?? 0) + 1;
+ scanGenerationBySender.set(event.sender.id, scanGeneration);
+ // A new scan attempt supersedes the previous snapshot immediately. If
+ // discovery fails, stale paths must not remain authorized.
+ scannedSkillRootsBySender.delete(event.sender.id);
try {
- return { success: true, ...(await scanAllSkills(params ?? {}, options.getMaker())) };
+ const scanOwnerId = getCurrentDataOwnerId();
+ if (!scanOwnerId || isAppSessionBoundaryPending()) {
+ throw new Error('active data owner is unavailable');
+ }
+ const projects = await validateRequestedProjects(
+ params?.projects,
+ options.getAllowedProjectRoots,
+ );
+ const result = await scanAllSkills({ projects }, options.getMaker());
+ if (
+ scanGenerationBySender.get(event.sender.id) === scanGeneration
+ && !isAppSessionBoundaryPending()
+ && getCurrentDataOwnerId() === scanOwnerId
+ ) {
+ rememberScannedSkillRoots(event, scanOwnerId, result.skills);
+ }
+ return { success: true, ...result };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
log.error('[skillhub:scan] failed:', err);
@@ -139,7 +301,8 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// from devolving into a generic file-read API.
ipcMain.handle(
'skillhub:read-skill',
- async (_event, params: { mdPath: string }) => {
+ async (event, params: { mdPath: string }) => {
+ if (!await hasScannedSkillGrant(event, params.mdPath)) return scanGrantDenied();
return readSkillContent(params);
},
);
@@ -149,7 +312,8 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// calls back into here for its contents.
ipcMain.handle(
'skillhub:list-children',
- async (_event, params: { dirPath: string }) => {
+ async (event, params: { dirPath: string }) => {
+ if (!await hasScannedSkillGrant(event, params.dirPath)) return scanGrantDenied();
return listSkillFolderChildren(params);
},
);
@@ -158,7 +322,8 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// when the user clicks a non-SKILL.md file in the FILES list.
ipcMain.handle(
'skillhub:read-sibling-file',
- async (_event, params: { filePath: string }) => {
+ async (event, params: { filePath: string }) => {
+ if (!await hasScannedSkillGrant(event, params.filePath)) return scanGrantDenied();
return readSkillSiblingFile(params);
},
);
@@ -170,7 +335,8 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// .md across kind boundaries.
ipcMain.handle(
'skillhub:read-raw',
- async (_event, params: { filePath: string }) => {
+ async (event, params: { filePath: string }) => {
+ if (!await hasScannedSkillGrant(event, params.filePath)) return scanGrantDenied();
return readSkillRawFile(params);
},
);
@@ -178,7 +344,8 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// realpath check defends against symlink-out-of-tree. See scanner module.
ipcMain.handle(
'skillhub:write-file',
- async (_event, params: { filePath: string; content: string }) => {
+ async (event, params: { filePath: string; content: string }) => {
+ if (!await hasScannedSkillGrant(event, params.filePath)) return scanGrantDenied();
return writeSkillFile(params);
},
);
@@ -200,7 +367,8 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// 拿去走 publish 即可。失败时盘上已回滚到原状态。
ipcMain.handle(
'skillhub:rename-local',
- async (_event, params: { absolutePath: string; newName: string }) => {
+ async (event, params: { absolutePath: string; newName: string }) => {
+ if (!await hasScannedSkillGrant(event, params.absolutePath)) return scanGrantDenied();
return renameLocalSkill(params);
},
);
diff --git a/apps/desktop/src/main/skillhub/scanner.ts b/apps/desktop/src/main/skillhub/scanner.ts
index e1b7a8b2b4..799dd8a437 100644
--- a/apps/desktop/src/main/skillhub/scanner.ts
+++ b/apps/desktop/src/main/skillhub/scanner.ts
@@ -14,11 +14,12 @@
* Read-only for scan; write helpers gated by SKILL_PATH_WHITELIST.
*/
+import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import matter from 'gray-matter';
-import type { AgentCustomization, Maker } from '@cindy/maker-core';
+import type { AgentCustomization, Maker, PiRuntimeCapabilityStatus } from '@cindy/maker-core';
import { registryService, type StoredInstall } from './registry';
import { isIgnoredSkillPackagePath } from './packageIgnore';
@@ -38,7 +39,8 @@ export interface SkillFileEntry {
export interface Skill {
/**
- * Stable id — React key,含 engine 前缀防跨引擎同名冲突。
+ * Stable id — React key,含 engine 前缀防跨引擎同名冲突。同一 engine 下
+ * 若 URL 基键重复,会再追加 canonical source path 的不可逆 hash。
* global → `${engine}:${kind}:global:${name}`
* project → `${engine}:${kind}:project:${projectHash}:${name}`
*/
@@ -49,10 +51,18 @@ export interface Skill {
* project → `${kind}:project:${projectHash}:${name}`
*/
urlKey: string;
+ /** Pi customization 的 canonical physical source hash;Pi 条目始终提供。 */
+ sourceKey?: string;
+ /** 同一 URL 基键存在多个来源时,详情路由必须携带 sourceKey。 */
+ requiresSourceKey?: boolean;
/** 来自哪个 agent 引擎。 */
- engine: 'claude-code' | 'codex';
+ engine: 'claude-code' | 'codex' | 'pi';
/** 发现该 skill 的所有引擎专属路径(去重后)。~/.agents/ 通用路径不算引擎。 */
- linkedEngines: Array<{ engine: 'claude-code' | 'codex'; label: string }>;
+ linkedEngines: Array<{
+ engine: 'claude-code' | 'codex' | 'pi';
+ label: string;
+ runtimeStatus?: PiRuntimeCapabilityStatus;
+ }>;
kind: SkillKind;
scope: SkillScope;
/** Folder name for kind=skill; basename without `.md` for kind=command/agent. */
@@ -69,6 +79,8 @@ export interface Skill {
* the file's parent dir, computed renderer-side via path utilities).
*/
absolutePath: string;
+ /** Lexical path reported by discovery before canonical realpath deduplication. */
+ discoveredPath: string;
/** Full path to the .md file we render (SKILL.md for skill, the file itself for command/agent). */
mdPath: string;
/** Sibling files / subfolders inside the skill folder. Always empty for command/agent. */
@@ -131,17 +143,25 @@ export interface ProjectInput {
* 状态; ok 状态简化为按 (kind/scope) 聚合 count。失败不抛, 单个 errors 收进 sources。
*/
/**
- * Codex scope → SkillScope 映射。
- * Codex: 'user'|'system'|'admin' → 'global', 'repo' → 'project'。
+ * Codex/Pi scope → SkillScope 映射。
+ * Codex/Pi: 'user'|'system'|'admin' → 'global', 'repo' → 'project'。
* Claude: 已经是 'global'|'project',直通。
*/
function normalizeScope(engine: string, rawScope: string): SkillScope {
- if (engine === 'codex') {
+ if (engine === 'codex' || engine === 'pi') {
return rawScope === 'repo' ? 'project' : 'global';
}
return rawScope as SkillScope;
}
+function realPathOrNormalized(value: string): string {
+ try {
+ return fs.realpathSync(value);
+ } catch {
+ return path.normalize(value);
+ }
+}
+
function normalizeSkillEntityPath(c: AgentCustomization): AgentCustomization {
if (
c.kind === 'skill' &&
@@ -168,14 +188,26 @@ export async function scanAllSkills(
maker: Maker,
): Promise<ScanResult> {
const projects = params.projects ?? [];
- // ProjectInput 带 hash,maker 只要 project root;建反查表用于补回 projectHash 字段。
- const hashByProjectRoot = new Map<string, string>();
+ const projectByWorkingDir = new Map<string, ProjectInput>();
+ const projectsByCanonicalWorkingDir = new Map<string, ProjectInput[]>();
+ const workingDirs: string[] = [];
for (const p of projects) {
if (p.projectRoot && path.isAbsolute(p.projectRoot)) {
- hashByProjectRoot.set(p.projectRoot, p.hash);
+ workingDirs.push(p.projectRoot);
+ projectByWorkingDir.set(path.normalize(p.projectRoot), p);
+ const canonicalRoot = realPathOrNormalized(p.projectRoot);
+ const aliases = projectsByCanonicalWorkingDir.get(canonicalRoot) ?? [];
+ aliases.push(p);
+ projectsByCanonicalWorkingDir.set(canonicalRoot, aliases);
}
}
- const workingDirs = Array.from(hashByProjectRoot.keys());
+ const projectForWorkingDir = (workingDir?: string): ProjectInput | undefined => {
+ if (!workingDir) return undefined;
+ const lexicalMatch = projectByWorkingDir.get(path.normalize(workingDir));
+ if (lexicalMatch) return lexicalMatch;
+ const canonicalMatches = projectsByCanonicalWorkingDir.get(realPathOrNormalized(workingDir));
+ return canonicalMatches?.length === 1 ? canonicalMatches[0] : undefined;
+ };
let listed: { items: AgentCustomization[]; errors: Array<{ path?: string; message: string }> };
try {
@@ -194,18 +226,16 @@ export async function scanAllSkills(
const HIDDEN_SCOPES = new Set(['system', 'admin']);
const isBackupPath = (p: string) => /\.bak\.\d+$/.test(path.basename(p));
const isGenericPath = (p: string) => /\/\.agents\/skills\//.test(p.replace(/\\/g, '/'));
- const seenItems = new Map<string, { winner: AgentCustomization; all: AgentCustomization[] }>();
+ const seenItems = new Map<string, { winner: AgentCustomization; all: AgentCustomization[]; realPath: string }>();
for (const item of listed.items) {
const c = normalizeSkillEntityPath(item);
if (HIDDEN_SCOPES.has(c.scope)) continue;
if (isBackupPath(c.absolutePath)) continue;
- let realKey: string;
- try {
- realKey = fs.realpathSync(c.absolutePath);
- } catch {
- realKey = c.absolutePath;
- }
- const existing = seenItems.get(realKey);
+ const realKey = realPathOrNormalized(c.absolutePath);
+ const normalizedScope = normalizeScope(c.engine, c.scope);
+ const project = normalizedScope === 'project' ? projectForWorkingDir(c.workingDir) : undefined;
+ const dedupeKey = project ? `${realKey}\0project:${project.hash}` : realKey;
+ const existing = seenItems.get(dedupeKey);
if (existing) {
existing.all.push(c);
if (!isGenericPath(existing.winner.absolutePath) && isGenericPath(c.absolutePath)) {
@@ -213,14 +243,15 @@ export async function scanAllSkills(
}
continue;
}
- seenItems.set(realKey, { winner: c, all: [c] });
+ seenItems.set(dedupeKey, { winner: c, all: [c], realPath: realKey });
}
- const deduped = Array.from(seenItems.entries()).map(([realPath, v]) => ({ ...v, realPath }));
+ const deduped = Array.from(seenItems.values());
// ── AgentCustomization → SkillhubSkill ──────────────────────────────────────
- const skills: Skill[] = deduped.map(({ winner: c, all, realPath }) => {
+ const candidates = deduped.map(({ winner: c, all, realPath }) => {
const engine = c.engine as Skill['engine'];
- const projectHash = c.workingDir ? hashByProjectRoot.get(c.workingDir) : undefined;
+ const project = projectForWorkingDir(c.workingDir);
+ const projectHash = project?.hash;
// skill 类型的 identity 始终是目录名(= market slug),不依赖 frontmatter name。
// Codex RPC 可能从 frontmatter 取 name 导致与目录名不一致,统一用 basename(realPath)。
const canonicalName = c.kind === 'skill' ? path.basename(realPath) : c.name;
@@ -232,23 +263,52 @@ export async function scanAllSkills(
const urlKey = scope === 'global'
? `${c.kind}:global:${canonicalName}`
: `${c.kind}:project:${projectHash}:${canonicalName}`;
- const id = `${engine}:${urlKey}`;
-
- const engineSet = new Map<string, string>();
+ return { c, all, realPath, engine, project, projectHash, canonicalName, scope, urlKey };
+ });
+ const identityCounts = new Map<string, number>();
+ for (const candidate of candidates) {
+ const identity = `${candidate.engine}:${candidate.urlKey}`;
+ identityCounts.set(identity, (identityCounts.get(identity) ?? 0) + 1);
+ }
+
+ const skills: Skill[] = candidates.map(({
+ c,
+ all,
+ realPath,
+ engine,
+ project,
+ projectHash,
+ canonicalName,
+ scope,
+ urlKey,
+ }) => {
+ const hasIdentityCollision = (identityCounts.get(`${engine}:${urlKey}`) ?? 0) > 1;
+ // Pi entries are new to this SkillHub projection. Give them a path-derived
+ // identity even when currently unique, so adding/removing a same-name source
+ // never changes the surviving Pi entry's React/storage identity.
+ const sourceKey = engine === 'pi' || hasIdentityCollision
+ ? createHash('sha256').update(realPath).digest('hex')
+ : undefined;
+ const id = `${engine}:${urlKey}${sourceKey ? `:source:${sourceKey}` : ''}`;
+
+ const engineSet = new Map<Skill['engine'], Skill['linkedEngines'][number]>();
for (const item of all) {
- const eng = item.engine as Skill['engine'];
+ const eng = item.engine;
if (!engineSet.has(eng)) {
- engineSet.set(eng, eng === 'claude-code' ? 'Claude' : eng === 'codex' ? 'Codex' : eng);
+ engineSet.set(eng, {
+ engine: eng,
+ label: eng === 'claude-code' ? 'Claude' : eng === 'codex' ? 'Codex' : 'Pi',
+ ...(item.runtimeStatus ? { runtimeStatus: item.runtimeStatus } : {}),
+ });
}
}
- const linkedEngines: Skill['linkedEngines'] = Array.from(engineSet, ([e, label]) => ({
- engine: e as Skill['engine'],
- label,
- }));
+ const linkedEngines = Array.from(engineSet.values());
const skill: Skill = {
id,
urlKey,
+ ...(sourceKey ? { sourceKey } : {}),
+ ...(hasIdentityCollision ? { requiresSourceKey: true } : {}),
engine,
linkedEngines,
kind: c.kind as SkillKind,
@@ -256,6 +316,7 @@ export async function scanAllSkills(
name: canonicalName,
description: c.description,
absolutePath: realPath,
+ discoveredPath: c.absolutePath,
mdPath: c.mdPath ?? realPath,
files: c.kind === 'skill'
? filterSkillPackageFileEntries(realPath, (c.files ?? []) as SkillFileEntry[])
@@ -263,7 +324,7 @@ export async function scanAllSkills(
frontmatter: c.frontmatter,
parseError: c.parseError,
registryEntry: null, // 下面 join 阶段填
- ...(c.workingDir ? { projectRoot: c.workingDir } : {}),
+ ...(project ? { projectRoot: project.projectRoot } : {}),
...(projectHash ? { projectHash } : {}),
};
return skill;
@@ -396,7 +457,8 @@ export async function readSkillContent(params: { mdPath: string }): Promise<{
return { success: false, error: 'only .md files may be read via this channel' };
}
- if (!isAllowedSkillPath(mdPath)) {
+ const resolvedMdPath = resolveAllowedExistingSkillPath(mdPath);
+ if (!resolvedMdPath) {
return { success: false, error: 'path is not under a recognized skills directory' };
}
if (isIgnoredSkillFilePath(mdPath)) {
@@ -404,7 +466,7 @@ export async function readSkillContent(params: { mdPath: string }): Promise<{
}
try {
- const raw = fs.readFileSync(mdPath, 'utf-8');
+ const raw = fs.readFileSync(resolvedMdPath, 'utf-8');
const parsed = matter(raw);
return { success: true, content: parsed.content };
} catch (err) {
@@ -436,7 +498,8 @@ export async function readSkillSiblingFile(params: { filePath: string }): Promis
return { success: false, error: 'filePath must be an absolute path' };
}
- if (!isAllowedSkillPath(filePath)) {
+ const resolvedFilePath = resolveAllowedExistingSkillPath(filePath);
+ if (!resolvedFilePath) {
return { success: false, error: 'path is not under a recognized skills directory' };
}
@@ -445,14 +508,14 @@ export async function readSkillSiblingFile(params: { filePath: string }): Promis
return { success: false, error: 'path is excluded from SkillHub packages' };
}
- const stat = fs.statSync(filePath);
+ const stat = fs.statSync(resolvedFilePath);
if (!stat.isFile()) {
return { success: false, error: 'path is not a file' };
}
if (stat.size > PREVIEW_SIZE_CAP) {
return { success: false, error: `文件超过 ${Math.round(PREVIEW_SIZE_CAP / 1024)} KB,无法在面板中预览` };
}
- const content = fs.readFileSync(filePath, 'utf-8');
+ const content = fs.readFileSync(resolvedFilePath, 'utf-8');
return { success: true, content };
} catch (err) {
return {
@@ -479,18 +542,19 @@ export async function listSkillFolderChildren(params: { dirPath: string }): Prom
return { success: false, error: 'dirPath must be an absolute path' };
}
- if (!isAllowedSkillPath(dirPath)) {
+ const resolvedDirPath = resolveAllowedExistingSkillPath(dirPath);
+ if (!resolvedDirPath) {
return { success: false, error: 'path is not under a recognized skills directory' };
}
try {
- const stat = fs.statSync(dirPath);
+ const stat = fs.statSync(resolvedDirPath);
if (!stat.isDirectory()) {
return { success: false, error: 'path is not a directory' };
}
const skillRoot = findSkillRootForPath(dirPath);
const entries: SkillFileEntry[] = fs
- .readdirSync(dirPath, { withFileTypes: true })
+ .readdirSync(resolvedDirPath, { withFileTypes: true })
.filter((s) => {
const childPath = path.join(dirPath, s.name);
return !isIgnoredSkillPackagePath(skillPackageRelPath(skillRoot, childPath, s.name));
@@ -522,17 +586,85 @@ const EDIT_SIZE_CAP_WRITE = 1024 * 1024; // 1 MB write cap (defensive against pa
// 统一白名单:所有引擎的 skill/command/agent 目录共用。
// 新增引擎时只需在此 regex 加一个分支。
-const SKILL_PATH_WHITELIST = /\/(\.(claude\/(skills|commands|agents)|agents\/skills|codex\/skills)|codex-home\/skills)\//;
+const SKILL_PATH_WHITELIST = /\/(\.(claude\/(skills|commands|agents)|agents\/skills|codex\/skills|pi\/skills)|codex-home\/skills)\//;
-function isAllowedSkillPath(absolutePath: string): boolean {
+function isLexicallyAllowedSkillPath(absolutePath: string): boolean {
// path.resolve 解析 .. 和 . 段,防止遍历绕过白名单
const norm = path.resolve(absolutePath).replace(/\\/g, '/');
return SKILL_PATH_WHITELIST.test(norm);
}
+function isPathWithin(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return relative === '' || (
+ relative !== '..'
+ && !relative.startsWith(`..${path.sep}`)
+ && !path.isAbsolute(relative)
+ );
+}
+
+/**
+ * Resolve the final existing target before Main performs IO. Project-owned
+ * `.pi/skills` paths get an extra physical boundary: neither the source root
+ * nor a child symlink may escape the project. Other roots keep supporting the
+ * existing global compatibility symlinks used by shared skill installs.
+ */
+function resolveAllowedExistingSkillPath(absolutePath: string): string | null {
+ if (!isLexicallyAllowedSkillPath(absolutePath)) return null;
+ const lexicalPath = path.resolve(absolutePath);
+ let realTarget: string;
+ try {
+ realTarget = fs.realpathSync.native(lexicalPath);
+ } catch {
+ return null;
+ }
+
+ const normalized = lexicalPath.replace(/\\/g, '/');
+ const marker = '/.pi/skills/';
+ const markerIndex = normalized.indexOf(marker);
+ if (markerIndex < 0) return realTarget;
+
+ const lexicalSkillRoot = path.normalize(normalized.slice(0, markerIndex + marker.length - 1));
+ const lexicalProjectRoot = path.dirname(path.dirname(lexicalSkillRoot));
+ try {
+ const realProjectRoot = fs.realpathSync.native(lexicalProjectRoot);
+ const realSkillRoot = fs.realpathSync.native(lexicalSkillRoot);
+ if (
+ !isPathWithin(realProjectRoot, realSkillRoot)
+ || !isPathWithin(realSkillRoot, realTarget)
+ ) return null;
+ } catch {
+ return null;
+ }
+ return realTarget;
+}
+
+/**
+ * Canonicalize a path previously surfaced by SkillHub discovery for an IPC
+ * grant. This deliberately reuses the same lexical whitelist and physical
+ * symlink boundary as the eventual read/write operation.
+ */
+export function resolveExistingSkillPathForGrant(absolutePath: string): string | null {
+ if (!absolutePath || !path.isAbsolute(absolutePath)) return null;
+ return resolveAllowedExistingSkillPath(absolutePath);
+}
+
+/** Return whether an existing target belongs to one of the sender's scanned roots. */
+export function isExistingSkillPathGranted(
+ absolutePath: string,
+ grantedRoots: ReadonlySet<string>,
+): boolean {
+ const realTarget = resolveExistingSkillPathForGrant(absolutePath);
+ if (!realTarget) return false;
+ for (const root of grantedRoots) {
+ if (isPathWithin(root, realTarget)) return true;
+ }
+ return false;
+}
+
function findSkillRootForPath(absolutePath: string): string | null {
const norm = path.resolve(absolutePath).replace(/\\/g, '/');
- const markerMatch = /\/(?:\.claude\/(?:skills|commands|agents)|\.agents\/skills|\.codex\/skills|codex-home\/skills)\//.exec(norm);
+ const markerMatch = /\/(?:\.claude\/(?:skills|commands|agents)|\.agents\/skills|\.codex\/skills|\.pi\/skills|codex-home\/skills)\//.exec(norm);
if (!markerMatch) return null;
const afterMarker = norm.slice((markerMatch.index ?? 0) + markerMatch[0].length);
@@ -566,19 +698,20 @@ export async function readSkillRawFile(params: { filePath: string }): Promise<{
if (path.normalize(filePath).split(path.sep).includes('..')) {
return { success: false, error: 'filePath contains traversal segments' };
}
- if (!isAllowedSkillPath(filePath)) {
+ const resolvedFilePath = resolveAllowedExistingSkillPath(filePath);
+ if (!resolvedFilePath) {
return { success: false, error: 'path is not under a recognized skills directory' };
}
if (isIgnoredSkillFilePath(filePath)) {
return { success: false, error: 'path is excluded from SkillHub packages' };
}
try {
- const stat = fs.statSync(filePath);
+ const stat = fs.statSync(resolvedFilePath);
if (!stat.isFile()) return { success: false, error: 'path is not a file' };
if (stat.size > EDIT_SIZE_CAP_READ) {
return { success: false, error: `文件超过 ${Math.round(EDIT_SIZE_CAP_READ / 1024)} KB,请用外部编辑器` };
}
- const content = fs.readFileSync(filePath, 'utf-8');
+ const content = fs.readFileSync(resolvedFilePath, 'utf-8');
return { success: true, content };
} catch (err) {
return { success: false, error: err instanceof Error ? err.message : String(err) };
@@ -596,7 +729,21 @@ export async function writeSkillFile(params: { filePath: string; content: string
if (path.normalize(filePath).split(path.sep).includes('..')) {
return { success: false, error: 'filePath contains traversal segments' };
}
- if (!isAllowedSkillPath(filePath)) {
+ if (!isLexicallyAllowedSkillPath(filePath)) {
+ return { success: false, error: 'path is not under a recognized skills directory' };
+ }
+ try {
+ // Parent-directory compatibility symlinks remain supported, but the final
+ // editable file must be a regular lexical entry. Otherwise resolving it
+ // first would let an atomic rename overwrite the symlink's external target.
+ if (fs.lstatSync(filePath).isSymbolicLink()) {
+ return { success: false, error: 'refusing to write through a symbolic link' };
+ }
+ } catch {
+ return { success: false, error: '文件不存在,本期不允许创建新文件' };
+ }
+ const resolvedFilePath = resolveAllowedExistingSkillPath(filePath);
+ if (!resolvedFilePath) {
return { success: false, error: 'path is not under a recognized skills directory' };
}
if (isIgnoredSkillFilePath(filePath)) {
@@ -605,7 +752,7 @@ export async function writeSkillFile(params: { filePath: string; content: string
// Existence requirement — v0.2.2 disallows creating new files.
let stat: fs.Stats;
try {
- stat = fs.statSync(filePath);
+ stat = fs.statSync(resolvedFilePath);
} catch {
return { success: false, error: '文件不存在,本期不允许创建新文件' };
}
@@ -618,7 +765,7 @@ export async function writeSkillFile(params: { filePath: string; content: string
}
// Atomic write: tmp + rename. fsync the tmp file before rename so a crash
// mid-write doesn't leave a half-written file at the target path.
- const tmpPath = `${filePath}.xdt-tmp`;
+ const tmpPath = `${resolvedFilePath}.xdt-tmp`;
try {
const fd = fs.openSync(tmpPath, 'w');
try {
@@ -627,7 +774,7 @@ export async function writeSkillFile(params: { filePath: string; content: string
} finally {
fs.closeSync(fd);
}
- fs.renameSync(tmpPath, filePath);
+ fs.renameSync(tmpPath, resolvedFilePath);
return { success: true };
} catch (err) {
// Best-effort tmp cleanup — ignore failures.
@@ -656,7 +803,7 @@ export async function renameLocalSkill(params: {
if (path.normalize(absolutePath).split(path.sep).includes('..')) {
return { success: false, error: 'absolutePath contains traversal segments' };
}
- if (!isAllowedSkillPath(absolutePath)) {
+ if (!resolveAllowedExistingSkillPath(absolutePath)) {
return { success: false, error: 'path is not under a recognized skills directory' };
}
if (!/^[a-z0-9-]+$/.test(newName)) {
@@ -666,10 +813,13 @@ export async function renameLocalSkill(params: {
// 必须是已有的 skill folder
let stat: fs.Stats;
try {
- stat = fs.statSync(absolutePath);
+ stat = fs.lstatSync(absolutePath);
} catch {
return { success: false, error: '目录不存在' };
}
+ if (stat.isSymbolicLink()) {
+ return { success: false, error: '符号链接 skill 不支持重命名' };
+ }
if (!stat.isDirectory()) {
return { success: false, error: 'absolutePath 不是目录' };
}
@@ -690,7 +840,16 @@ export async function renameLocalSkill(params: {
// 必须有 SKILL.md
const oldSkillMd = path.join(absolutePath, 'SKILL.md');
- if (!fs.existsSync(oldSkillMd) || !fs.statSync(oldSkillMd).isFile()) {
+ let skillMdStat: fs.Stats;
+ try {
+ skillMdStat = fs.lstatSync(oldSkillMd);
+ } catch {
+ return { success: false, error: 'SKILL.md 不存在,无法改名' };
+ }
+ if (skillMdStat.isSymbolicLink()) {
+ return { success: false, error: '符号链接 SKILL.md 不支持重命名' };
+ }
+ if (!skillMdStat.isFile()) {
return { success: false, error: 'SKILL.md 不存在,无法改名' };
}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 83853b133a..6aa94c69f0 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5028,7 +5028,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
listAgentSkills: (
agentKind: 'claude-code' | 'codex' | 'pi',
- params: { workingDir?: string; forceReload?: boolean },
+ params: { workingDir?: string; forceReload?: boolean; sessionId?: string },
): Promise<{
success: boolean;
error?: string;
@@ -5040,6 +5040,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
path?: string;
scope?: string;
enabled?: boolean;
+ runtimeStatus?: 'discovered' | 'approved' | 'loaded' | 'failed' | 'unknown';
+ runtimeCommandName?: string;
}>;
}> => ipcRenderer.invoke('maker:list-agent-skills', agentKind, params),
diff --git a/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts
index e9acae68ca..f27fa03a02 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts
@@ -51,6 +51,14 @@ describe('ChatInput steer shortcut contract', () => {
expect(windowKeydownBlock).toContain("(enterIntent === 'queue' || enterIntent === 'steer')");
expect(windowKeydownBlock).toContain("currentState !== 'listening'");
expect(windowKeydownBlock).toContain('void dispatchSendRef.current(enterIntent);');
+ const paletteGuard = windowComposerCaptureBlock.indexOf(
+ 'panelBridgeRef.current?.captureKey(event)',
+ );
+ const modifiedSend = windowComposerCaptureBlock.indexOf(
+ 'void dispatchSendRef.current(enterIntent);',
+ );
+ expect(paletteGuard).toBeGreaterThan(-1);
+ expect(paletteGuard).toBeLessThan(modifiedSend);
expect(chatInputSource).toContain("'Alt-Enter': () => this.editor.commands.setHardBreak()");
expect(chatInputSource).toContain('ComposerHardBreak');
expect(chatInputSource).toContain('turnRunning={showStopButton}');
diff --git a/apps/desktop/src/renderer/__tests__/issueCommandAttachments.test.ts b/apps/desktop/src/renderer/__tests__/issueCommandAttachments.test.ts
index 601a1d3079..2864127ff2 100644
--- a/apps/desktop/src/renderer/__tests__/issueCommandAttachments.test.ts
+++ b/apps/desktop/src/renderer/__tests__/issueCommandAttachments.test.ts
@@ -122,10 +122,12 @@ describe('CCAgentSessionView /issue attachment wiring', () => {
it('passes composer files through both dispatch entry points', () => {
// 已有会话:handleSend 把当前 composer files 交给命令 dispatch。
- expect(sessionViewSource).toContain('maybeDispatchDesktopSlashCommand(message, files)');
+ expect(sessionViewSource).toMatch(
+ /maybeDispatchDesktopSlashCommand\(message, files(?:,|\))/,
+ );
// 新建会话:首条消息补发时把 pending.files 交给命令 dispatch(此前被静默丢弃)。
- expect(sessionViewSource).toContain(
- 'maybeDispatchDesktopSlashCommand(pending.text, pending.files)',
+ expect(sessionViewSource).toMatch(
+ /maybeDispatchDesktopSlashCommand\(\s*pending\.text,\s*pending\.files,/,
);
});
diff --git a/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts b/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts
index ede937d2cf..f582df58c4 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts
@@ -140,6 +140,63 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
expect(sessionViewSource).toContain('disabled={remoteHandoffPreparing}');
});
+ it('rebases delayed-create inline metadata after rewriting a Pi skill alias', () => {
+ const pendingBranch = sessionViewSource.slice(
+ sessionViewSource.indexOf('const pending = consumePending(sessionId);'),
+ sessionViewSource.indexOf('const pendingGoalConsumedRef'),
+ ).replace(/\r\n/g, '\n');
+
+ expect(pendingBranch).toContain(
+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.agentReferences,',
+ );
+ expect(pendingBranch).toContain(
+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.pastedTextRanges,',
+ );
+ expect(pendingBranch).toContain(
+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.slashCommandRanges,',
+ );
+ expect(pendingBranch).toContain('agentReferences: pendingAgentReferences');
+ expect(pendingBranch).toContain('pastedTextRanges: pendingPastedTextRanges');
+ expect(pendingBranch).toContain('slashCommandRanges: pendingSlashCommandRanges');
+ expect(pendingBranch).toContain('PI_RUNTIME_SKILL_RETRY_DELAYS_MS');
+ });
+
+ it('reconciles Pi skill aliases after the user selects a working directory', () => {
+ const workingDirHandler = sessionViewSource.slice(
+ sessionViewSource.indexOf('const handleWorkingDirChange = useCallback('),
+ sessionViewSource.indexOf('const maybeShowContextUsage'),
+ ).replace(/\r\n/g, '\n');
+
+ expect(sessionViewSource).toContain('const commands = options?.workingDirOverride');
+ expect(workingDirHandler).toContain('workingDirOverride: newDir');
+ expect(workingDirHandler).toContain(
+ 'piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS',
+ );
+ expect(workingDirHandler).toContain('preparePiRuntime: async () =>');
+ expect(workingDirHandler).toContain("'maker:create-session'");
+ expect(workingDirHandler).toContain('window.electronAPI.maker.createSession(createOpts)');
+ expect(workingDirHandler).toContain(
+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.agentReferences,',
+ );
+ expect(workingDirHandler).toContain(
+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.pastedTextRanges,',
+ );
+ expect(workingDirHandler).toContain(
+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.slashCommandRanges,',
+ );
+ expect(workingDirHandler).toContain('slashDispatch.message,');
+ });
+
+ it('uses bounded Pi runtime reconciliation for ordinary sends and steering', () => {
+ const slashDispatchBranch = sessionViewSource.slice(
+ sessionViewSource.indexOf('const originalMessage = message;'),
+ sessionViewSource.indexOf('if (slashDispatch.handled) return;'),
+ ).replace(/\r\n/g, '\n');
+
+ expect(slashDispatchBranch.match(/piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS/g))
+ .toHaveLength(2);
+ });
+
it('refreshes the remote mirror even when the remote enableOrca reports failure', () => {
// 控制端的 invoke 超时**不会取消**被控端正在跑的 enableOrca,所以「控制端报失败、
// 对端稍后仍建成 team」是真实终态(codex review P1)。回流放在 finally 里,让
diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
index 861000428a..8a0e5b1558 100644
--- a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
@@ -93,9 +93,9 @@ describe('CCAgentSessionView 接线不变式', () => {
it('补选目录后的续发保持 delivery mode,并按本地/远端策略清理原 composer', () => {
expect(sessionViewSrc).toContain('deliveryMode: MessageDeliveryMode;');
expect(sessionViewSrc).toContain(
- "const dispatch = deliveryMode === 'steer' ? steerMessage : sendMessage;",
+ "const dispatch = pending.deliveryMode === 'steer' ? steerMessage : sendMessage;",
);
- expect(sessionViewSrc).toContain('if (accepted) onDeferredAccepted?.();');
+ expect(sessionViewSrc).toContain('if (accepted) pending.onDeferredAccepted?.();');
expect(sessionViewSrc).toContain(
'...(opts?.onDeferredAccepted ? { onDeferredAccepted: opts.onDeferredAccepted } : {})',
);
diff --git a/apps/desktop/src/renderer/__tests__/slashCommandsDeviceId.test.ts b/apps/desktop/src/renderer/__tests__/slashCommandsDeviceId.test.ts
index 79d32531dc..ecdb1c58fc 100644
--- a/apps/desktop/src/renderer/__tests__/slashCommandsDeviceId.test.ts
+++ b/apps/desktop/src/renderer/__tests__/slashCommandsDeviceId.test.ts
@@ -40,10 +40,13 @@ function stubElectron() {
describe('loadAllCommands deviceId', () => {
it('本地会话(无 deviceId):三源全本地,不碰隧道', async () => {
const s = stubElectron();
- const cmds = await loadAllCommands('claude-code', '/w');
+ const cmds = await loadAllCommands('claude-code', '/w', { sessionId: 'local-session' });
expect(s.invoke).not.toHaveBeenCalled();
expect(s.listAgentCommands).toHaveBeenCalledWith('claude-code');
- expect(s.listAgentSkills).toHaveBeenCalled();
+ expect(s.listAgentSkills).toHaveBeenCalledWith('claude-code', {
+ workingDir: '/w',
+ sessionId: 'local-session',
+ });
// 本地会话:goal 命令保留(可对本地 session 设目标)。
expect(cmds.map((x) => x.name).sort()).toEqual(['compact', 'goal', 'help', 'localskill']);
});
@@ -80,7 +83,12 @@ describe('loadAllCommands deviceId', () => {
it('远程会话:agent-builtin / agent-skill 走隧道,desktop 仍本地', async () => {
const s = stubElectron();
- const cmds = await loadAllCommands('claude-code', '/host/path', undefined, 'dev-1');
+ const cmds = await loadAllCommands(
+ 'claude-code',
+ '/host/path',
+ { sessionId: 'remote-session' },
+ 'dev-1',
+ );
// desktop 始终本地
expect(s.listDesktopCommands).toHaveBeenCalled();
// agent-builtin / agent-skill 不走本地、走隧道
@@ -89,7 +97,7 @@ describe('loadAllCommands deviceId', () => {
expect(s.invoke).toHaveBeenCalledWith('dev-1', 'maker:list-agent-commands', ['claude-code']);
expect(s.invoke).toHaveBeenCalledWith('dev-1', 'maker:list-agent-skills', [
'claude-code',
- { workingDir: '/host/path' },
+ { workingDir: '/host/path', sessionId: 'remote-session' },
]);
// 结果 = 本地 desktop(help + goal,远程会话不再剔除)+ 被控端 builtin(host-cmd)+ 被控端 skill(host-skill)
expect(cmds.map((x) => x.name).sort()).toEqual(['goal', 'help', 'host-cmd', 'host-skill']);
diff --git a/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts b/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts
new file mode 100644
index 0000000000..70c5a11fa6
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts
@@ -0,0 +1,26 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const chatInputSource = readFileSync(
+ resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
+ 'utf8',
+).replace(/\r\n/g, '\n');
+
+describe('slash palette empty-result keyboard guard', () => {
+ it('captures Enter and Tab while the slash palette is open with no focused result', () => {
+ const selectionBlock = chatInputSource.slice(
+ chatInputSource.indexOf("case 'Enter':"),
+ chatInputSource.indexOf("case 'Escape':", chatInputSource.indexOf("case 'Enter':")),
+ );
+
+ expect(selectionBlock).toContain('if (slashOpen) {');
+ expect(selectionBlock).toContain('const focusedCommand = filteredCommands[slashFocus];');
+ expect(selectionBlock).toContain('if (!focusedCommand) {');
+ expect(selectionBlock).toContain("if (trigger.kind === 'slash') setSuppressedSlashAt(trigger.from);");
+ expect(selectionBlock.indexOf('return true;')).toBeLessThan(
+ selectionBlock.indexOf('if (\n atOpen'),
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts
index c32029770d..fe646d0eb9 100644
--- a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts
+++ b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts
@@ -38,6 +38,10 @@ describe('ChatInput voice input Enter-to-send contract', () => {
expect(keydownBlock).toContain('event.stopPropagation();');
expect(keydownBlock).toContain('void voiceInputStopAndSendRef.current(enterIntent);');
expect(keydownBlock).not.toContain('composerCanSubmitRef.current');
+ const paletteGuard = keydownBlock.indexOf('panelBridgeRef.current?.captureKey(event)');
+ const voiceSend = keydownBlock.indexOf('void voiceInputStopAndSendRef.current(enterIntent);');
+ expect(paletteGuard).toBeGreaterThan(-1);
+ expect(paletteGuard).toBeLessThan(voiceSend);
});
it('allows voice Enter-to-send only when the event target itself falls back to the document body', () => {
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index e9668a1bfd..0dbd531b32 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -214,8 +214,15 @@ import {
EMPTY_SLASH_COMMANDS,
failSlashCommandRosterLoad,
filterSlashCommands,
+ firstAvailableSlashCommandIndex,
+ hasAvailableSlashCommand,
+ hasUnavailableProjectSkillPreview,
+ isSlashCommandUnavailable,
isSlashCommandRosterReady,
loadAllCommands,
+ nextAvailableSlashCommandIndex,
+ PI_RUNTIME_SKILL_RETRY_DELAYS_MS,
+ slashCommandInvocationName,
type SlashCommandRosterState,
type UnifiedCommand,
} from '@/lib/slashCommands';
@@ -345,7 +352,6 @@ const ComposerHardBreak = HardBreak.extend({
// 自然宽度(permission + model + voice + send 等)估,实测可微调。
const TOOLBAR_DENSE_MAX_WIDTH = 520;
const TOOLBAR_COMPACT_MAX_WIDTH = 448;
-
function isVoiceInputIdleLike(state: VoiceInputState): boolean {
return state === 'idle' || state === 'done' || state === 'error';
}
@@ -2740,12 +2746,28 @@ export function ChatInput({
) {
event.preventDefault();
event.stopPropagation();
+ if (panelBridgeRef.current?.captureKey(event)) return;
clearPressTimer();
voiceShortcutPressRef.current = null;
void dispatchSendRef.current(enterIntent);
return;
}
+ // This window capture listener runs before Tiptap's palette bridge. While
+ // listening, preserve the editor's normal priority: Enter first selects
+ // or dismisses the open palette instead of stopping voice and sending the
+ // unresolved slash query.
+ if (
+ currentState === 'listening' &&
+ isComposerEnterTarget(event.target) &&
+ (enterIntent === 'queue' || enterIntent === 'steer') &&
+ panelBridgeRef.current?.captureKey(event)
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+
if (
currentState === 'listening' &&
voiceInputCanStopAndSendRef.current &&
@@ -3413,6 +3435,7 @@ export function ChatInput({
workingDir ?? null,
paletteAgentKind,
isRemoteSession,
+ sessionId ?? null,
deviceLinkDeviceId ?? null,
]);
const [slashCommandLoadState, setSlashCommandLoadState] = useState<SlashCommandRosterState>({
@@ -3438,6 +3461,7 @@ export function ChatInput({
[mergedCommands, planModeCommandAvailable, slashCommandsReady, t],
);
const slashCommandLoadSeqRef = useRef(0);
+ const piRuntimeRetryRef = useRef(0);
useEffect(
() => () => {
slashCommandLoadSeqRef.current += 1;
@@ -3455,7 +3479,7 @@ export function ChatInput({
loadAllCommands(
paletteAgentKind,
workingDir,
- { ...opts, skipAgentSkills: isRemoteSession },
+ { ...opts, skipAgentSkills: isRemoteSession, sessionId },
deviceLinkDeviceId,
)
.then((cmds) => {
@@ -3479,10 +3503,14 @@ export function ChatInput({
workingDir,
paletteAgentKind,
isRemoteSession,
+ sessionId,
deviceLinkDeviceId,
slashCommandContextKey,
],
);
+ useEffect(() => {
+ piRuntimeRetryRef.current = 0;
+ }, [slashCommandContextKey]);
useEffect(() => {
reloadSlashCommands();
}, [reloadSlashCommands]);
@@ -3772,10 +3800,15 @@ export function ChatInput({
const [slashFocus, setSlashFocus] = useState(0);
const [atFocus, setAtFocus] = useState(0);
- // Reset focus when the list shrinks below current index
+ // Keep keyboard focus on an executable row when filtering or runtime status changes.
useEffect(() => {
- if (slashFocus >= filteredCommands.length) setSlashFocus(0);
- }, [filteredCommands.length, slashFocus]);
+ setSlashFocus((current) => (
+ current >= filteredCommands.length
+ || (filteredCommands[current] && isSlashCommandUnavailable(filteredCommands[current]))
+ ? firstAvailableSlashCommandIndex(filteredCommands)
+ : current
+ ));
+ }, [filteredCommands]);
useEffect(() => {
if (
atFocus >= filteredAt.length ||
@@ -3852,6 +3885,21 @@ export function ChatInput({
if (!slashOpen) return;
reloadSlashCommands({ forceReload: true });
}, [slashOpen, reloadSlashCommands]);
+ useEffect(() => {
+ if (!slashOpen) {
+ piRuntimeRetryRef.current = 0;
+ return;
+ }
+ if (paletteAgentKind !== 'pi' || !sessionId) return;
+ if (!hasUnavailableProjectSkillPreview(mergedCommands)) return;
+ const attempt = piRuntimeRetryRef.current;
+ if (attempt >= PI_RUNTIME_SKILL_RETRY_DELAYS_MS.length) return;
+ piRuntimeRetryRef.current = attempt + 1;
+ const timer = window.setTimeout(() => {
+ reloadSlashCommands({ forceReload: true });
+ }, PI_RUNTIME_SKILL_RETRY_DELAYS_MS[attempt]);
+ return () => window.clearTimeout(timer);
+ }, [mergedCommands, paletteAgentKind, reloadSlashCommands, sessionId, slashOpen]);
// ── Panel → editor bridge for keyboard nav ─────────────────────────
// The editor's `handleKeyDown` fires before React re-renders, so we need
@@ -3868,7 +3916,7 @@ export function ChatInput({
switch (e.key) {
case 'ArrowDown':
if (slashOpen && filteredCommands.length > 0) {
- setSlashFocus((i) => (i + 1) % filteredCommands.length);
+ setSlashFocus((i) => nextAvailableSlashCommandIndex(filteredCommands, i, 1));
return true;
}
if (atOpen && filteredAt.length > 0) {
@@ -3878,7 +3926,7 @@ export function ChatInput({
return false;
case 'ArrowUp':
if (slashOpen && filteredCommands.length > 0) {
- setSlashFocus((i) => (i - 1 + filteredCommands.length) % filteredCommands.length);
+ setSlashFocus((i) => nextAvailableSlashCommandIndex(filteredCommands, i, -1));
return true;
}
if (atOpen && filteredAt.length > 0) {
@@ -3888,8 +3936,20 @@ export function ChatInput({
return false;
case 'Enter':
case 'Tab':
- if (slashOpen && filteredCommands[slashFocus]) {
- insertSlashCommand(filteredCommands[slashFocus]);
+ if (slashOpen) {
+ const focusedCommand = filteredCommands[slashFocus];
+ if (!focusedCommand) {
+ if (trigger.kind === 'slash') setSuppressedSlashAt(trigger.from);
+ return true;
+ }
+ if (isSlashCommandUnavailable(focusedCommand)) {
+ setSlashFocus(firstAvailableSlashCommandIndex(filteredCommands));
+ if (!hasAvailableSlashCommand(filteredCommands) && trigger.kind === 'slash') {
+ setSuppressedSlashAt(trigger.from);
+ }
+ return true;
+ }
+ insertSlashCommand(focusedCommand);
return true;
}
if (
@@ -3933,7 +3993,8 @@ export function ChatInput({
!editor ||
editor.isDestroyed ||
trigger.kind !== 'slash' || composerMutationLockedRef.current ||
- editor.view.composing
+ editor.view.composing ||
+ isSlashCommandUnavailable(cmd)
) {
return;
}
@@ -3983,7 +4044,13 @@ export function ChatInput({
} else {
// Slash 也保持纯文本;SlashCommandDecoration 只负责视觉确认,
// Backspace / 光标移动因此与普通文字完全一致。
- replaceSlashCommandRunWithText(tr, editor.schema, from, runEnd, cmd.name);
+ replaceSlashCommandRunWithText(
+ tr,
+ editor.schema,
+ from,
+ runEnd,
+ slashCommandInvocationName(cmd),
+ );
}
return true;
})
diff --git a/apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx b/apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx
index 0911dac67f..b6575c6a18 100644
--- a/apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx
@@ -14,10 +14,12 @@
*/
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
+import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import {
filterSlashCommands,
+ isSlashCommandUnavailable,
type UnifiedCommand,
} from '@/lib/slashCommands';
@@ -67,6 +69,7 @@ export function SlashCommandPalette({
onTooltipHoverChange,
maxHeight = 400,
}: SlashCommandPaletteProps) {
+ const { t } = useTranslation();
const filtered = useMemo(() => filterSlashCommands(commands, query), [commands, query]);
const rootRef = useRef<HTMLDivElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
@@ -227,15 +230,20 @@ export function SlashCommandPalette({
) : (
filtered.map((cmd, idx) => {
const focused = idx === focusedIndex;
+ const unavailable = isSlashCommandUnavailable(cmd);
return (
<button
key={cmd.name}
ref={focused ? focusedRef : undefined}
type="button"
+ aria-disabled={unavailable}
+ aria-label={unavailable ? `${cmd.name}: ${t('commandPalette.projectTrustRequired')}` : cmd.name}
+ title={unavailable ? t('commandPalette.projectTrustRequired') : undefined}
// `onMouseDown` instead of `onClick` so the textarea
// keeps focus — click would fire after blur.
onMouseDown={(e) => {
e.preventDefault();
+ if (unavailable) return;
onSelect(cmd);
}}
onMouseEnter={() => onFocusedIndexChange(idx)}
@@ -246,6 +254,7 @@ export function SlashCommandPalette({
'text-[var(--cmd-palette-item-text)]',
'outline-none transition-colors',
focused && 'bg-[var(--cmd-palette-item-hover)]',
+ unavailable && 'cursor-not-allowed opacity-50',
)}
>
<span className="truncate">{cmd.name}</span>
@@ -285,7 +294,9 @@ export function SlashCommandPalette({
{focusedCmd.name}
</div>
<div className="mt-[8px] text-13 leading-[1.5] text-[var(--cmd-palette-tooltip-body)]">
- {focusedCmd.description}
+ {isSlashCommandUnavailable(focusedCmd)
+ ? t('commandPalette.projectTrustRequired')
+ : focusedCmd.description}
</div>
</div>,
document.body,
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index db44e1c55f..9681e8d27a 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -133,13 +133,23 @@ import {
useControlledBy,
} from '@/features/remote-device/ControlledBanner';
import { useAnimatedNumber } from '@/hooks/useAnimatedNumber';
+import {
+ loadAllCommands,
+ dispatchCommand,
+ PI_RUNTIME_SKILL_RETRY_DELAYS_MS,
+ rebaseInlineRangesAfterSlashCommandRewrite,
+ reconcilePiRuntimeCommandForDispatch,
+ reconcilePiRuntimeCommandForDispatchWithRetry,
+ rewriteAgentSkillInvocationForDispatch,
+ type UnifiedCommand,
+} from '@/lib/slashCommands';
import { useReducedMotion } from '@/hooks/useReducedMotion';
-import { loadAllCommands, dispatchCommand, type UnifiedCommand } from '@/lib/slashCommands';
import * as sessionService from '@/lib/sessionService';
import { emitRefresh } from '@/lib/sessionsBus';
import type { Session } from '@/lib/ccAgent.types';
import { toast } from '@/lib/toast';
import {
+ buildCreateOptsForCurrentSession,
decodeRemoteErrorMessage,
makerChatStore,
type AgentTaskUpdate,
@@ -1201,7 +1211,10 @@ export function CCAgentSessionView({
// (与 ChatInput palette 同源)。否则此 cache 取的是控制端命令,maybeDispatchDesktopSlashCommand
// 会把被控端 skill/builtin 影子掉的 /clear、/help 等误判成 desktop 命令、在控制端执行。
// 本机会话 remoteDeviceId=undefined → 行为不变。desktop 命令始终本地(见 loadAllCommands)。
- loadAllCommands(agentKind, wd, { skipAgentSkills: isRemoteSession }, remoteDeviceId)
+ loadAllCommands(agentKind, wd, {
+ skipAgentSkills: isRemoteSession,
+ sessionId: session?.id,
+ }, remoteDeviceId)
.then((cmds) => {
if (!cancelled) setAllCommands(cmds);
})
@@ -1211,7 +1224,7 @@ export function CCAgentSessionView({
return () => {
cancelled = true;
};
- }, [session?.agentKind, session?.workingDir, isRemoteSession, remoteDeviceId]);
+ }, [session?.id, session?.agentKind, session?.workingDir, isRemoteSession, remoteDeviceId]);
// Keep lastWorkingDir in sync so Settings can distinguish a real project
// scope from「新对话默认值」. Standalone dialogues have an internal runtime
@@ -1752,13 +1765,13 @@ export function CCAgentSessionView({
return await loadAllCommands(
agentKind,
session?.workingDir,
- { skipAgentSkills: isRemoteSession },
+ { skipAgentSkills: isRemoteSession, sessionId: session?.id },
remoteDeviceId,
);
} catch {
return [];
}
- }, [session?.agentKind, session?.workingDir, isRemoteSession, remoteDeviceId]);
+ }, [session?.id, session?.agentKind, session?.workingDir, isRemoteSession, remoteDeviceId]);
const insertHelpCard = useCallback(async () => {
const commands = await getHelpCommandsSnapshot();
@@ -2206,72 +2219,6 @@ export function CCAgentSessionView({
}
}, [sessionId]);
- const handleWorkingDirChange = useCallback(
- (newDir: string | null) => {
- // ChatInput already persists workingDir to server; we just refresh our local copy.
- refreshServerSession();
-
- // Auto-continue: if there's a pending send and a valid dir was selected, execute step ③
- if (newDir && pendingSendRef.current) {
- const {
- deliveryMode,
- message,
- model,
- effort,
- permissionMode,
- files,
- mentions,
- vendorOptions,
- quotesEncoded,
- agentReferences,
- pastedTextRanges,
- slashCommandRanges,
- onRemoteOptimisticFailure,
- onDeferredAccepted,
- } = pendingSendRef.current;
- pendingSendRef.current = null;
- const dispatch = deliveryMode === 'steer' ? steerMessage : sendMessage;
- void dispatch(
- message,
- model,
- effort,
- permissionMode,
- newDir,
- files,
- mentions,
- quotesEncoded ||
- vendorOptions !== undefined ||
- agentReferences?.length ||
- pastedTextRanges?.length ||
- slashCommandRanges !== undefined ||
- onRemoteOptimisticFailure !== undefined ||
- onDeferredAccepted !== undefined
- ? {
- ...(vendorOptions ? { vendorOptions } : {}),
- ...(quotesEncoded ? { quotesEncoded: true } : {}),
- ...(agentReferences?.length ? { agentReferences } : {}),
- ...(pastedTextRanges?.length ? { pastedTextRanges } : {}),
- ...(slashCommandRanges !== undefined ? { slashCommandRanges } : {}),
- ...(onRemoteOptimisticFailure ? { onRemoteOptimisticFailure } : {}),
- ...(onDeferredAccepted ? { onDeferredAccepted } : {}),
- }
- : undefined,
- ).then(
- (accepted) => {
- if (accepted) onDeferredAccepted?.();
- },
- (error) => {
- log.warn(
- 'pending send after working directory selection failed:',
- error instanceof Error ? error.message : String(error),
- );
- },
- );
- }
- },
- [refreshServerSession, sendMessage, steerMessage],
- );
-
const handleFolderPickerOpenChange = useCallback((open: boolean) => {
setFolderPickerOpen(open);
// If user closed the popover without selecting, clear pending send
@@ -2401,15 +2348,68 @@ export function CCAgentSessionView({
const pendingIssueFilesRef = useRef<AttachedFile[] | undefined>(undefined);
const maybeDispatchDesktopSlashCommand = useCallback(
- async (message: string, files?: AttachedFile[]): Promise<boolean> => {
+ async (
+ message: string,
+ files?: AttachedFile[],
+ options?: {
+ allowDesktopDispatch?: boolean;
+ piRuntimeRetryDelaysMs?: readonly number[];
+ workingDirOverride?: string;
+ preparePiRuntime?: () => Promise<void>;
+ },
+ ): Promise<{ handled: boolean; message: string }> => {
const slashMatch = message.match(/^\/(\S+)(?:\s+(.*))?$/s);
- if (!slashMatch) return false;
+ if (!slashMatch) return { handled: false, message };
const cmdName = slashMatch[1].toLowerCase();
const args = slashMatch[2] ?? '';
+ const allowDesktopDispatch = options?.allowDesktopDispatch ?? true;
+ const workingDir = options?.workingDirOverride ?? session?.workingDir;
const cached = allCommandsRef.current;
- const commands = cached.length > 0 ? cached : await getHelpCommandsSnapshot();
- const hit = commands.find((c) => c.name.toLowerCase() === cmdName);
- if (hit?.kind !== 'desktop') return false;
+ // A newly selected project changes command ownership, so do not let a
+ // pre-selection global hit suppress the forced project catalog refresh.
+ const commands = options?.workingDirOverride
+ ? []
+ : cached.length > 0
+ ? cached
+ : await getHelpCommandsSnapshot();
+ const agentKind = dbToMakerAgentKind(session?.agentKind);
+ const reconcileParams = {
+ agentKind,
+ sessionId: session?.id,
+ commandName: cmdName,
+ commands,
+ reload: () => loadAllCommands(
+ agentKind,
+ workingDir,
+ {
+ skipAgentSkills: isRemoteSession,
+ sessionId: session?.id,
+ forceReload: true,
+ },
+ remoteDeviceId,
+ ),
+ };
+ const reconciled = options?.piRuntimeRetryDelaysMs
+ ? await reconcilePiRuntimeCommandForDispatchWithRetry({
+ ...reconcileParams,
+ prepareRuntime: options.preparePiRuntime,
+ retryDelaysMs: options.piRuntimeRetryDelaysMs,
+ })
+ : await reconcilePiRuntimeCommandForDispatch(reconcileParams);
+ if (reconciled.commands !== commands) {
+ allCommandsRef.current = reconciled.commands;
+ setAllCommands(reconciled.commands);
+ }
+ const hit = reconciled.command;
+ if (hit?.kind !== 'desktop') {
+ return {
+ handled: false,
+ message: agentKind === 'pi'
+ ? rewriteAgentSkillInvocationForDispatch(message, hit)
+ : message,
+ };
+ }
+ if (!allowDesktopDispatch) return { handled: false, message };
// 仅 /issue 需要携带附件:snapshot 到 ref,DESKTOP_COMMAND_TRIGGERED 回流时消费。
// 其它 desktop 命令(/help /clear /cmd ...)不涉及附件,不写 ref。
if (hit.name === 'issue') {
@@ -2421,13 +2421,153 @@ export function CCAgentSessionView({
// (/cmd 拿被控端路径本机 spawn、/goal /learn 在本机产生副作用;Codex review #548)。
void dispatchCommand(hit, {
...(sessionId ? { sessionId } : {}),
- ...(session?.workingDir ? { workingDir: session.workingDir } : {}),
+ ...(workingDir ? { workingDir } : {}),
...(args ? { args } : {}),
...(remoteDeviceId ? { deviceId: remoteDeviceId } : {}),
});
- return true;
+ return { handled: true, message };
+ },
+ [
+ getHelpCommandsSnapshot,
+ isRemoteSession,
+ session?.agentKind,
+ session?.id,
+ session?.workingDir,
+ sessionId,
+ remoteDeviceId,
+ ],
+ );
+
+ const handleWorkingDirChange = useCallback(
+ (newDir: string | null) => {
+ // ChatInput already persists workingDir to server; we just refresh our local copy.
+ refreshServerSession();
+
+ // Auto-continue: if there's a pending send and a valid dir was selected, execute step ③.
+ // The first slash reconciliation ran before this directory existed, so refresh again with
+ // the selected project before dispatching and keep inline metadata aligned with any alias rewrite.
+ const pending = pendingSendRef.current;
+ if (!newDir || !pending) return;
+ pendingSendRef.current = null;
+ void (async () => {
+ try {
+ const slashDispatch = await maybeDispatchDesktopSlashCommand(
+ pending.message,
+ pending.files,
+ {
+ allowDesktopDispatch: pending.deliveryMode !== 'steer',
+ piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,
+ workingDirOverride: newDir,
+ preparePiRuntime: async () => {
+ if (!sessionId || dbToMakerAgentKind(session?.agentKind) !== 'pi') return;
+ const createOpts = {
+ id: sessionId,
+ ...buildCreateOptsForCurrentSession(
+ sessionId,
+ pending.model,
+ pending.effort,
+ pending.permissionMode,
+ newDir,
+ pending.vendorOptions ? { vendorOptions: pending.vendorOptions } : undefined,
+ ),
+ agentKind: 'pi' as const,
+ workingDir: newDir,
+ orcaRole: session?.orcaRole ?? null,
+ };
+ if (remoteDeviceId) {
+ await window.electronAPI.deviceLink.invoke(
+ remoteDeviceId,
+ 'maker:create-session',
+ [createOpts],
+ );
+ } else {
+ await window.electronAPI.maker.createSession(createOpts);
+ }
+ },
+ },
+ );
+ if (slashDispatch.handled) {
+ pending.onDeferredAccepted?.();
+ return;
+ }
+
+ const pendingAgentReferences = pending.agentReferences
+ ? rebaseInlineRangesAfterSlashCommandRewrite(
+ pending.agentReferences,
+ pending.message,
+ slashDispatch.message,
+ )
+ : undefined;
+ const pendingPastedTextRanges = pending.pastedTextRanges
+ ? rebaseInlineRangesAfterSlashCommandRewrite(
+ pending.pastedTextRanges,
+ pending.message,
+ slashDispatch.message,
+ )
+ : undefined;
+ const pendingSlashCommandRanges = pending.slashCommandRanges !== undefined
+ ? rebaseInlineRangesAfterSlashCommandRewrite(
+ pending.slashCommandRanges,
+ pending.message,
+ slashDispatch.message,
+ )
+ : undefined;
+ const dispatch = pending.deliveryMode === 'steer' ? steerMessage : sendMessage;
+ const accepted = await dispatch(
+ slashDispatch.message,
+ pending.model,
+ pending.effort,
+ pending.permissionMode,
+ newDir,
+ pending.files,
+ pending.mentions,
+ pending.quotesEncoded ||
+ pending.vendorOptions !== undefined ||
+ pendingAgentReferences?.length ||
+ pendingPastedTextRanges?.length ||
+ pendingSlashCommandRanges !== undefined ||
+ pending.onRemoteOptimisticFailure !== undefined ||
+ pending.onDeferredAccepted !== undefined
+ ? {
+ ...(pending.vendorOptions ? { vendorOptions: pending.vendorOptions } : {}),
+ ...(pending.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(pendingAgentReferences?.length
+ ? { agentReferences: pendingAgentReferences }
+ : {}),
+ ...(pendingPastedTextRanges?.length
+ ? { pastedTextRanges: pendingPastedTextRanges }
+ : {}),
+ ...(pendingSlashCommandRanges !== undefined
+ ? { slashCommandRanges: pendingSlashCommandRanges }
+ : {}),
+ ...(pending.onRemoteOptimisticFailure
+ ? { onRemoteOptimisticFailure: pending.onRemoteOptimisticFailure }
+ : {}),
+ ...(pending.onDeferredAccepted
+ ? { onDeferredAccepted: pending.onDeferredAccepted }
+ : {}),
+ }
+ : undefined,
+ );
+ if (accepted) pending.onDeferredAccepted?.();
+ } catch (error) {
+ log.warn(
+ 'pending send after working directory selection failed:',
+ error instanceof Error ? error.message : String(error),
+ );
+ }
+ })();
},
- [getHelpCommandsSnapshot, session?.workingDir, sessionId, remoteDeviceId],
+ [
+ maybeDispatchDesktopSlashCommand,
+ refreshServerSession,
+ remoteDeviceId,
+ session?.agentKind,
+ session?.orcaRole,
+ sessionId,
+ sendMessage,
+ steerMessage,
+ ],
);
const maybeShowContextUsage = useCallback(
@@ -2534,8 +2674,48 @@ export function CCAgentSessionView({
// 广播回 renderer (上面 useEffect 订阅), 不发给 agent。
// - agent-builtin / agent-skill / 没命中任何已知命令 → 走默认 send,
// 原文(含前导 `/`)直接送 agent, 由 SDK 自己识别 (/compact 等)。
- if (deliveryMode !== 'steer' && (await maybeDispatchDesktopSlashCommand(message, files))) {
- return;
+ const originalMessage = message;
+ const slashDispatch = deliveryMode === 'steer'
+ ? await maybeDispatchDesktopSlashCommand(message, files, {
+ allowDesktopDispatch: false,
+ piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,
+ })
+ : await maybeDispatchDesktopSlashCommand(message, files, {
+ piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,
+ });
+ if (slashDispatch.handled) return;
+ message = slashDispatch.message;
+ if (message !== originalMessage && opts) {
+ opts = {
+ ...opts,
+ ...(opts.agentReferences
+ ? {
+ agentReferences: rebaseInlineRangesAfterSlashCommandRewrite(
+ opts.agentReferences,
+ originalMessage,
+ message,
+ ),
+ }
+ : {}),
+ ...(opts.pastedTextRanges
+ ? {
+ pastedTextRanges: rebaseInlineRangesAfterSlashCommandRewrite(
+ opts.pastedTextRanges,
+ originalMessage,
+ message,
+ ),
+ }
+ : {}),
+ ...(opts.slashCommandRanges !== undefined
+ ? {
+ slashCommandRanges: rebaseInlineRangesAfterSlashCommandRewrite(
+ opts.slashCommandRanges,
+ originalMessage,
+ message,
+ ),
+ }
+ : {}),
+ };
}
// ① 本机会话维持既有 readiness gate。device-link 已建任务不把视图生命周期内
@@ -2997,15 +3177,43 @@ export function CCAgentSessionView({
}
// 三处交接统一走 deliverRecoverableHandoff:交付成功才丢副本,
// resolve false / 抛错都保留(见该函数注释)。
- const dispatched = await deliverRecoverableHandoff(sessionId, () =>
- maybeDispatchDesktopSlashCommand(pending.text, pending.files),
- );
+ let pendingText = pending.text;
+ const dispatched = await deliverRecoverableHandoff(sessionId, async () => {
+ const slashDispatch = await maybeDispatchDesktopSlashCommand(
+ pending.text,
+ pending.files,
+ { piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS },
+ );
+ pendingText = slashDispatch.message;
+ return slashDispatch.handled;
+ });
if (dispatched) return;
+ const pendingAgentReferences = pending.agentReferences
+ ? rebaseInlineRangesAfterSlashCommandRewrite(
+ pending.agentReferences,
+ pending.text,
+ pendingText,
+ )
+ : undefined;
+ const pendingPastedTextRanges = pending.pastedTextRanges
+ ? rebaseInlineRangesAfterSlashCommandRewrite(
+ pending.pastedTextRanges,
+ pending.text,
+ pendingText,
+ )
+ : undefined;
+ const pendingSlashCommandRanges = pending.slashCommandRanges !== undefined
+ ? rebaseInlineRangesAfterSlashCommandRewrite(
+ pending.slashCommandRanges,
+ pending.text,
+ pendingText,
+ )
+ : undefined;
// 必须 await:sendMessage 在设备离线 / 访问被撤销 / 远端 enqueue 拒绝时不抛错,
// 而是 resolve false —— 不等它就丢副本,正文会从界面和磁盘上一起消失(codex P1)。
await deliverRecoverableHandoff(sessionId, () =>
sendMessage(
- pending.text,
+ pendingText,
session.model,
session.effort as Effort,
session.permissionMode as PermissionMode,
@@ -3014,20 +3222,20 @@ export function CCAgentSessionView({
pending.mentions,
pending.vendorOptions ||
pending.quotesEncoded ||
- pending.agentReferences?.length ||
- pending.pastedTextRanges?.length ||
- pending.slashCommandRanges !== undefined
+ pendingAgentReferences?.length ||
+ pendingPastedTextRanges?.length ||
+ pendingSlashCommandRanges !== undefined
? {
...(pending.vendorOptions ? { vendorOptions: pending.vendorOptions } : {}),
...(pending.quotesEncoded ? { quotesEncoded: true } : {}),
- ...(pending.agentReferences?.length
- ? { agentReferences: pending.agentReferences }
+ ...(pendingAgentReferences?.length
+ ? { agentReferences: pendingAgentReferences }
: {}),
- ...(pending.pastedTextRanges?.length
- ? { pastedTextRanges: pending.pastedTextRanges }
+ ...(pendingPastedTextRanges?.length
+ ? { pastedTextRanges: pendingPastedTextRanges }
: {}),
- ...(pending.slashCommandRanges !== undefined
- ? { slashCommandRanges: pending.slashCommandRanges }
+ ...(pendingSlashCommandRanges !== undefined
+ ? { slashCommandRanges: pendingSlashCommandRanges }
: {}),
}
: undefined,
diff --git a/apps/desktop/src/renderer/features/skillhub/PublishDialog.tsx b/apps/desktop/src/renderer/features/skillhub/PublishDialog.tsx
index 8b5a44f98d..d3fc250574 100644
--- a/apps/desktop/src/renderer/features/skillhub/PublishDialog.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/PublishDialog.tsx
@@ -791,7 +791,9 @@ export function PublishDialog({
let publishAbsolutePath = eff.absolutePath;
if (autoCleanName && !renamedToRef.current && submitName !== eff.name) {
const renameRes = await window.electronAPI.skillhub.renameLocal({
- absolutePath: eff.absolutePath,
+ // Keep the lexical discovery path for lstat: canonical absolutePath may
+ // point at a symlink target and would bypass the rename safety gate.
+ absolutePath: skill.discoveredPath ?? eff.absolutePath,
newName: submitName,
});
if (!renameRes.success) {
@@ -812,7 +814,18 @@ export function PublishDialog({
// 应该走专门的入口,不应混在"发新版本"里默默动。
const params = buildCurrentPublishParams(publishAbsolutePath, submitName);
runPublish(params);
- }, [canSubmit, form, effectiveSkill, effectiveFirstPublish, autoCleanName, confirm, t, buildCurrentPublishParams, runPublish]);
+ }, [
+ canSubmit,
+ form,
+ effectiveSkill,
+ effectiveFirstPublish,
+ autoCleanName,
+ confirm,
+ t,
+ buildCurrentPublishParams,
+ runPublish,
+ skill.discoveredPath,
+ ]);
// ── Cancel publish in progress (working / failure 都可调) ────────────────
const handleCancelWorking = useCallback(async () => {
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
index 420c7d34ad..b08af045f3 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
@@ -45,6 +45,11 @@ import {
} from './hooks/useSkillhub';
import { triggerIncrementalSync } from './hooks/useSkillSync';
import { type DetailState, deriveDetailActionState, deriveDetailState } from './lib/detailButtons';
+import {
+ buildLocalSkillRoute,
+ findLocalSkillByPath,
+ findLocalSkillRouteEntry,
+} from './lib/localRoutes';
import { isMarketDeleted as checkMarketDeleted, getCachedInfo, invalidate as invalidateInfo, refreshInfo } from './lib/infoDedupe';
import {
activePublishedReviewFromVersions,
@@ -979,27 +984,10 @@ export function SkillhubDetailView() {
const metaResize = useMetaColumnResize();
const entry = useMemo(() => {
- const { kind, projectHash, name } = params as Record<string, string | undefined>;
- if (!kind || !name) return null;
- const decodedName = decodeURIComponent(name);
- const engine = searchParams.get('engine');
- const matchEngine = (s: SkillhubSkill) => !engine || s.engine === engine;
- if (projectHash) {
- return (
- skills.find(
- (s) =>
- s.kind === kind &&
- s.scope === 'project' &&
- s.projectHash === projectHash &&
- s.name === decodedName &&
- matchEngine(s),
- ) ?? null
- );
- }
- return (
- skills.find(
- (s) => s.kind === kind && s.scope === 'global' && s.name === decodedName && matchEngine(s),
- ) ?? null
+ return findLocalSkillRouteEntry(
+ skills,
+ params as Record<string, string | undefined>,
+ searchParams,
);
}, [params, searchParams, skills]);
@@ -1870,19 +1858,32 @@ export function SkillhubDetailView() {
</h2>
<KindChip kind={entry.kind} />
<ScopeChip scope={entry.scope} />
- {entry.linkedEngines.map(le => (
- <span
- key={le.engine}
- className={cn(
- 'inline-flex h-5 shrink-0 items-center rounded-full px-2 whitespace-nowrap',
- 'bg-[var(--settings-btn-secondary-bg)] text-[var(--msg-assistant-text)]',
- )}
- >
- <span className="relative top-[0.5px] text-11 font-medium leading-none">
- {le.label}
+ {entry.linkedEngines.map(le => {
+ const statusKey = le.runtimeStatus === 'discovered'
+ ? 'skillhub.common.statusDiscovered'
+ : le.runtimeStatus === 'approved'
+ ? 'skillhub.common.statusApproved'
+ : le.runtimeStatus === 'loaded'
+ ? 'skillhub.common.statusLoaded'
+ : le.runtimeStatus === 'failed'
+ ? 'skillhub.common.statusFailed'
+ : le.runtimeStatus === 'unknown'
+ ? 'skillhub.common.statusUnknown'
+ : null;
+ return (
+ <span
+ key={le.engine}
+ className={cn(
+ 'inline-flex h-5 shrink-0 items-center rounded-full px-2 whitespace-nowrap',
+ 'bg-[var(--settings-btn-secondary-bg)] text-[var(--msg-assistant-text)]',
+ )}
+ >
+ <span className="relative top-[0.5px] text-11 font-medium leading-none">
+ {statusKey ? `${le.label} · ${t(statusKey)}` : le.label}
+ </span>
</span>
- </span>
- ))}
+ );
+ })}
{detailState?.isMine && publishedStatus === 'rejected' && (
<Tip text={t('skillhub.detail.rejectedTooltip')}>
<button
@@ -2564,20 +2565,13 @@ export function SkillhubDetailView() {
// + 旧 name 的 info 缓存(让新 name 重新查),然后刷新 scanner,
// 最后导航到新 URL。先 await refresh 才 navigate,确保新 URL 落地时
// skills 已包含新 entry,免得短暂闪一下"未找到"。
- const newId = entry
- ? `${entry.kind}:${entry.scope}:${entry.scope === 'project' ? `${entry.projectHash}:` : ''}${newName}`
- : null;
- const newUrl = entry
- ? entry.scope === 'global'
- ? `/skillhub/local/${entry.kind}/global/${encodeURIComponent(newName)}`
- : `/skillhub/local/${entry.kind}/project/${entry.projectHash}/${encodeURIComponent(newName)}`
- : null;
invalidateInfo(entry.name);
invalidateHash(newAbsolutePath);
- // 在新 URL 上替换 lastEntryId,避免下次启动还指向旧 id
- if (newId) setLastEntryId(newId);
- void refreshSkillhub().then(() => {
- if (newUrl) navigate(newUrl, { replace: true });
+ void refreshSkillhub().then((scannedSkills) => {
+ const renamed = findLocalSkillByPath(scannedSkills, newAbsolutePath);
+ if (!renamed) return;
+ setLastEntryId(renamed.id);
+ navigate(buildLocalSkillRoute(renamed), { replace: true });
});
}}
onScanResult={setScanResult}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
index f2d628e9aa..02ce019acd 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
@@ -130,11 +130,13 @@ export function SkillhubFeatureLayout() {
const skillhubProjects = useMemo<SkillhubProject[] | null>(() => {
if (sessionsLoading) return null;
const { projects } = groupSessions(sessions);
- return projects.map((p) => ({
- projectRoot: p.workingDir,
- hash: projectHash(p.workingDir),
- displayName: p.displayName,
- }));
+ return projects
+ .filter((p) => p.scope === 'local')
+ .map((p) => ({
+ projectRoot: p.workingDir,
+ hash: projectHash(p.workingDir),
+ displayName: p.displayName,
+ }));
}, [sessions, sessionsLoading]);
useEffect(() => {
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
index a4c1de491e..257131d566 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
@@ -32,6 +32,7 @@ import {
PluginManagementPage,
} from '@/features/plugin/PluginManagementLayout';
import { canAccessSkillhubMarket } from './lib/marketAccess';
+import { buildLocalSkillRoute, findLocalSkillByPath } from './lib/localRoutes';
import { refresh as refreshSkillhub, useSkillhub } from './hooks/useSkillhub';
import { useMarketList, type MarketSkill } from './hooks/useMarketList';
import { basename, deriveProjectWorkingDir } from './lib/pathDerivations';
@@ -150,15 +151,10 @@ export function SkillhubHomeView() {
const [importBusy, setImportBusy] = useState(false);
const openLocal = (s: SkillhubSkill) => {
- const name = encodeURIComponent(s.name);
- const base =
- s.scope === 'global'
- ? `/skillhub/local/${s.kind}/global/${name}`
- : `/skillhub/local/${s.kind}/project/${s.projectHash}/${name}`;
// 从首页进入 = 一次全新入口:清掉旧的技能历史栈(resetHistory),并把回退落点
// 设为首页(from)。这样详情页「返回」回到首页这一步,而不是会话内残留的上一个技能。
// 详情→详情的链式跳转不带 resetHistory,链路仍能逐级回退。
- navigate(`${base}?engine=${s.engine}`, {
+ navigate(buildLocalSkillRoute(s), {
state: { from: '/skillhub/local', resetHistory: true },
});
};
@@ -432,22 +428,33 @@ export function SkillhubHomeView() {
});
}}
onInstallComplete={(result) => {
- void refreshSkillhub();
closeImportPicker();
if (!result?.name) return;
- const name = encodeURIComponent(result.name);
- const projectRoot = result.absolutePath
- ? deriveProjectWorkingDir(result.absolutePath)
- : null;
- if (projectRoot) {
- navigate(
- `/skillhub/local/skill/project/${projectHash(projectRoot)}/${name}`,
- { state: { from: '/skillhub/local', resetHistory: true } },
- );
- return;
- }
- navigate(`/skillhub/local/skill/global/${name}`, {
- state: { from: '/skillhub/local', resetHistory: true },
+ void refreshSkillhub().then((scannedSkills) => {
+ const imported = result.absolutePath
+ ? findLocalSkillByPath(scannedSkills, result.absolutePath)
+ : undefined;
+ if (imported) {
+ navigate(buildLocalSkillRoute(imported), {
+ state: { from: '/skillhub/local', resetHistory: true },
+ });
+ return;
+ }
+ const projectRoot = result.absolutePath
+ ? deriveProjectWorkingDir(result.absolutePath)
+ : null;
+ const fallback = {
+ id: '',
+ absolutePath: result.absolutePath ?? '',
+ engine: 'claude-code' as const,
+ kind: 'skill' as const,
+ scope: projectRoot ? 'project' as const : 'global' as const,
+ projectHash: projectRoot ? projectHash(projectRoot) : undefined,
+ name: result.name,
+ };
+ navigate(buildLocalSkillRoute(fallback), {
+ state: { from: '/skillhub/local', resetHistory: true },
+ });
});
}}
/>
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts
index 83ca117ef1..b10dd50c2c 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts
@@ -7,7 +7,7 @@ vi.mock('../useSkillSync', () => ({
invalidateSkillSyncRequests: vi.fn(),
}));
-import { bootstrapSkillhub, setSkillhubDataOwner } from '../useSkillhub';
+import { bootstrapSkillhub, refresh, reset, setSkillhubDataOwner } from '../useSkillhub';
describe('SkillHub data-owner bootstrap', () => {
const scan = vi.fn();
@@ -31,4 +31,27 @@ describe('SkillHub data-owner bootstrap', () => {
expect(scan).toHaveBeenLastCalledWith({ projects: [] });
});
+
+ it('makes a stale refresh wait for and return the newest scan result', async () => {
+ reset();
+ let resolveFirst!: (value: { success: true; skills: SkillhubSkill[]; sources: [] }) => void;
+ let resolveSecond!: (value: { success: true; skills: SkillhubSkill[]; sources: [] }) => void;
+ scan
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));
+ const latestSkill = { id: 'skill:global:latest', name: 'latest' } as SkillhubSkill;
+
+ const first = refresh();
+ const second = refresh();
+ let firstSettled = false;
+ void first.then(() => { firstSettled = true; });
+
+ resolveFirst({ success: true, skills: [], sources: [] });
+ await Promise.resolve();
+ expect(firstSettled).toBe(false);
+
+ resolveSecond({ success: true, skills: [latestSkill], sources: [] });
+ await expect(second).resolves.toEqual([latestSkill]);
+ await expect(first).resolves.toEqual([latestSkill]);
+ });
});
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
index b0b0ac9633..44808780bb 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
@@ -74,37 +74,49 @@ function setState(patch: Partial<SkillhubState>): void {
// 过期结果保护:每次 scan 领取递增 id,只有最新请求能写回 state,避免旧项目列表的
// 慢响应覆盖新项目列表的扫描结果。
let scanRequestId = 0;
+let latestScan: { id: number; promise: Promise<SkillhubSkill[]> } | null = null;
-export async function refresh(): Promise<void> {
+export function refresh(): Promise<SkillhubSkill[]> {
const myId = ++scanRequestId;
- setState({ loading: true, error: null });
- try {
- const result = await window.electronAPI.skillhub.scan({
- projects: state.projects.map((p) => ({ projectRoot: p.projectRoot, hash: p.hash })),
- });
- if (myId !== scanRequestId) return;
- if (result.success) {
+ const promise = (async (): Promise<SkillhubSkill[]> => {
+ setState({ loading: true, error: null });
+ try {
+ const result = await window.electronAPI.skillhub.scan({
+ projects: state.projects.map((p) => ({ projectRoot: p.projectRoot, hash: p.hash })),
+ });
+ if (myId !== scanRequestId) {
+ return latestScan?.id === scanRequestId ? latestScan.promise : state.skills;
+ }
+ if (result.success) {
+ const skills = result.skills ?? [];
+ setState({
+ skills,
+ sources: result.sources ?? [],
+ loading: false,
+ bootstrapped: true,
+ });
+ return skills;
+ }
setState({
- skills: result.skills ?? [],
- sources: result.sources ?? [],
+ error: result.error ?? 'scan failed with no error message',
loading: false,
bootstrapped: true,
});
- } else {
+ return state.skills;
+ } catch (err) {
+ if (myId !== scanRequestId) {
+ return latestScan?.id === scanRequestId ? latestScan.promise : state.skills;
+ }
setState({
- error: result.error ?? 'scan failed with no error message',
+ error: err instanceof Error ? err.message : String(err),
loading: false,
bootstrapped: true,
});
+ return state.skills;
}
- } catch (err) {
- if (myId !== scanRequestId) return;
- setState({
- error: err instanceof Error ? err.message : String(err),
- loading: false,
- bootstrapped: true,
- });
- }
+ })();
+ latestScan = { id: myId, promise };
+ return promise;
}
/**
@@ -184,6 +196,7 @@ export function setSyncError(err: string | null): void {
*/
export function reset(): void {
scanRequestId += 1;
+ latestScan = null;
invalidateSkillSyncRequests();
bootstrapped = false;
state = {
@@ -223,7 +236,7 @@ function ensureAuthListener(): void {
registerSyncStoreSetters({ setSyncResults, mergeSyncResults, setSyncError });
interface UseSkillhubReturn extends SkillhubState {
- refresh: () => Promise<void>;
+ refresh: () => Promise<SkillhubSkill[]>;
}
export function useSkillhub(): UseSkillhubReturn {
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
new file mode 100644
index 0000000000..38aecb4ac4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/localRoutes.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildLocalSkillRoute,
+ findLocalSkillByPath,
+ findLocalSkillRouteEntry,
+} from '../localRoutes';
+
+type Entry = Parameters<typeof buildLocalSkillRoute>[0];
+
+function entry(overrides: Partial<Entry> = {}): Entry {
+ return {
+ id: 'pi:skill:project:abcd1234:demo',
+ engine: 'pi',
+ kind: 'skill',
+ scope: 'project',
+ name: 'demo',
+ absolutePath: '/repo/.pi/skills/demo',
+ projectHash: 'abcd1234',
+ ...overrides,
+ };
+}
+
+describe('local SkillHub routes', () => {
+ it('finds a renamed skill by its lexical discovered path when absolutePath is realpathed', () => {
+ const renamed = entry({
+ absolutePath: '/shared/skills/renamed',
+ discoveredPath: '/home/user/.claude/skills/renamed',
+ });
+
+ expect(findLocalSkillByPath(
+ [renamed],
+ '/home/user/.claude/skills/renamed',
+ )).toBe(renamed);
+ });
+
+ it('keeps the existing URL shape for an unambiguous skill', () => {
+ expect(buildLocalSkillRoute(entry())).toBe(
+ '/skillhub/local/skill/project/abcd1234/demo?engine=pi',
+ );
+ });
+
+ it('keeps a unique source stable when a same-name source appears later', () => {
+ const original = entry({ sourceKey: 'pi-source' });
+ const route = buildLocalSkillRoute(original);
+ const addedLater = entry({
+ id: 'pi:demo:agents-source',
+ absolutePath: '/repo/.agents/skills/demo',
+ sourceKey: 'agents-source',
+ requiresSourceKey: true,
+ });
+ const search = new URL(route, 'https://cindy.local').searchParams;
+
+ expect(route).toBe(
+ '/skillhub/local/skill/project/abcd1234/demo?engine=pi&source=pi-source',
+ );
+ expect(findLocalSkillRouteEntry(
+ [addedLater, original],
+ { kind: 'skill', projectHash: 'abcd1234', name: 'demo' },
+ search,
+ )).toBe(original);
+ });
+
+ it('adds a source key and resolves each same-name physical source exactly', () => {
+ const pi = entry({ id: 'pi:demo:pi-source', sourceKey: 'pi-source', requiresSourceKey: true });
+ const agents = entry({
+ id: 'pi:demo:agents-source',
+ absolutePath: '/repo/.agents/skills/demo',
+ sourceKey: 'agents-source',
+ requiresSourceKey: true,
+ });
+ const params = { kind: 'skill', projectHash: 'abcd1234', name: 'demo' };
+
+ expect(buildLocalSkillRoute(pi)).toBe(
+ '/skillhub/local/skill/project/abcd1234/demo?engine=pi&source=pi-source',
+ );
+ expect(
+ findLocalSkillRouteEntry(
+ [agents, pi],
+ params,
+ new URLSearchParams('engine=pi&source=pi-source'),
+ ),
+ ).toBe(pi);
+ expect(
+ findLocalSkillRouteEntry(
+ [pi, agents],
+ params,
+ new URLSearchParams('engine=pi&source=agents-source'),
+ ),
+ ).toBe(agents);
+ expect(
+ findLocalSkillRouteEntry(
+ [pi, agents],
+ params,
+ new URLSearchParams('engine=pi&source=missing'),
+ ),
+ ).toBeNull();
+ });
+
+ it('makes a legacy ambiguous URL fall back independently of discovery order', () => {
+ const first = entry({ absolutePath: '/repo/z/.pi/skills/demo', sourceKey: 'bbbb' });
+ const second = entry({ absolutePath: '/repo/a/.agents/skills/demo', sourceKey: 'aaaa' });
+ const params = { kind: 'skill', projectHash: 'abcd1234', name: 'demo' };
+ const search = new URLSearchParams('engine=pi');
+
+ expect(findLocalSkillRouteEntry([first, second], params, search)).toBe(second);
+ expect(findLocalSkillRouteEntry([second, first], params, search)).toBe(second);
+ });
+
+ it('keeps a source-aware URL valid after its collision shrinks to one survivor', () => {
+ const survivor = entry({
+ engine: 'codex',
+ absolutePath: '/home/.agents/skills/demo',
+ sourceKey: undefined,
+ requiresSourceKey: undefined,
+ });
+
+ expect(findLocalSkillRouteEntry(
+ [survivor],
+ { kind: 'skill', projectHash: 'abcd1234', name: 'demo' },
+ new URLSearchParams('engine=codex&source=removed-source'),
+ )).toBe(survivor);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/publishProgressFilter.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/publishProgressFilter.test.ts
index 3a1ded1835..b8a482dcec 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/publishProgressFilter.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/publishProgressFilter.test.ts
@@ -27,4 +27,12 @@ describe('publish progress event filter', () => {
expect(scanningCloseBranch).toContain("dispatch({ type: 'CLOSE' });");
expect(scanningCloseBranch).not.toContain('stopScanPoll');
});
+
+ it('preserves the lexical discovery path for rename safety checks', () => {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const source = readFileSync(resolve(here, '../../PublishDialog.tsx'), 'utf8')
+ .replace(/\r\n/g, '\n');
+
+ expect(source).toContain('absolutePath: skill.discoveredPath ?? eff.absolutePath');
+ });
});
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts b/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts
new file mode 100644
index 0000000000..7386df62f4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts
@@ -0,0 +1,78 @@
+interface LocalSkillRouteEntry {
+ id: string;
+ engine: 'claude-code' | 'codex' | 'pi';
+ kind: SkillhubKind;
+ scope: SkillhubScope;
+ name: string;
+ absolutePath: string;
+ discoveredPath?: string;
+ projectHash?: string;
+ sourceKey?: string;
+ requiresSourceKey?: boolean;
+}
+
+export function findLocalSkillByPath<T extends LocalSkillRouteEntry>(
+ skills: readonly T[],
+ targetPath: string,
+): T | null {
+ return skills.find(
+ (skill) => skill.absolutePath === targetPath || skill.discoveredPath === targetPath,
+ ) ?? null;
+}
+
+interface LocalSkillRouteParams {
+ kind?: string;
+ projectHash?: string;
+ name?: string;
+}
+
+/** Builds a local detail URL while preserving the legacy pathname contract. */
+export function buildLocalSkillRoute(entry: LocalSkillRouteEntry): string {
+ const name = encodeURIComponent(entry.name);
+ const pathname =
+ entry.scope === 'global'
+ ? `/skillhub/local/${entry.kind}/global/${name}`
+ : `/skillhub/local/${entry.kind}/project/${entry.projectHash}/${name}`;
+ const search = new URLSearchParams({ engine: entry.engine });
+ if (entry.sourceKey) search.set('source', entry.sourceKey);
+ return `${pathname}?${search.toString()}`;
+}
+
+/** Resolves both source-aware links and legacy links that predate source keys. */
+export function findLocalSkillRouteEntry<T extends LocalSkillRouteEntry>(
+ skills: readonly T[],
+ params: LocalSkillRouteParams,
+ searchParams: Pick<URLSearchParams, 'get'>,
+): T | null {
+ const { kind, projectHash, name } = params;
+ if (!kind || !name) return null;
+ const decodedName = decodeURIComponent(name);
+ const engine = searchParams.get('engine');
+ const source = searchParams.get('source');
+ const matches = skills.filter(
+ (skill) =>
+ skill.kind === kind &&
+ skill.scope === (projectHash ? 'project' : 'global') &&
+ (!projectHash || skill.projectHash === projectHash) &&
+ skill.name === decodedName &&
+ (!engine || skill.engine === engine),
+ );
+ if (source) {
+ const exact = matches.find((skill) => skill.sourceKey === source);
+ if (exact) return exact;
+ // A source-aware URL may outlive the collision that created it. Once only
+ // one physical source remains, that survivor is unambiguous even if older
+ // scanners omitted its no-longer-required sourceKey.
+ return matches.length === 1 ? matches[0] : null;
+ }
+
+ // Old URLs cannot identify a physical source. Keep their fallback stable even
+ // if an agent changes discovery order between scans.
+ return (
+ matches.toSorted(
+ (left, right) =>
+ (left.sourceKey ?? '').localeCompare(right.sourceKey ?? '') ||
+ left.absolutePath.localeCompare(right.absolutePath),
+ )[0] ?? null
+ );
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 79b64d3002..59f2614ced 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7933,6 +7933,9 @@
"deny": "Deny"
}
},
+ "commandPalette": {
+ "projectTrustRequired": "Available after you trust this project"
+ },
"skillhub": {
"home": {
"title": "Skills",
@@ -7960,7 +7963,12 @@
},
"common": {
"openFolderFailed": "Failed to open folder",
- "close": "Close"
+ "close": "Close",
+ "statusDiscovered": "Discovered",
+ "statusApproved": "Approved",
+ "statusLoaded": "Loaded",
+ "statusFailed": "Load failed",
+ "statusUnknown": "Unknown"
},
"welcome": {
"scanning": "Scanning local skills…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 95c90070bd..337ff66636 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7920,6 +7920,9 @@
"deny": "拒否"
}
},
+ "commandPalette": {
+ "projectTrustRequired": "このプロジェクトを信頼すると使用できます"
+ },
"skillhub": {
"home": {
"title": "スキル",
@@ -7947,7 +7950,12 @@
},
"common": {
"openFolderFailed": "フォルダを開けませんでした",
- "close": "閉じる"
+ "close": "閉じる",
+ "statusDiscovered": "検出済み",
+ "statusApproved": "承認済み",
+ "statusLoaded": "読み込み済み",
+ "statusFailed": "読み込み失敗",
+ "statusUnknown": "不明"
},
"welcome": {
"scanning": "ローカルの skill をスキャン中…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 8403014ea5..fe6208207d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7920,6 +7920,9 @@
"deny": "거부"
}
},
+ "commandPalette": {
+ "projectTrustRequired": "이 프로젝트를 신뢰하면 사용할 수 있습니다"
+ },
"skillhub": {
"home": {
"title": "스킬",
@@ -7947,7 +7950,12 @@
},
"common": {
"openFolderFailed": "폴더 열기 실패",
- "close": "닫기"
+ "close": "닫기",
+ "statusDiscovered": "발견됨",
+ "statusApproved": "승인됨",
+ "statusLoaded": "로드됨",
+ "statusFailed": "로드 실패",
+ "statusUnknown": "알 수 없음"
},
"welcome": {
"scanning": "로컬 skill 스캔 중…",
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 227ec6d157..1f85d9baa0 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7920,6 +7920,9 @@
"deny": "拒绝"
}
},
+ "commandPalette": {
+ "projectTrustRequired": "需要信任此项目后可用"
+ },
"skillhub": {
"home": {
"title": "技能",
@@ -7947,7 +7950,12 @@
},
"common": {
"openFolderFailed": "打开文件夹失败",
- "close": "关闭"
+ "close": "关闭",
+ "statusDiscovered": "已发现",
+ "statusApproved": "已批准",
+ "statusLoaded": "已加载",
+ "statusFailed": "加载失败",
+ "statusUnknown": "未知"
},
"welcome": {
"scanning": "正在扫描本地 Skill…",
diff --git a/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts b/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts
index 7ce4d94e15..6e783e4233 100644
--- a/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts
@@ -1,6 +1,78 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
-import { filterSlashCommands } from '@/lib/slashCommands';
+import {
+ filterSlashCommands,
+ firstAvailableSlashCommandIndex,
+ hasAvailableSlashCommand,
+ hasUnavailableProjectSkillPreview,
+ isSlashCommandUnavailable,
+ mergeCommands,
+ nextAvailableSlashCommandIndex,
+ rebaseInlineRangesAfterSlashCommandRewrite,
+ reconcilePiRuntimeCommandForDispatch,
+ reconcilePiRuntimeCommandForDispatchWithRetry,
+ rewriteAgentSkillInvocationForDispatch,
+ slashCommandInvocationName,
+ type UnifiedCommand,
+} from '@/lib/slashCommands';
+
+const skill = (overrides: Partial<Extract<UnifiedCommand, { kind: 'agent-skill' }>> = {}) => ({
+ kind: 'agent-skill' as const,
+ name: 'demo',
+ source: 'skill' as const,
+ ...overrides,
+});
+
+describe('rewriteAgentSkillInvocationForDispatch', () => {
+ it('rewrites a directly typed loaded Pi skill alias and preserves its arguments', () => {
+ const loaded = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:demo',
+ });
+
+ expect(rewriteAgentSkillInvocationForDispatch('/demo keep spacing', loaded)).toBe(
+ '/skill:demo keep spacing',
+ );
+ });
+
+ it('rebases command and later inline metadata when the runtime alias grows', () => {
+ const original = '/demo @task pasted';
+ const rewritten = '/skill:demo @task pasted';
+
+ expect(rebaseInlineRangesAfterSlashCommandRewrite(
+ [
+ { start: 0, end: 5, kind: 'slash' },
+ { start: 6, end: 11, kind: 'reference' },
+ { start: 12, end: 18, kind: 'paste' },
+ ],
+ original,
+ rewritten,
+ )).toEqual([
+ { start: 0, end: 11, kind: 'slash' },
+ { start: 12, end: 17, kind: 'reference' },
+ { start: 18, end: 24, kind: 'paste' },
+ ]);
+ });
+
+ it('does not rewrite unavailable, mismatched, or non-skill commands', () => {
+ const discovered = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'discovered',
+ runtimeCommandName: 'skill:demo',
+ });
+ const desktop: UnifiedCommand = { kind: 'desktop', name: 'demo', description: 'Demo' };
+
+ expect(rewriteAgentSkillInvocationForDispatch('/demo', discovered)).toBe('/demo');
+ expect(rewriteAgentSkillInvocationForDispatch('/other', {
+ ...discovered,
+ runtimeStatus: 'loaded',
+ })).toBe('/other');
+ expect(rewriteAgentSkillInvocationForDispatch('/demo', desktop)).toBe('/demo');
+ });
+});
describe('filterSlashCommands', () => {
it('matches command names by case-insensitive containment', () => {
@@ -47,3 +119,331 @@ describe('filterSlashCommands', () => {
).toContain('drive');
});
});
+
+describe('Pi project skill availability', () => {
+ it('does not apply Pi runtime retry delays to non-Pi sessions', async () => {
+ const sleeps: number[] = [];
+ const reload = vi.fn(async () => [] as UnifiedCommand[]);
+
+ await expect(reconcilePiRuntimeCommandForDispatchWithRetry({
+ agentKind: 'codex',
+ sessionId: 'session-1',
+ commandName: 'missing',
+ commands: [],
+ retryDelaysMs: [10, 20],
+ sleep: async (delayMs) => { sleeps.push(delayMs); },
+ reload,
+ })).resolves.toEqual({ command: undefined, commands: [] });
+ expect(sleeps).toEqual([]);
+ expect(reload).not.toHaveBeenCalled();
+ });
+
+ it('does not retry a Pi slash name absent from the refreshed filesystem catalog', async () => {
+ const sleeps: number[] = [];
+ const reload = vi.fn(async () => [] as UnifiedCommand[]);
+
+ await expect(reconcilePiRuntimeCommandForDispatchWithRetry({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'missing',
+ commands: [],
+ retryDelaysMs: [10, 20],
+ sleep: async (delayMs) => { sleeps.push(delayMs); },
+ reload,
+ })).resolves.toEqual({ command: undefined, commands: [] });
+ expect(sleeps).toEqual([]);
+ expect(reload).toHaveBeenCalledTimes(1);
+ });
+
+ it('disables only discovered project skills', () => {
+ expect(isSlashCommandUnavailable(skill({ scope: 'repo', runtimeStatus: 'discovered' }))).toBe(true);
+ expect(isSlashCommandUnavailable(skill({ scope: 'repo', runtimeStatus: 'loaded' }))).toBe(false);
+ expect(isSlashCommandUnavailable(skill({ scope: 'user', runtimeStatus: 'discovered' }))).toBe(false);
+ expect(isSlashCommandUnavailable(skill({ scope: 'repo' }))).toBe(false);
+ });
+
+ it('keeps the palette label while invoking Pi skills by their runtime command name', () => {
+ const loaded = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:demo',
+ });
+
+ expect(loaded.name).toBe('demo');
+ expect(slashCommandInvocationName(loaded)).toBe('skill:demo');
+ expect(slashCommandInvocationName({ kind: 'desktop', name: 'help', description: 'Help' })).toBe('help');
+ });
+
+ it('keeps an available same-name skill ahead of a discovered project preview', () => {
+ const discovered = skill({ scope: 'repo', runtimeStatus: 'discovered', path: '/repo/.pi/skills/demo' });
+ const available = skill({ scope: 'user', path: '/home/user/.agents/skills/demo' });
+
+ expect(mergeCommands([], [], [discovered, available])).toEqual([available]);
+ });
+
+ it('does not let a discovered preview shadow same-name executable tiers', () => {
+ const discovered = skill({ name: 'help', scope: 'repo', runtimeStatus: 'discovered' });
+ const desktop: UnifiedCommand = {
+ kind: 'desktop',
+ name: 'help',
+ description: 'Open help',
+ };
+
+ expect(mergeCommands([desktop], [], [discovered])).toEqual([desktop]);
+ });
+
+ it('keeps hidden discovered collisions visible to Pi palette polling', () => {
+ const discovered = skill({ name: 'help', scope: 'repo', runtimeStatus: 'discovered' });
+ const desktop: UnifiedCommand = {
+ kind: 'desktop',
+ name: 'help',
+ description: 'Open help',
+ };
+
+ const commands = mergeCommands([desktop], [], [discovered]);
+
+ expect(commands).toEqual([desktop]);
+ expect(hasUnavailableProjectSkillPreview(commands)).toBe(true);
+ expect(hasUnavailableProjectSkillPreview([desktop])).toBe(false);
+ });
+
+ it('initializes and moves keyboard focus past unavailable project skills', () => {
+ const commands = [
+ skill({ name: 'first', scope: 'repo', runtimeStatus: 'discovered' }),
+ skill({ name: 'second', scope: 'user' }),
+ skill({ name: 'third', scope: 'repo', runtimeStatus: 'discovered' }),
+ skill({ name: 'fourth', scope: 'user' }),
+ ];
+
+ expect(firstAvailableSlashCommandIndex(commands)).toBe(1);
+ expect(nextAvailableSlashCommandIndex(commands, 1, 1)).toBe(3);
+ expect(nextAvailableSlashCommandIndex(commands, 3, 1)).toBe(1);
+ expect(nextAvailableSlashCommandIndex(commands, 1, -1)).toBe(3);
+ });
+
+ it('keeps focus stable when every matching command is unavailable', () => {
+ const commands = [
+ skill({ name: 'first', scope: 'repo', runtimeStatus: 'discovered' }),
+ skill({ name: 'second', scope: 'repo', runtimeStatus: 'discovered' }),
+ ];
+
+ expect(firstAvailableSlashCommandIndex(commands)).toBe(0);
+ expect(nextAvailableSlashCommandIndex(commands, 0, 1)).toBe(0);
+ expect(hasAvailableSlashCommand(commands)).toBe(false);
+ });
+
+ it('refreshes a Pi desktop hit before dispatch so a loaded same-name skill wins', async () => {
+ const desktop: UnifiedCommand = { kind: 'desktop', name: 'help', description: 'Help' };
+ const loaded = skill({ name: 'help', scope: 'repo', runtimeStatus: 'loaded' });
+
+ await expect(reconcilePiRuntimeCommandForDispatch({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'help',
+ commands: [desktop],
+ reload: async () => [loaded],
+ })).resolves.toEqual({ command: loaded, commands: [loaded] });
+ });
+
+ it('refreshes a stale discovered Pi skill before rewriting a typed alias', async () => {
+ const discovered = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'discovered',
+ });
+ const loaded = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:demo',
+ });
+
+ await expect(reconcilePiRuntimeCommandForDispatch({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'demo',
+ commands: [discovered],
+ reload: async () => [loaded],
+ })).resolves.toEqual({ command: loaded, commands: [loaded] });
+ });
+
+ it('waits for a transient discovered Pi skill to enter the runtime catalog', async () => {
+ const discovered = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'discovered',
+ });
+ const loaded = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:demo',
+ });
+ const sleeps: number[] = [];
+ let reloads = 0;
+
+ await expect(reconcilePiRuntimeCommandForDispatchWithRetry({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'demo',
+ commands: [discovered],
+ retryDelaysMs: [10, 20, 30],
+ sleep: async (delayMs) => { sleeps.push(delayMs); },
+ reload: async () => (++reloads < 3 ? [discovered] : [loaded]),
+ })).resolves.toEqual({ command: loaded, commands: [loaded] });
+ expect(sleeps).toEqual([10, 20]);
+ expect(reloads).toBe(3);
+ });
+
+ it('keeps waiting when a Desktop command temporarily shadows a same-name Pi skill', async () => {
+ const desktop: UnifiedCommand = { kind: 'desktop', name: 'help', description: 'Help' };
+ const discovered = skill({ name: 'help', scope: 'repo', runtimeStatus: 'discovered' });
+ const loaded = skill({
+ name: 'help',
+ scope: 'repo',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:help',
+ });
+ const sleeps: number[] = [];
+ let reloads = 0;
+ const initial = mergeCommands([desktop], [], [discovered]);
+
+ await expect(reconcilePiRuntimeCommandForDispatchWithRetry({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'help',
+ commands: initial,
+ retryDelaysMs: [10, 20, 30],
+ sleep: async (delayMs) => { sleeps.push(delayMs); },
+ reload: async () => (
+ ++reloads < 3
+ ? mergeCommands([desktop], [], [discovered])
+ : mergeCommands([desktop], [], [loaded])
+ ),
+ })).resolves.toEqual({ command: loaded, commands: [loaded] });
+ expect(sleeps).toEqual([10, 20]);
+ expect(reloads).toBe(3);
+ });
+
+ it('starts the selected project runtime before resolving its first Pi skill command', async () => {
+ const discovered = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'discovered',
+ });
+ const loaded = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:demo',
+ });
+ const events: string[] = [];
+ let runtimeReady = false;
+
+ await expect(reconcilePiRuntimeCommandForDispatchWithRetry({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'demo',
+ commands: [],
+ retryDelaysMs: [],
+ prepareRuntime: async () => {
+ events.push('runtime');
+ runtimeReady = true;
+ },
+ reload: async () => {
+ events.push('catalog');
+ return runtimeReady ? [loaded] : [discovered];
+ },
+ })).resolves.toEqual({ command: loaded, commands: [loaded] });
+ expect(events).toEqual(['runtime', 'catalog']);
+ });
+
+ it('does not restart the runtime for an already loaded Pi skill', async () => {
+ const loaded = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:demo',
+ });
+ let prepared = false;
+
+ await expect(reconcilePiRuntimeCommandForDispatchWithRetry({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'demo',
+ commands: [loaded],
+ prepareRuntime: async () => { prepared = true; },
+ reload: async () => [],
+ })).resolves.toEqual({ command: loaded, commands: [loaded] });
+ expect(prepared).toBe(false);
+ });
+
+ it('refreshes an unknown Pi alias in case the runtime catalog arrived late', async () => {
+ const loaded = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:demo',
+ });
+
+ await expect(reconcilePiRuntimeCommandForDispatch({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'demo',
+ commands: [],
+ reload: async () => [loaded],
+ })).resolves.toEqual({ command: loaded, commands: [loaded] });
+ });
+
+ it('does not refresh an already available Pi skill', async () => {
+ const loaded = skill({
+ name: 'demo',
+ scope: 'repo',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:demo',
+ });
+ let reloaded = false;
+
+ await expect(reconcilePiRuntimeCommandForDispatch({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'demo',
+ commands: [loaded],
+ reload: async () => {
+ reloaded = true;
+ return [];
+ },
+ })).resolves.toEqual({ command: loaded, commands: [loaded] });
+ expect(reloaded).toBe(false);
+ });
+
+ it('keeps the cached command when a best-effort refresh has no matching result', async () => {
+ const desktop: UnifiedCommand = { kind: 'desktop', name: 'help', description: 'Help' };
+
+ await expect(reconcilePiRuntimeCommandForDispatch({
+ agentKind: 'pi',
+ sessionId: 'session-1',
+ commandName: 'help',
+ commands: [desktop],
+ reload: async () => [],
+ })).resolves.toEqual({ command: desktop, commands: [desktop] });
+ });
+
+ it('does not refresh a non-Pi desktop hit', async () => {
+ const desktop: UnifiedCommand = { kind: 'desktop', name: 'help', description: 'Help' };
+ let reloaded = false;
+
+ await expect(reconcilePiRuntimeCommandForDispatch({
+ agentKind: 'claude-code',
+ sessionId: 'session-1',
+ commandName: 'help',
+ commands: [desktop],
+ reload: async () => {
+ reloaded = true;
+ return [];
+ },
+ })).resolves.toEqual({ command: desktop, commands: [desktop] });
+ expect(reloaded).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 16db4cc58c..1681825fb9 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -10799,7 +10799,7 @@ function extractSessionRefs(
return reconcileSessionRefsForText(text, previous, getStickySessionDeviceId);
}
-function buildCreateOptsForCurrentSession(
+export function buildCreateOptsForCurrentSession(
sessionId: string,
model: string,
effort: string,
diff --git a/apps/desktop/src/renderer/lib/slashCommands.ts b/apps/desktop/src/renderer/lib/slashCommands.ts
index a7c946b2db..4143afe532 100644
--- a/apps/desktop/src/renderer/lib/slashCommands.ts
+++ b/apps/desktop/src/renderer/lib/slashCommands.ts
@@ -21,9 +21,94 @@ import type { UnifiedCommand, AgentKind } from '@cindy/maker-core';
import { createLogger } from '@/lib/logger';
const log = createLogger('SlashCommands');
+const shadowedUnavailableSkillsByCommands = new WeakMap<UnifiedCommand[], Set<string>>();
export type { UnifiedCommand } from '@cindy/maker-core';
+export const PI_RUNTIME_SKILL_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000, 4_000] as const;
+
+export function isSlashCommandUnavailable(command: UnifiedCommand): boolean {
+ return command.kind === 'agent-skill'
+ && command.scope === 'repo'
+ && command.runtimeStatus === 'discovered';
+}
+
+export function hasAvailableSlashCommand(commands: readonly UnifiedCommand[]): boolean {
+ return commands.some((command) => !isSlashCommandUnavailable(command));
+}
+
+export function slashCommandInvocationName(command: UnifiedCommand): string {
+ return command.kind === 'agent-skill' && command.runtimeCommandName
+ ? command.runtimeCommandName
+ : command.name;
+}
+
+/**
+ * Palette selection already inserts runtimeCommandName. Apply the same mapping
+ * to a matching command that the user typed or pasted directly before send.
+ */
+export function rewriteAgentSkillInvocationForDispatch(
+ message: string,
+ command: UnifiedCommand | undefined,
+): string {
+ if (
+ !command ||
+ command.kind !== 'agent-skill' ||
+ !command.runtimeCommandName ||
+ isSlashCommandUnavailable(command)
+ ) {
+ return message;
+ }
+ const match = message.match(/^\/(\S+)([\s\S]*)$/);
+ if (!match || match[1].toLowerCase() !== command.name.toLowerCase()) return message;
+ return `/${command.runtimeCommandName}${match[2]}`;
+}
+
+/**
+ * Rebase persisted/render-only inline ranges after the leading slash-command
+ * token grows or shrinks during runtime alias rewriting.
+ */
+export function rebaseInlineRangesAfterSlashCommandRewrite<T extends { start: number; end: number }>(
+ ranges: readonly T[],
+ originalMessage: string,
+ rewrittenMessage: string,
+): T[] {
+ if (originalMessage === rewrittenMessage) return [...ranges];
+ const originalCommand = originalMessage.match(/^\/\S+/)?.[0];
+ const rewrittenCommand = rewrittenMessage.match(/^\/\S+/)?.[0];
+ if (!originalCommand || !rewrittenCommand) return [...ranges];
+
+ const boundary = originalCommand.length;
+ const delta = rewrittenCommand.length - boundary;
+ if (delta === 0) return [...ranges];
+ return ranges.map((range) => ({
+ ...range,
+ start: range.start >= boundary ? range.start + delta : range.start,
+ end: range.end >= boundary ? range.end + delta : range.end,
+ }));
+}
+
+/** First available command index, or 0 when nothing is available/present. */
+export function firstAvailableSlashCommandIndex(commands: readonly UnifiedCommand[]): number {
+ const index = commands.findIndex((command) => !isSlashCommandUnavailable(command));
+ return index >= 0 ? index : 0;
+}
+
+/** Move with wraparound while skipping unavailable discovered project skills. */
+export function nextAvailableSlashCommandIndex(
+ commands: readonly UnifiedCommand[],
+ current: number,
+ delta: 1 | -1,
+): number {
+ if (commands.length === 0) return current;
+ let index = current;
+ for (let step = 0; step < commands.length; step++) {
+ index = (index + delta + commands.length) % commands.length;
+ if (!isSlashCommandUnavailable(commands[index])) return index;
+ }
+ return current;
+}
+
export type SlashCommandRosterStatus = 'loading' | 'refreshing' | 'ready' | 'error';
export interface SlashCommandRosterState {
@@ -92,24 +177,47 @@ export function mergeCommands(
): UnifiedCommand[] {
const seen = new Set<string>();
const result: UnifiedCommand[] = [];
+ const shadowedUnavailableSkills = new Set<string>();
+ const availableSkills = agentSkill.filter((command) => !isSlashCommandUnavailable(command));
+ const unavailableSkills = agentSkill.filter(isSlashCommandUnavailable);
const tiers: UnifiedCommand[][] = [
- [...agentSkill].sort((a, b) => a.name.localeCompare(b.name)),
+ availableSkills.sort((a, b) => a.name.localeCompare(b.name)),
[...desktop].sort((a, b) => a.name.localeCompare(b.name)),
[...agentBuiltin].sort((a, b) => a.name.localeCompare(b.name)),
+ unavailableSkills.sort((a, b) => a.name.localeCompare(b.name)),
];
for (const tier of tiers) {
for (const cmd of tier) {
if (seen.has(cmd.name)) {
- log.warn(`Slash command "/${cmd.name}" already provided by higher-priority tier; skipping ${cmd.kind}.`);
+ if (isSlashCommandUnavailable(cmd)) {
+ shadowedUnavailableSkills.add(cmd.name.toLowerCase());
+ } else {
+ log.warn(`Slash command "/${cmd.name}" already provided by higher-priority tier; skipping ${cmd.kind}.`);
+ }
continue;
}
seen.add(cmd.name);
result.push(cmd);
}
}
+ if (shadowedUnavailableSkills.size > 0) {
+ shadowedUnavailableSkillsByCommands.set(result, shadowedUnavailableSkills);
+ }
return result;
}
+function hasShadowedUnavailableSkill(
+ commands: UnifiedCommand[],
+ commandName: string,
+): boolean {
+ return shadowedUnavailableSkillsByCommands.get(commands)?.has(commandName.toLowerCase()) ?? false;
+}
+
+export function hasUnavailableProjectSkillPreview(commands: UnifiedCommand[]): boolean {
+ return commands.some(isSlashCommandUnavailable)
+ || (shadowedUnavailableSkillsByCommands.get(commands)?.size ?? 0) > 0;
+}
+
/**
* 包含过滤(case-insensitive); 精确匹配优先,其次是前缀匹配,最后是普通包含匹配。
*
@@ -146,7 +254,7 @@ export function filterSlashCommands(
export async function loadAllCommands(
agentKind: AgentKind,
workingDir: string | null | undefined,
- opts?: { forceReload?: boolean; skipAgentSkills?: boolean },
+ opts?: { forceReload?: boolean; skipAgentSkills?: boolean; sessionId?: string },
deviceId?: string,
): Promise<UnifiedCommand[]> {
const api = window.electronAPI.maker;
@@ -168,6 +276,7 @@ export async function loadAllCommands(
const skillParams = {
...(workingDir ? { workingDir } : {}),
...(opts?.forceReload !== undefined ? { forceReload: opts.forceReload } : {}),
+ ...(opts?.sessionId ? { sessionId: opts.sessionId } : {}),
};
const skillP: Promise<SkillRes> = shouldLoadSkills
? (
@@ -188,6 +297,89 @@ export async function loadAllCommands(
return mergeCommands(desktop, agentBuiltin, agentSkill);
}
+/**
+ * A Pi runtime catalog may finish after the palette/dispatch snapshot was
+ * created. Recheck desktop hits before executing them so a newly loaded
+ * same-name project skill keeps command ownership.
+ */
+export async function reconcilePiRuntimeCommandForDispatch(params: {
+ agentKind: AgentKind;
+ sessionId?: string;
+ commandName: string;
+ commands: UnifiedCommand[];
+ reload: () => Promise<UnifiedCommand[]>;
+}): Promise<{ command: UnifiedCommand | undefined; commands: UnifiedCommand[] }> {
+ const findCommand = (commands: UnifiedCommand[]) => commands.find(
+ (command) => command.name.toLowerCase() === params.commandName.toLowerCase(),
+ );
+ const current = findCommand(params.commands);
+ const shouldReload = !current
+ || current.kind === 'desktop'
+ || isSlashCommandUnavailable(current);
+ if (params.agentKind !== 'pi' || !params.sessionId || !shouldReload) {
+ return { command: current, commands: params.commands };
+ }
+ try {
+ const refreshed = await params.reload();
+ const refreshedCommand = findCommand(refreshed);
+ return refreshedCommand || !current
+ ? { command: refreshedCommand, commands: refreshed }
+ : { command: current, commands: params.commands };
+ } catch {
+ return { command: current, commands: params.commands };
+ }
+}
+
+export async function reconcilePiRuntimeCommandForDispatchWithRetry(params: {
+ agentKind: AgentKind;
+ sessionId?: string;
+ commandName: string;
+ commands: UnifiedCommand[];
+ reload: () => Promise<UnifiedCommand[]>;
+ prepareRuntime?: () => Promise<void>;
+ retryDelaysMs?: readonly number[];
+ sleep?: (delayMs: number) => Promise<void>;
+}): Promise<{ command: UnifiedCommand | undefined; commands: UnifiedCommand[] }> {
+ if (params.agentKind !== 'pi' || !params.sessionId) {
+ return reconcilePiRuntimeCommandForDispatch(params);
+ }
+ const retryDelaysMs = params.retryDelaysMs ?? PI_RUNTIME_SKILL_RETRY_DELAYS_MS;
+ const sleep = params.sleep ?? ((delayMs: number) => new Promise<void>(
+ (resolve) => window.setTimeout(resolve, delayMs),
+ ));
+ const current = params.commands.find(
+ (command) => command.name.toLowerCase() === params.commandName.toLowerCase(),
+ );
+ const shouldPrepareRuntime = !current
+ || current.kind === 'desktop'
+ || isSlashCommandUnavailable(current);
+ if (
+ params.agentKind === 'pi'
+ && params.sessionId
+ && params.prepareRuntime
+ && shouldPrepareRuntime
+ ) {
+ await params.prepareRuntime();
+ }
+ let result = await reconcilePiRuntimeCommandForDispatch(params);
+ for (const delayMs of retryDelaysMs) {
+ const shouldRetry = result.command !== undefined && (
+ isSlashCommandUnavailable(result.command)
+ || (
+ result.command.kind === 'desktop'
+ && hasShadowedUnavailableSkill(result.commands, params.commandName)
+ )
+ );
+ if (!shouldRetry) return result;
+ await sleep(delayMs);
+ result = await reconcilePiRuntimeCommandForDispatch({
+ ...params,
+ commands: result.commands,
+ });
+ }
+ return result;
+}
+
/**
* Dispatch context —— 调用方(handleSend)透传 session 上下文给 main。
* desktop 命令的 execute 拿到这些信息决定怎么响应。
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index c772c3d0d7..4146b035a4 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4677,7 +4677,7 @@ interface ElectronAPI {
listAgentSkills: (
agentKind: 'claude-code' | 'codex' | 'pi',
- params: { workingDir?: string; forceReload?: boolean },
+ params: { workingDir?: string; forceReload?: boolean; sessionId?: string },
) => Promise<{
success: boolean;
error?: string;
@@ -4689,6 +4689,8 @@ interface ElectronAPI {
path?: string;
scope?: string;
enabled?: boolean;
+ runtimeStatus?: 'discovered' | 'approved' | 'loaded' | 'failed' | 'unknown';
+ runtimeCommandName?: string;
}>;
}>;
@@ -5840,15 +5842,25 @@ interface SkillhubSkill {
id: string;
/** URL 匹配键 — 不含 engine,和路由格式一致,用于侧栏选中高亮。 */
urlKey: string;
+ /** Pi customization 的 canonical physical source hash;Pi 条目始终提供。 */
+ sourceKey?: string;
+ /** 同一 URL 基键存在多个来源时,详情路由必须携带 sourceKey。 */
+ requiresSourceKey?: boolean;
/** 来自哪个 agent 引擎。 */
engine: 'claude-code' | 'codex' | 'pi';
/** 发现该 skill 的所有引擎专属路径(去重后)。 */
- linkedEngines: Array<{ engine: 'claude-code' | 'codex' | 'pi'; label: string }>;
+ linkedEngines: Array<{
+ engine: 'claude-code' | 'codex' | 'pi';
+ label: string;
+ runtimeStatus?: 'discovered' | 'approved' | 'loaded' | 'failed' | 'unknown';
+ }>;
kind: SkillhubKind;
scope: SkillhubScope;
name: string;
description?: string;
absolutePath: string;
+ /** Lexical path reported by discovery before canonical realpath deduplication. */
+ discoveredPath?: string;
mdPath: string;
files: SkillhubFileEntry[];
frontmatter?: Record<string, unknown>;
diff --git a/packages/maker-core/src/agents/pi/__tests__/customization-scanner.test.ts b/packages/maker-core/src/agents/pi/__tests__/customization-scanner.test.ts
new file mode 100644
index 0000000000..9f0d06cb70
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/customization-scanner.test.ts
@@ -0,0 +1,325 @@
+import fs from 'node:fs';
+import { homedir, tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { isCustomizationPathInside } from '../../shared/customization-scanner.js';
+import { buildPiSources, scanPiCustomizations } from '../customization-scanner.js';
+
+const { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } = fs;
+
+const roots: string[] = [];
+
+function canCreateSymlink(kind: 'dir' | 'file'): boolean {
+ const probe = mkdtempSync(path.join(tmpdir(), `pi-customization-${kind}-link-probe-`));
+ try {
+ const target = path.join(probe, `target-${kind}`);
+ if (kind === 'dir') mkdirSync(target);
+ else writeFileSync(target, 'probe');
+ symlinkSync(
+ target,
+ path.join(probe, `link-${kind}`),
+ process.platform === 'win32' && kind === 'dir' ? 'junction' : kind,
+ );
+ return true;
+ } catch {
+ return false;
+ } finally {
+ rmSync(probe, { recursive: true, force: true });
+ }
+}
+
+const canLinkDirectory = canCreateSymlink('dir');
+const canLinkFile = canCreateSymlink('file');
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function tempRoot(): string {
+ const root = mkdtempSync(path.join(tmpdir(), 'pi-customizations-'));
+ roots.push(root);
+ return root;
+}
+
+function writeSkill(root: string, relativeDir: string, name: string): string {
+ const skillDir = path.join(root, relativeDir, name);
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(
+ path.join(skillDir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: ${name} description\n---\n# ${name}\n`,
+ );
+ return skillDir;
+}
+
+function canonical(value: string): string {
+ try {
+ return realpathSync(value);
+ } catch {
+ return path.resolve(value);
+ }
+}
+
+function projectItems(result: Awaited<ReturnType<typeof scanPiCustomizations>>) {
+ return result.items.filter((item) => item.scope === 'repo');
+}
+
+describe('scanPiCustomizations', () => {
+ it('uses Windows path semantics for drive and UNC containment', () => {
+ expect(isCustomizationPathInside(
+ 'C:\\Repo',
+ 'c:\\repo\\.pi\\skills\\demo',
+ path.win32,
+ )).toBe(true);
+ expect(isCustomizationPathInside(
+ 'C:\\Repo',
+ 'D:\\Repo\\.pi\\skills\\demo',
+ path.win32,
+ )).toBe(false);
+ expect(isCustomizationPathInside(
+ '\\\\server\\share\\repo',
+ '\\\\server\\share\\repo\\.pi\\skills\\demo',
+ path.win32,
+ )).toBe(true);
+ expect(isCustomizationPathInside(
+ '\\\\server\\share\\repo',
+ '\\\\server\\other\\repo\\.pi\\skills\\demo',
+ path.win32,
+ )).toBe(false);
+ });
+
+ it('keeps only the shared user skill root', () => {
+ const userSources = buildPiSources([]).filter((source) => source.scope === 'user');
+
+ expect(userSources.map((source) => source.dir)).toEqual([
+ path.join(homedir(), '.agents', 'skills'),
+ ]);
+ expect(userSources.some((source) => source.dir.includes(path.join('.pi', 'agent')))).toBe(false);
+ });
+
+ it('discovers .pi/skills and .agents/skills through the nearest Git root', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ const cwd = path.join(repo, 'packages', 'app');
+ mkdirSync(path.join(repo, '.git'), { recursive: true });
+ mkdirSync(cwd, { recursive: true });
+ const piSkill = writeSkill(cwd, path.join('.pi', 'skills'), 'pi-project');
+ const localShared = writeSkill(cwd, path.join('.agents', 'skills'), 'local-shared');
+ const ancestorShared = writeSkill(repo, path.join('.agents', 'skills'), 'ancestor-shared');
+ writeSkill(root, path.join('.agents', 'skills'), 'above-repo');
+ writeSkill(cwd, path.join('.pi', 'agent', 'skills'), 'legacy-path');
+
+ const result = await scanPiCustomizations({ workingDirs: [cwd] });
+ const items = projectItems(result);
+
+ expect(items.map((item) => canonical(item.absolutePath))).toEqual(expect.arrayContaining([
+ canonical(piSkill),
+ canonical(localShared),
+ canonical(ancestorShared),
+ ]));
+ expect(items.map((item) => item.name)).not.toContain('above-repo');
+ expect(items.map((item) => item.name)).not.toContain('legacy-path');
+ expect(items.every((item) => item.runtimeStatus === 'discovered')).toBe(true);
+ expect(items.every((item) => item.workingDir === path.resolve(cwd))).toBe(true);
+ });
+
+ it('stops ancestor discovery at a nested repository root', async () => {
+ const root = tempRoot();
+ const outer = path.join(root, 'outer');
+ const nested = path.join(outer, 'nested');
+ const cwd = path.join(nested, 'src');
+ mkdirSync(path.join(outer, '.git'), { recursive: true });
+ mkdirSync(path.join(nested, '.git'), { recursive: true });
+ mkdirSync(cwd, { recursive: true });
+ writeSkill(outer, path.join('.agents', 'skills'), 'outer-skill');
+ writeSkill(nested, path.join('.agents', 'skills'), 'nested-skill');
+
+ const result = await scanPiCustomizations({ workingDirs: [cwd] });
+ const names = projectItems(result).map((item) => item.name);
+
+ expect(names).toContain('nested-skill');
+ expect(names).not.toContain('outer-skill');
+ });
+
+ it('treats a worktree-style .git file as the repository boundary', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'worktree');
+ const cwd = path.join(repo, 'src');
+ mkdirSync(cwd, { recursive: true });
+ writeFileSync(path.join(repo, '.git'), 'gitdir: /tmp/example-git-dir\n');
+ writeSkill(repo, path.join('.agents', 'skills'), 'worktree-skill');
+ writeSkill(root, path.join('.agents', 'skills'), 'above-worktree');
+
+ const result = await scanPiCustomizations({ workingDirs: [cwd] });
+ const names = projectItems(result).map((item) => item.name);
+
+ expect(names).toContain('worktree-skill');
+ expect(names).not.toContain('above-worktree');
+ });
+
+ it('treats an unreadable .git marker as a repository boundary', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ const cwd = path.join(repo, 'src');
+ mkdirSync(cwd, { recursive: true });
+ const canonicalRepo = canonical(repo);
+ const canonicalCwd = canonical(cwd);
+ const originalStatSync = fs.statSync;
+ const statSyncSpy = vi.spyOn(fs, 'statSync').mockImplementation((candidate, options) => {
+ if (String(candidate) === path.join(canonicalRepo, '.git')) {
+ throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ }
+ return originalStatSync(candidate, options as never);
+ });
+
+ const projectDirs = buildPiSources([cwd])
+ .filter((source) => source.scope === 'repo')
+ .map((source) => source.dir);
+
+ expect(projectDirs).toEqual([
+ path.join(canonicalCwd, '.pi', 'skills'),
+ path.join(canonicalCwd, '.agents', 'skills'),
+ path.join(canonicalRepo, '.agents', 'skills'),
+ ]);
+ statSyncSpy.mockRestore();
+ });
+
+ it('scans only the working directory .agents path outside Git repositories', async () => {
+ const root = tempRoot();
+ const cwd = path.join(root, 'parent', 'cwd');
+ mkdirSync(cwd, { recursive: true });
+ writeSkill(root, path.join('parent', '.agents', 'skills'), 'parent-skill');
+ writeSkill(cwd, path.join('.agents', 'skills'), 'cwd-skill');
+
+ const result = await scanPiCustomizations({ workingDirs: [cwd] });
+ const names = projectItems(result).map((item) => item.name);
+
+ expect(names).toContain('cwd-skill');
+ expect(names).not.toContain('parent-skill');
+ });
+
+ it('handles a Git root working directory and missing skill directories', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ mkdirSync(path.join(repo, '.git'), { recursive: true });
+ writeSkill(repo, path.join('.agents', 'skills'), 'root-skill');
+
+ const result = await scanPiCustomizations({ workingDirs: [repo] });
+
+ expect(projectItems(result).filter((item) => item.name === 'root-skill')).toHaveLength(1);
+ expect(result.errors).toEqual([]);
+ });
+
+ it('returns an empty project result when every project skill directory is missing', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ const cwd = path.join(repo, 'src');
+ mkdirSync(path.join(repo, '.git'), { recursive: true });
+ mkdirSync(cwd, { recursive: true });
+
+ const result = await scanPiCustomizations({ workingDirs: [cwd] });
+
+ expect(projectItems(result)).toEqual([]);
+ expect(result.errors).toEqual([]);
+ });
+
+ it('does not inherit ancestor skills for a missing working directory', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ const missingCwd = path.join(repo, 'deleted-project');
+ mkdirSync(path.join(repo, '.git'), { recursive: true });
+ writeSkill(repo, path.join('.agents', 'skills'), 'ancestor-skill');
+
+ const result = await scanPiCustomizations({ workingDirs: [missingCwd] });
+
+ expect(projectItems(result)).toEqual([]);
+ expect(result.errors).toEqual([]);
+ });
+
+ it('keeps same-name skills from distinct project sources', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ const cwd = path.join(repo, 'src');
+ mkdirSync(path.join(repo, '.git'), { recursive: true });
+ mkdirSync(cwd, { recursive: true });
+ const first = writeSkill(repo, path.join('.agents', 'skills'), 'duplicate');
+ const second = writeSkill(cwd, path.join('.pi', 'skills'), 'duplicate');
+
+ const result = await scanPiCustomizations({ workingDirs: [cwd] });
+ const duplicates = projectItems(result).filter((item) => item.name === 'duplicate');
+
+ expect(duplicates.map((item) => canonical(item.absolutePath))).toEqual(
+ [canonical(first), canonical(second)].sort(),
+ );
+ });
+
+ it.skipIf(!canLinkDirectory)('rejects project skill folders that resolve outside the repository', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ const outsideSkill = writeSkill(root, 'outside', 'linked-folder');
+ const skillsDir = path.join(repo, '.pi', 'skills');
+ mkdirSync(path.join(repo, '.git'), { recursive: true });
+ mkdirSync(skillsDir, { recursive: true });
+ symlinkSync(
+ outsideSkill,
+ path.join(skillsDir, 'linked-folder'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+
+ const result = await scanPiCustomizations({ workingDirs: [repo] });
+
+ expect(projectItems(result).map((item) => item.name)).not.toContain('linked-folder');
+ expect(result.errors).toEqual([]);
+ });
+
+ it.skipIf(!canLinkFile)('rejects project SKILL.md files that resolve outside the repository', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ const skillDir = path.join(repo, '.pi', 'skills', 'linked-file');
+ const outsideMd = path.join(root, 'outside-SKILL.md');
+ mkdirSync(path.join(repo, '.git'), { recursive: true });
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(outsideMd, '---\ndescription: external description\n---\n# External\n');
+ symlinkSync(outsideMd, path.join(skillDir, 'SKILL.md'));
+
+ const result = await scanPiCustomizations({ workingDirs: [repo] });
+
+ expect(projectItems(result).map((item) => item.name)).not.toContain('linked-file');
+ expect(result.errors).toEqual([]);
+ });
+
+ it.skipIf(process.platform === 'win32')('resolves a symlinked working directory for scanning while preserving its ownership path', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ const physicalCwd = path.join(repo, 'src');
+ const linkedCwd = path.join(root, 'linked-cwd');
+ mkdirSync(path.join(repo, '.git'), { recursive: true });
+ mkdirSync(physicalCwd, { recursive: true });
+ symlinkSync(physicalCwd, linkedCwd, 'dir');
+ writeSkill(repo, path.join('.agents', 'skills'), 'repo-skill');
+
+ const result = await scanPiCustomizations({ workingDirs: [linkedCwd] });
+ const found = projectItems(result).find((item) => item.name === 'repo-skill');
+
+ expect(found?.workingDir).toBe(path.resolve(linkedCwd));
+ expect(canonical(found?.absolutePath ?? '')).toBe(canonical(path.join(repo, '.agents', 'skills', 'repo-skill')));
+ });
+
+ it.skipIf(process.platform === 'win32')('keeps lexical project aliases distinct for the same physical checkout', async () => {
+ const root = tempRoot();
+ const repo = path.join(root, 'repo');
+ const linkedRepo = path.join(root, 'linked-repo');
+ mkdirSync(path.join(repo, '.git'), { recursive: true });
+ symlinkSync(repo, linkedRepo, 'dir');
+ writeSkill(repo, path.join('.pi', 'skills'), 'aliased-skill');
+
+ const items = projectItems(await scanPiCustomizations({ workingDirs: [repo, linkedRepo] }))
+ .filter((item) => item.name === 'aliased-skill');
+
+ expect(items).toHaveLength(2);
+ expect(items.map((item) => item.workingDir).sort()).toEqual([
+ path.resolve(repo),
+ path.resolve(linkedRepo),
+ ].sort());
+ });
+});
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 d463bf3cb0..38ab97f614 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
@@ -25,6 +25,7 @@ import { StringDecoder } from 'node:string_decoder';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, it } from 'vitest';
+import { scanPiCustomizations } from '../customization-scanner.js';
import { capturePiRuntimeCapabilityManifest } from '../runtime-capabilities.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -666,6 +667,33 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts
}]);
});
+ it('scanner superset differs from unapproved runtime only by project trust', async () => {
+ const fixture = await createFixture('pi-rpc-scanner-trust-gap-');
+ const result = await runGetCommands({
+ binaryPath: PI_BINARY,
+ cwd: fixture.workingDir,
+ configHome: fixture.configHome,
+ sessionDir: fixture.sessionDir,
+ approve: false,
+ });
+ const loadedNames = new Set(
+ normalizeSkills(result.commands, fixture)
+ .filter((skill) => skill.scope === 'project')
+ .map((skill) => skill.name),
+ );
+ const scanned = await scanPiCustomizations({ workingDirs: [fixture.workingDir] });
+ const discovered = scanned.items.filter((item) => item.scope === 'repo');
+ const discoveredNames = new Set(discovered.map((item) => `skill:${item.name}`));
+
+ expect([...loadedNames].every((name) => discoveredNames.has(name))).toBe(true);
+ expect([...discoveredNames].filter((name) => !loadedNames.has(name)).sort()).toEqual([
+ 'skill:ancestor-agents-skill',
+ 'skill:project-agents-skill',
+ 'skill:project-pi-skill',
+ ]);
+ expect(discovered.every((item) => item.runtimeStatus === 'discovered')).toBe(true);
+ });
+
it('records project .pi/skills and current/ancestor .agents/skills only with explicit trust', async () => {
const fixture = await createFixture('pi-rpc-trust-');
const result = await runGetCommands({
@@ -676,6 +704,38 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts
approve: true,
});
const skills = normalizeSkills(result.commands, fixture);
+ const scanned = await scanPiCustomizations({ workingDirs: [fixture.workingDir] });
+ const discoveredProjectNames = new Set(
+ scanned.items
+ .filter((item) => item.scope === 'repo')
+ .map((item) => `skill:${item.name}`),
+ );
+ const loadedProjectNames = new Set(
+ skills
+ .filter((skill) => skill.scope === 'project')
+ .map((skill) => skill.name),
+ );
+ const loadedProjectBaseDirs = new Map(
+ result.commands.flatMap((command) => {
+ const baseDir = command.sourceInfo?.baseDir;
+ if (command.source !== 'skill' || command.sourceInfo?.scope !== 'project' || !baseDir) {
+ return [];
+ }
+ return [[command.name, canonicalPath(baseDir)] as const];
+ }),
+ );
+ expect(discoveredProjectNames).toEqual(new Set([
+ 'skill:ancestor-agents-skill',
+ 'skill:project-agents-skill',
+ 'skill:project-pi-skill',
+ ]));
+ expect([...loadedProjectNames].every((name) => discoveredProjectNames.has(name))).toBe(true);
+ expect([...discoveredProjectNames].filter((name) => !loadedProjectNames.has(name))).toEqual([]);
+ expect(loadedProjectBaseDirs).toEqual(new Map([
+ ['skill:ancestor-agents-skill', canonicalPath(path.join(fixture.repoRoot, '.agents'))],
+ ['skill:project-agents-skill', canonicalPath(path.join(fixture.workingDir, '.agents'))],
+ ['skill:project-pi-skill', canonicalPath(path.join(fixture.workingDir, '.pi'))],
+ ]));
expect(skills).toEqual([
{
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-skills.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-skills.test.ts
index c7f50da21a..ffc445f783 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-skills.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-skills.test.ts
@@ -1,7 +1,7 @@
/**
* PiAgent.listAgentSkills 单测 —— 纯文件系统技能发现(不 spawn pi 二进制)。
*
- * 验证 pi 的 ChatInput `/` palette agent-skill 类目能扫到项目 .pi/agent/skills 下的
+ * 验证 pi 的 ChatInput `/` palette agent-skill 类目能扫到项目 .pi/skills 下的
* SKILL.md,与 CC/Codex 的技能可见性对齐;发现层零基线上下文(仅 name/description)。
*/
@@ -48,8 +48,8 @@ describe('PiAgent.listAgentSkills (filesystem discovery, no binary spawn)', () =
rmSync(workingDir, { recursive: true, force: true });
});
- it('discovers a project-scoped skill from .pi/agent/skills/<name>/SKILL.md', async () => {
- const skillDir = path.join(workingDir, '.pi', 'agent', 'skills', 'demo-skill');
+ it('discovers a project-scoped skill from .pi/skills/<name>/SKILL.md as unavailable', async () => {
+ const skillDir = path.join(workingDir, '.pi', 'skills', 'demo-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(
path.join(skillDir, 'SKILL.md'),
@@ -64,6 +64,8 @@ describe('PiAgent.listAgentSkills (filesystem discovery, no binary spawn)', () =
expect(found?.kind).toBe('agent-skill');
expect(found?.source).toBe('skill');
expect(found?.scope).toBe('repo');
+ expect(found?.runtimeStatus).toBe('discovered');
+ expect(found?.runtimeCommandName).toBe('skill:demo-skill');
expect(found?.description).toContain('demo skill');
});
diff --git a/packages/maker-core/src/agents/pi/customization-scanner.ts b/packages/maker-core/src/agents/pi/customization-scanner.ts
index aa6105d21a..ae0fd12133 100644
--- a/packages/maker-core/src/agents/pi/customization-scanner.ts
+++ b/packages/maker-core/src/agents/pi/customization-scanner.ts
@@ -1,59 +1,136 @@
/**
- * pi 文件系统 customization scanner。
+ * Pi filesystem customization scanner.
*
- * 扫描路径:
- * ~/.agents/skills/{name}/SKILL.md → kind=skill, scope=user (跨引擎共享;
- * 与 cc/codex 同一个根,pi 因此看到与它们
- * 一致的技能包,无需 fan)
- * ~/.pi/agent/skills/{name}/SKILL.md → kind=skill, scope=user (pi 原生)
- * {workingDir}/.agents/skills/{name}/... → kind=skill, scope=repo
- * {workingDir}/.pi/agent/skills/{name}/... → kind=skill, scope=repo (pi 原生)
- *
- * 纯文件系统发现,不 spawn pi —— ChatInput `/` palette 的 agent-skill 类目与
- * SkillHub 管理页共用。只暴露技能"存在"(name/description frontmatter),技能正文
- * 仅在 `/skill:name` 被调用时才进上下文,故此发现层零基线上下文增长。
+ * Pi reads user skills from ~/.agents/skills in Cindy sessions. Project skills
+ * live in {cwd}/.pi/skills and in every .agents/skills directory from cwd up to
+ * the nearest Git repository root. Project discovery is only a preview until
+ * Pi's runtime catalog confirms a skill was loaded.
*/
+import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type {
+ AgentCustomization,
ListCustomizationsOptions,
ListCustomizationsResult,
} from '../../types/customizations.js';
import { scanCustomizationSources, type SourceDef } from '../shared/customization-scanner.js';
-function buildPiSources(workingDirs: string[]): SourceDef[] {
- const home = os.homedir();
+function canonicalDirectory(dir: string): string {
+ const resolved = path.resolve(dir);
+ if (!fs.existsSync(resolved)) return resolved;
+ try {
+ return fs.realpathSync(resolved);
+ } catch {
+ return resolved;
+ }
+}
+
+function isExistingDirectory(dir: string): boolean {
+ try {
+ return fs.statSync(dir).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+function hasGitMarker(dir: string): boolean {
+ try {
+ const marker = fs.statSync(path.join(dir, '.git'));
+ return marker.isDirectory() || marker.isFile();
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ return code !== 'ENOENT' && code !== 'ENOTDIR';
+ }
+}
+
+function findNearestGitRoot(workingDir: string): string | null {
+ let current = canonicalDirectory(workingDir);
+ while (true) {
+ if (hasGitMarker(current)) return current;
+ const parent = path.dirname(current);
+ if (parent === current) return null;
+ current = parent;
+ }
+}
+
+function agentSkillAncestors(workingDir: string): string[] {
+ const start = canonicalDirectory(workingDir);
+ const repoRoot = findNearestGitRoot(start);
+ const result: string[] = [];
+ let current = start;
+
+ while (true) {
+ result.push(current);
+ if (!repoRoot || current === repoRoot) break;
+ const parent = path.dirname(current);
+ if (parent === current) break;
+ current = parent;
+ }
+ return result;
+}
+
+export function buildPiSources(workingDirs: string[]): SourceDef[] {
const sources: SourceDef[] = [
- { engine: 'pi', kind: 'skill', scope: 'user', dir: path.join(home, '.agents', 'skills') },
- { engine: 'pi', kind: 'skill', scope: 'user', dir: path.join(home, '.pi', 'agent', 'skills') },
+ { engine: 'pi', kind: 'skill', scope: 'user', dir: path.join(os.homedir(), '.agents', 'skills') },
];
- for (const wd of workingDirs) {
- if (!wd || !path.isAbsolute(wd)) continue;
- sources.push(
- { engine: 'pi', kind: 'skill', scope: 'repo', dir: path.join(wd, '.agents', 'skills'), workingDir: wd },
- { engine: 'pi', kind: 'skill', scope: 'repo', dir: path.join(wd, '.pi', 'agent', 'skills'), workingDir: wd },
- );
+ const seen = new Set<string>();
+
+ for (const input of workingDirs) {
+ if (!input || !path.isAbsolute(input) || !isExistingDirectory(input)) continue;
+ // Scan through the physical directory so Git-boundary discovery is stable,
+ // but preserve the caller's lexical root for project ownership. Two project
+ // entries may intentionally refer to the same checkout through different
+ // symlink paths and must remain distinguishable to SkillHub.
+ const workingDir = path.resolve(input);
+ const scanRoot = canonicalDirectory(input);
+ const projectBoundary = findNearestGitRoot(scanRoot) ?? scanRoot;
+ const addProjectSource = (dir: string): void => {
+ const key = `${workingDir}\0${canonicalDirectory(dir)}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ sources.push({
+ engine: 'pi',
+ kind: 'skill',
+ scope: 'repo',
+ dir,
+ workingDir,
+ runtimeStatus: 'discovered',
+ skillContainWithin: projectBoundary,
+ });
+ };
+
+ addProjectSource(path.join(scanRoot, '.pi', 'skills'));
+ for (const ancestor of agentSkillAncestors(scanRoot)) {
+ addProjectSource(path.join(ancestor, '.agents', 'skills'));
+ }
}
return sources;
}
-export async function scanPiCustomizations(
- opts: ListCustomizationsOptions,
-): Promise<ListCustomizationsResult> {
+function dedupePiItems(items: AgentCustomization[]): AgentCustomization[] {
+ const seen = new Set<string>();
+ return items.filter((item) => {
+ const key = [item.scope, item.workingDir ?? '', canonicalDirectory(item.absolutePath)].join('\0');
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+}
+
+export async function scanPiCustomizations(opts: ListCustomizationsOptions): Promise<ListCustomizationsResult> {
if (opts.kinds && opts.kinds.length > 0 && !opts.kinds.includes('skill')) {
return { items: [], errors: [] };
}
- const workingDirs = opts.workingDirs ?? [];
- const sources = buildPiSources(workingDirs);
- const result = scanCustomizationSources(sources, null);
-
+ const result = scanCustomizationSources(buildPiSources(opts.workingDirs ?? []), null);
+ result.items = dedupePiItems(result.items);
result.items.sort((a, b) => {
if (a.scope !== b.scope) return a.scope.localeCompare(b.scope);
- return a.name.localeCompare(b.name);
+ if (a.name !== b.name) return a.name.localeCompare(b.name);
+ return a.absolutePath.localeCompare(b.absolutePath);
});
-
return result;
}
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index cd0bd7e7f2..aed02fb1a1 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -75,6 +75,7 @@ import type {
import type { MemoryResetResult, MemorySetResult, MemoryStatus } from '../../types/memory.js';
import type { AgentKind, Effort, UserMessage, UserContentBlock } from '../../types/common.js';
import type { ListAgentSkillsOptions, ListAgentSkillsResult } from '../../types/palette.js';
+import type { ListCustomizationsOptions, ListCustomizationsResult } from '../../types/customizations.js';
import { scanPiCustomizations } from './customization-scanner.js';
import { createAsyncQueue, type AsyncQueue } from '../shared/async-queue.js';
import { resolveMcpToolTarget } from '../shared/mcp-tool-target.js';
@@ -2355,12 +2356,18 @@ export class PiAgent extends BaseAgent {
}
}
+ /** SkillHub raw view; project items remain discovered until runtime truth says otherwise. */
+ override async listCustomizations(
+ opts: ListCustomizationsOptions,
+ ): Promise<ListCustomizationsResult> {
+ return scanPiCustomizations(opts);
+ }
+
/**
* ChatInput `/` palette 的 agent-skill 类目 —— 纯文件系统发现,与 CC/Codex 对齐。
*
- * 扫共享根 ~/.agents/skills(cc/codex 同源,pi 因此看到一致的技能包)+ pi 原生
- * ~/.pi/agent/skills + 项目目录。只暴露技能"存在"(name/description),技能正文仅
- * 在 /skill:name 被调用时进上下文 —— 故此发现层零基线上下文增长(契合精简 pi)。
+ * 扫共享根 ~/.agents/skills + 项目 .pi/skills 和从 cwd 到 Git 根的
+ * .agents/skills。项目条目仅表示已发现;只有 get_commands 能确认 loaded。
*/
override async listAgentSkills(opts: ListAgentSkillsOptions): Promise<ListAgentSkillsResult> {
const { items, errors } = await scanPiCustomizations({
@@ -2377,6 +2384,8 @@ export class PiAgent extends BaseAgent {
path: it.absolutePath,
scope: (it.scope === 'repo' ? 'repo' : 'user') as 'user' | 'repo',
enabled: it.enabled ?? true,
+ runtimeStatus: it.runtimeStatus,
+ runtimeCommandName: `skill:${it.name}`,
}))
.sort((a, b) => a.name.localeCompare(b.name)),
};
diff --git a/packages/maker-core/src/agents/shared/customization-scanner.ts b/packages/maker-core/src/agents/shared/customization-scanner.ts
index 6861732c7b..5f584f8f4b 100644
--- a/packages/maker-core/src/agents/shared/customization-scanner.ts
+++ b/packages/maker-core/src/agents/shared/customization-scanner.ts
@@ -21,6 +21,9 @@ export interface SourceDef {
scope: string;
dir: string;
workingDir?: string;
+ runtimeStatus?: AgentCustomization['runtimeStatus'];
+ /** Optional physical root that the skill source, folder, and SKILL.md must stay inside. */
+ skillContainWithin?: string;
}
export function parseFrontmatter(raw: string): {
@@ -100,6 +103,7 @@ function readFolderSkill(source: SourceDef, folder: string, mdPath: string): Age
frontmatter,
parseError,
...(source.workingDir ? { workingDir: source.workingDir } : {}),
+ ...(source.runtimeStatus ? { runtimeStatus: source.runtimeStatus } : {}),
};
}
@@ -128,9 +132,29 @@ function readFileCustomization(source: SourceDef, mdPath: string): AgentCustomiz
frontmatter,
parseError,
...(source.workingDir ? { workingDir: source.workingDir } : {}),
+ ...(source.runtimeStatus ? { runtimeStatus: source.runtimeStatus } : {}),
};
}
+type PathContainmentApi = Pick<typeof path, 'relative' | 'isAbsolute'>;
+
+export function isCustomizationPathInside(
+ parent: string,
+ child: string,
+ pathApi: PathContainmentApi = path,
+): boolean {
+ const relative = pathApi.relative(parent, child);
+ return relative === '' || (!relative.startsWith('..') && !pathApi.isAbsolute(relative));
+}
+
+function realPathInside(parentRealPath: string, candidate: string): boolean {
+ try {
+ return isCustomizationPathInside(parentRealPath, fs.realpathSync(candidate));
+ } catch {
+ return false;
+ }
+}
+
function scanOneSource(source: SourceDef): {
items: AgentCustomization[];
errors: Array<{ path?: string; message: string }>;
@@ -140,6 +164,15 @@ function scanOneSource(source: SourceDef): {
if (!fs.existsSync(source.dir)) return { items: [], errors };
const stat = fs.statSync(source.dir);
if (!stat.isDirectory()) return { items: [], errors };
+ let containmentRoot: string | null = null;
+ if (source.skillContainWithin) {
+ try {
+ containmentRoot = fs.realpathSync(source.skillContainWithin);
+ } catch {
+ return { items: [], errors };
+ }
+ if (!realPathInside(containmentRoot, source.dir)) return { items: [], errors };
+ }
const entries = fs.readdirSync(source.dir, { withFileTypes: true });
const items: AgentCustomization[] = [];
@@ -161,6 +194,12 @@ function scanOneSource(source: SourceDef): {
continue;
}
}
+ if (
+ containmentRoot &&
+ (!realPathInside(containmentRoot, folder) || !realPathInside(containmentRoot, actualMd))
+ ) {
+ continue;
+ }
items.push(readFolderSkill(source, folder, actualMd));
} else {
if (!ent.isFile()) continue;
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index 6992bd2f53..63ceed26f7 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -910,6 +910,95 @@ describe('Maker session capabilities', () => {
});
});
+describe('Maker Pi runtime skill status', () => {
+ it('marks only project skills confirmed by the matching live session as loaded', async () => {
+ const agent = createAgent(async (opts) => {
+ const handle = createHandle({ id: `pi-${opts.sessionId}`, agentKind: 'pi' });
+ handle.getRuntimeCapabilities = () => ({
+ sessionId: opts.sessionId,
+ capturedAt: '2026-08-08T00:00:00.000Z',
+ generation: 1,
+ status: 'loaded',
+ source: 'pi:get_commands',
+ commands: [
+ {
+ name: `skill:${opts.sessionId}-skill`,
+ source: 'skill',
+ sourceInfo: { source: 'auto', scope: 'project', baseDir: '/repo/.pi' },
+ },
+ {
+ name: 'skill:user-collision',
+ source: 'skill',
+ sourceInfo: { source: 'auto', scope: 'user', baseDir: '/home/.agents/skills' },
+ },
+ ],
+ });
+ return handle;
+ }, 'pi');
+ const projectSkill = (name: string, skillPath: string) => ({
+ kind: 'agent-skill' as const,
+ name,
+ source: 'skill' as const,
+ scope: 'repo' as const,
+ path: skillPath,
+ runtimeStatus: 'discovered' as const,
+ });
+ agent.listAgentSkills = vi.fn(async () => ({
+ skills: [
+ projectSkill('one-skill', '/repo/.pi/skills/one-skill'),
+ projectSkill('one-skill', '/repo/.agents/skills/one-skill'),
+ projectSkill('two-skill', '/repo/.pi/skills/two-skill'),
+ projectSkill('user-collision', '/repo/.pi/skills/user-collision'),
+ ],
+ }));
+ const maker = new Maker({
+ agents: { pi: agent },
+ storage: createStorage(),
+ logger: createLogger(),
+ });
+ await maker.createSession({
+ id: 'one',
+ agentKind: 'pi',
+ workingDir: '/repo',
+ model: 'm',
+ });
+ await maker.createSession({
+ id: 'two',
+ agentKind: 'pi',
+ workingDir: '/repo',
+ model: 'm',
+ });
+
+ const one = await maker.listAgentSkills('pi', { workingDir: '/repo', sessionId: 'one' });
+ const two = await maker.listAgentSkills('pi', { workingDir: '/repo', sessionId: 'two' });
+ const preview = await maker.listAgentSkills('pi', { workingDir: '/repo' });
+ const wrongProject = await maker.listAgentSkills('pi', {
+ workingDir: '/other-repo',
+ sessionId: 'one',
+ });
+
+ expect(one.skills.map((skill) => [skill.name, skill.runtimeStatus])).toEqual([
+ ['one-skill', 'loaded'],
+ ['one-skill', 'discovered'],
+ ['two-skill', 'discovered'],
+ ['user-collision', 'discovered'],
+ ]);
+ expect(one.skills[0]).toMatchObject({
+ name: 'one-skill',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:one-skill',
+ });
+ expect(two.skills.map((skill) => [skill.name, skill.runtimeStatus])).toEqual([
+ ['one-skill', 'discovered'],
+ ['one-skill', 'discovered'],
+ ['two-skill', 'loaded'],
+ ['user-collision', 'discovered'],
+ ]);
+ expect(preview.skills.every((skill) => skill.runtimeStatus === 'discovered')).toBe(true);
+ expect(wrongProject.skills.every((skill) => skill.runtimeStatus === 'discovered')).toBe(true);
+ });
+});
+
describe('Session turn send guard', () => {
it('reserves the turn synchronously while handle.send is still awaiting', async () => {
let publishRelease!: (release: () => void) => void;
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index 199e537e14..54a180d045 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -16,6 +16,8 @@
*/
import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
+import fs from 'node:fs';
+import path from 'node:path';
import type { AgentKind } from './types/common.js';
import type { Capabilities } from './types/capabilities.js';
@@ -149,6 +151,51 @@ function capabilitiesForSession(
};
}
+function canonicalPiRuntimePath(value: string): string {
+ try {
+ return fs.realpathSync(value);
+ } catch {
+ return path.resolve(value);
+ }
+}
+
+function mergePiRuntimeSkillStatuses(
+ result: ListAgentSkillsResult,
+ manifest: PiRuntimeCapabilityManifest | undefined,
+): ListAgentSkillsResult {
+ if (manifest?.status !== 'loaded') return result;
+ const loadedProjectSkills = new Map(
+ manifest.commands.flatMap((command) => {
+ const baseDir = command.sourceInfo.baseDir;
+ if (
+ command.source !== 'skill'
+ || command.sourceInfo.scope !== 'project'
+ || typeof baseDir !== 'string'
+ || !command.name.startsWith('skill:')
+ ) return [];
+ return [[[
+ command.name.slice('skill:'.length),
+ canonicalPiRuntimePath(baseDir),
+ ].join('\0'), command.name] as const];
+ }),
+ );
+ if (loadedProjectSkills.size === 0) return result;
+ return {
+ ...result,
+ skills: result.skills.map((skill) => {
+ const runtimeCommandName = skill.scope === 'repo' && skill.path
+ ? loadedProjectSkills.get([
+ skill.name,
+ canonicalPiRuntimePath(path.dirname(path.dirname(skill.path))),
+ ].join('\0'))
+ : undefined;
+ return runtimeCommandName
+ ? { ...skill, runtimeStatus: 'loaded' as const, runtimeCommandName }
+ : skill;
+ }),
+ };
+}
+
function isClaimableCodexThreadId(id: string | undefined): id is string {
return (
typeof id === 'string' &&
@@ -794,9 +841,20 @@ export class Maker {
*/
async listAgentSkills(
agentKind: AgentKind,
- opts: ListAgentSkillsOptions,
+ opts: ListAgentSkillsOptions & { sessionId?: string },
): Promise<ListAgentSkillsResult> {
- return this.requireAgent(agentKind).listAgentSkills(opts);
+ const { sessionId, ...agentOpts } = opts;
+ const result = await this.requireAgent(agentKind).listAgentSkills(agentOpts);
+ if (agentKind !== 'pi' || !sessionId) return result;
+ const session = this.getSession(sessionId);
+ if (
+ session?.agentKind !== 'pi'
+ || !opts.workingDir
+ || canonicalPiRuntimePath(opts.workingDir) !== canonicalPiRuntimePath(session.workDir)
+ ) {
+ return result;
+ }
+ return mergePiRuntimeSkillStatuses(result, session.getRuntimeCapabilities());
}
/** ChatInput `@` palette entries, routed by agent kind. */
diff --git a/packages/maker-core/src/types/customizations.ts b/packages/maker-core/src/types/customizations.ts
index 7330d8ec60..ea1a66291c 100644
--- a/packages/maker-core/src/types/customizations.ts
+++ b/packages/maker-core/src/types/customizations.ts
@@ -1,3 +1,5 @@
+import type { PiRuntimeCapabilityStatus } from './pi-runtime-capabilities.js';
+
/**
* AgentCustomization —— "agent 自己认识的本地 customization" 的统一描述。
*
@@ -64,6 +66,9 @@ export interface AgentCustomization {
/** Codex 'enabled' 字段; Claude 视为始终 true (不填即 true)。 */
enabled?: boolean;
+ /** Pi scanner/runtime state. Omitted by engines without a runtime truth layer. */
+ runtimeStatus?: PiRuntimeCapabilityStatus;
+
/** Folder-shaped customization 的一级文件清单; 文件型空数组或不填。 */
files?: AgentCustomizationFile[];
diff --git a/packages/maker-core/src/types/palette.ts b/packages/maker-core/src/types/palette.ts
index 5ce0742070..1aac390c34 100644
--- a/packages/maker-core/src/types/palette.ts
+++ b/packages/maker-core/src/types/palette.ts
@@ -1,3 +1,5 @@
+import type { PiRuntimeCapabilityStatus } from './pi-runtime-capabilities.js';
+
export type SlashCommandSource = 'user' | 'skill';
/**
@@ -14,6 +16,10 @@ export interface AgentSlashCommand {
path?: string;
scope?: 'global' | 'project' | 'user' | 'repo' | 'system' | 'admin';
enabled?: boolean;
+ /** Pi discovery/runtime state; omitted for engines without a runtime truth layer. */
+ runtimeStatus?: PiRuntimeCapabilityStatus;
+ /** Provider command name used for invocation when it differs from the palette label. */
+ runtimeCommandName?: string;
}
// ── New unified command model (palette refactor) ──────────────────────────
@@ -59,6 +65,10 @@ export interface AgentSkillCommand {
path?: string;
scope?: 'global' | 'project' | 'user' | 'repo' | 'system' | 'admin';
enabled?: boolean;
+ /** Pi discovery/runtime state; omitted for engines without a runtime truth layer. */
+ runtimeStatus?: PiRuntimeCapabilityStatus;
+ /** Provider command name used for invocation when it differs from the palette label. */
+ runtimeCommandName?: string;
}
export type UnifiedCommand = DesktopCommandMeta | AgentBuiltinCommand | AgentSkillCommand;