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。

chore(desktop): restore skillhub file formatting

xd-bobo5e1259a9f27a
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 8011bce045..39ec9fe85e 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -14,9 +14,7 @@ const showMessageBox = vi.fn();
vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
const assertTrustedAppRendererEvent = vi.fn();
const isTrustedAppRendererWindow = vi.fn();
-const publishServiceOptions = vi.hoisted(() => ({
- onProgress: null as null | ((event: unknown) => void),
-}));
+const publishServiceOptions = vi.hoisted(() => ({ onProgress: null as null | ((event: unknown) => void) }));
vi.mock('../publishService', () => ({
SkillPublishService: class {
constructor(options: { onProgress: (event: unknown) => void }) {
@@ -67,10 +65,7 @@ vi.mock('../../authManager', () => ({ getCurrentDataOwnerId }));
const ownerState = { generation: 1, pending: false };
vi.mock('../../appSessionState', () => ({
activeOwnerScopeKey: () => `cloud:owner:${ownerState.generation}`,
- getActiveDataOwnerPushStamp: () => ({
- dataOwnerId: 'owner',
- ownerGeneration: ownerState.generation,
- }),
+ getActiveDataOwnerPushStamp: () => ({ dataOwnerId: 'owner', ownerGeneration: ownerState.generation }),
isAppSessionBoundaryPending: vi.fn(() => ownerState.pending),
}));
@@ -169,13 +164,12 @@ describe('registerSkillhubIpc usage handlers', () => {
showMessageBox.mockResolvedValue({ response: 0 });
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'),
- );
+ 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,
@@ -193,29 +187,16 @@ describe('registerSkillhubIpc usage handlers', () => {
const utility = { webContents: { send: vi.fn() } };
const navigated = { webContents: { send: vi.fn() } };
const destroyed = { webContents: { send: vi.fn() } };
- vi.mocked(BrowserWindow.getAllWindows).mockReturnValueOnce([
- trusted,
- utility,
- navigated,
- destroyed,
- ] as never);
+ vi.mocked(BrowserWindow.getAllWindows).mockReturnValueOnce([trusted, utility, navigated, destroyed] as never);
isTrustedAppRendererWindow.mockImplementation((win) => win === trusted);
registerSkillhubIpc({
getMaker: () => ({ listAgentSkills }) as never,
- getManagedSkillRoots,
- getAllowedProjectRoots,
- marketService: marketService as never,
+ getManagedSkillRoots, getAllowedProjectRoots, marketService: marketService as never,
});
- const feedback = {
- phase: 'scan-result',
- name: 'review-helper',
- status: 'rejected',
- rejectionReason: 'Private feedback',
- };
+ const feedback = { phase: 'scan-result', name: 'review-helper', status: 'rejected', rejectionReason: 'Private feedback' };
publishServiceOptions.onProgress!(feedback);
expect(trusted.webContents.send).toHaveBeenCalledWith('skillhub:publish-progress', {
- ...feedback,
- ownerStamp: { dataOwnerId: 'owner', ownerGeneration: 1 },
+ ...feedback, ownerStamp: { dataOwnerId: 'owner', ownerGeneration: 1 },
});
for (const win of [utility, navigated, destroyed]) {
expect(isTrustedAppRendererWindow).toHaveBeenCalledWith(win);
@@ -248,27 +229,20 @@ describe('registerSkillhubIpc usage handlers', () => {
registerSkillhubIpc({
getMaker: () => ({ listAgentSkills }) as never,
getManagedSkillRoots,
- getBuiltInSkills: () => [
- {
- name: 'cindy-skill-creator',
- absolutePath: builtInRoot,
- nativeClaudePath: '/tmp/claude-home/skills/cindy-skill-creator',
- },
- ],
+ getBuiltInSkills: () => [{
+ name: 'cindy-skill-creator',
+ absolutePath: builtInRoot,
+ nativeClaudePath: '/tmp/claude-home/skills/cindy-skill-creator',
+ }],
getAllowedProjectRoots,
marketService: marketService as never,
publishService: { publish, cancel } as never,
});
const event = { sender: { id: 12 } };
- await expect(
- handlers.get('skillhub:publish')!(event, {
- absolutePath: builtInFile,
- }),
- ).resolves.toMatchObject({
- success: false,
- message: expect.stringContaining('cannot be published'),
- });
+ await expect(handlers.get('skillhub:publish')!(event, {
+ absolutePath: builtInFile,
+ })).resolves.toMatchObject({ success: false, message: expect.stringContaining('cannot be published') });
expect(assertTrustedAppRendererEvent).toHaveBeenCalledWith(event);
expect(publish).not.toHaveBeenCalled();
});
@@ -278,89 +252,49 @@ describe('registerSkillhubIpc usage handlers', () => {
{ channel: 'skillhub:list-published-versions', field: 'name', method: 'listPublishedVersions' },
] as const)('$channel private review boundary', ({ channel, field, method }) => {
it('rejects an untrusted sender before accessing the service', async () => {
- assertTrustedAppRendererEvent.mockImplementationOnce(() => {
- throw new Error('PERMISSION_DENIED');
- });
- await expect(handlers.get(channel)!({}, { [field]: 'review-helper' })).rejects.toThrow(
- 'PERMISSION_DENIED',
- );
+ assertTrustedAppRendererEvent.mockImplementationOnce(() => { throw new Error('PERMISSION_DENIED'); });
+ await expect(handlers.get(channel)!({}, { [field]: 'review-helper' })).rejects.toThrow('PERMISSION_DENIED');
expect(marketService[method]).not.toHaveBeenCalled();
});
- it.each([
- null,
- [],
- {},
- { value: 3 },
- { value: '' },
- { value: 'a'.repeat(129) },
- { value: 'valid', version: 3 },
- { value: 'valid', version: 'v'.repeat(129) },
- { value: 'valid', catalogScope: 'invalid' },
- { value: 'bad\0name' },
+ it.each([null, [], {}, { value: 3 }, { value: '' }, { value: 'a'.repeat(129) },
+ { value: 'valid', version: 3 }, { value: 'valid', version: 'v'.repeat(129) },
+ { value: 'valid', catalogScope: 'invalid' }, { value: 'bad\0name' },
])('rejects malformed parameters %j without a service request', async (input) => {
const params = input && !Array.isArray(input) ? { ...input, [field]: input.value } : input;
await expect(handlers.get(channel)!({}, params)).rejects.toThrow('INVALID_PARAMS');
expect(marketService[method]).not.toHaveBeenCalled();
});
- it.each([undefined, 'team', 'market'] as const)(
- 'preserves catalog selection %s for trusted reads',
- async (catalogScope) => {
- const result = { success: true, rejectionReason: 'Private feedback' };
- marketService[method].mockResolvedValueOnce(result);
- const event = { sender: { id: 11 } };
- expect(
- await handlers.get(channel)!(event, {
- [field]: 'review-helper',
- version: '1.0.1',
- catalogScope,
- }),
- ).toEqual(result);
- expect(assertTrustedAppRendererEvent).toHaveBeenCalledWith(event);
- if (method === 'getScanStatus') {
- expect(marketService[method]).toHaveBeenCalledWith({
- slug: 'review-helper',
- version: '1.0.1',
- ...(catalogScope ? { catalogScope } : {}),
- });
- } else {
- expect(marketService[method]).toHaveBeenCalledWith('review-helper', catalogScope);
- }
- },
- );
+ it.each([undefined, 'team', 'market'] as const)('preserves catalog selection %s for trusted reads', async (catalogScope) => {
+ const result = { success: true, rejectionReason: 'Private feedback' };
+ marketService[method].mockResolvedValueOnce(result);
+ const event = { sender: { id: 11 } };
+ expect(await handlers.get(channel)!(event, { [field]: 'review-helper', version: '1.0.1', catalogScope })).toEqual(result);
+ expect(assertTrustedAppRendererEvent).toHaveBeenCalledWith(event);
+ if (method === 'getScanStatus') {
+ expect(marketService[method]).toHaveBeenCalledWith({ slug: 'review-helper', version: '1.0.1', ...(catalogScope ? { catalogScope } : {}) });
+ } else {
+ expect(marketService[method]).toHaveBeenCalledWith('review-helper', catalogScope);
+ }
+ });
- it.each(['generation', 'boundary'] as const)(
- 'drops a private response across an account %s change',
- async (transition) => {
- let resolve!: (value: unknown) => void;
- marketService[method].mockImplementationOnce(
- () =>
- new Promise((done) => {
- resolve = done;
- }),
- );
- const request = handlers.get(channel)!({}, { [field]: 'review-helper' });
- if (transition === 'generation') ownerState.generation += 1;
- else ownerState.pending = true;
- resolve({
- success: true,
- rejectionReason: 'Private feedback',
- versions: [{ rejectionReason: 'Private feedback' }],
- });
- const result = await request;
- expect(result).toMatchObject({ success: false });
- expect(JSON.stringify(result)).not.toContain('Private feedback');
- },
- );
+ it.each(['generation', 'boundary'] as const)('drops a private response across an account %s change', async (transition) => {
+ let resolve!: (value: unknown) => void;
+ marketService[method].mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
+ const request = handlers.get(channel)!({}, { [field]: 'review-helper' });
+ if (transition === 'generation') ownerState.generation += 1;
+ else ownerState.pending = true;
+ resolve({ success: true, rejectionReason: 'Private feedback', versions: [{ rejectionReason: 'Private feedback' }] });
+ const result = await request;
+ expect(result).toMatchObject({ success: false });
+ expect(JSON.stringify(result)).not.toContain('Private feedback');
+ });
it('preserves the empty-version shorthand for the latest release', async () => {
marketService[method].mockResolvedValueOnce({ success: true });
- expect(await handlers.get(channel)!({}, { [field]: 'review-helper', version: '' })).toEqual({
- success: true,
- });
- if (method === 'getScanStatus')
- expect(marketService[method]).toHaveBeenCalledWith({ slug: 'review-helper' });
+ expect(await handlers.get(channel)!({}, { [field]: 'review-helper', version: '' })).toEqual({ success: true });
+ if (method === 'getScanStatus') expect(marketService[method]).toHaveBeenCalledWith({ slug: 'review-helper' });
});
});
@@ -374,14 +308,12 @@ describe('registerSkillhubIpc usage handlers', () => {
}),
};
scanAllSkills.mockResolvedValueOnce({
- skills: [
- {
- absolutePath: '/physical/demo',
- discoveredPath: '/repo/.pi/skills/authorized/demo',
- scope: 'project',
- projectRoot: '/repo',
- },
- ],
+ skills: [{
+ absolutePath: '/physical/demo',
+ discoveredPath: '/repo/.pi/skills/authorized/demo',
+ scope: 'project',
+ projectRoot: '/repo',
+ }],
sources: [],
});
readSkillContent.mockResolvedValue({ success: true, content: 'demo' });
@@ -401,41 +333,16 @@ describe('registerSkillhubIpc usage handlers', () => {
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,
- ],
+ ['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);
- if (channel === 'skillhub:rename-local')
- expect(delegated).toHaveBeenCalledWith(params, expect.any(Function));
+ if (channel === 'skillhub:rename-local') expect(delegated).toHaveBeenCalledWith(params, expect.any(Function));
else expect(delegated).toHaveBeenCalledWith(params);
}
@@ -443,19 +350,13 @@ describe('registerSkillhubIpc usage handlers', () => {
{ sender: { id: 22 } },
{ filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },
);
- expect(wrongSender).toMatchObject({
- success: false,
- error: expect.stringContaining('latest SkillHub scan'),
- });
+ 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'),
- });
+ expect(unscannedPath).toMatchObject({ success: false, error: expect.stringContaining('latest SkillHub scan') });
scanAllSkills.mockRejectedValueOnce(new Error('scan failed'));
await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });
@@ -485,18 +386,16 @@ describe('registerSkillhubIpc usage handlers', () => {
resolveExistingSkillPathForGrant.mockReturnValue(null);
isExistingSkillPathGranted.mockReturnValue(false);
scanAllSkills.mockResolvedValueOnce({
- skills: [
- {
- id: 'builtin:learn',
- kind: 'skill',
- name: 'learn',
- absolutePath: builtInRoot,
- discoveredPath: builtInRoot,
- discoveryPaths: [builtInRoot],
- scope: 'global',
- builtIn: true,
- },
- ],
+ skills: [{
+ id: 'builtin:learn',
+ kind: 'skill',
+ name: 'learn',
+ absolutePath: builtInRoot,
+ discoveredPath: builtInRoot,
+ discoveryPaths: [builtInRoot],
+ scope: 'global',
+ builtIn: true,
+ }],
sources: [],
});
readSkillContent.mockResolvedValue({ success: true, content: 'Learn' });
@@ -507,24 +406,26 @@ describe('registerSkillhubIpc usage handlers', () => {
registerSkillhubIpc({
getMaker: () => ({ listAgentSkills }) as never,
getManagedSkillRoots,
- getBuiltInSkills: () => [
- {
- name: 'learn',
- absolutePath: builtInRoot,
- nativeClaudePath: '/tmp/claude-home/skills/learn',
- },
- ],
+ getBuiltInSkills: () => [{
+ name: 'learn',
+ absolutePath: builtInRoot,
+ nativeClaudePath: '/tmp/claude-home/skills/learn',
+ }],
getAllowedProjectRoots,
marketService: marketService as never,
publishService: { publish, cancel } as never,
});
await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });
- await expect(
- handlers.get('skillhub:read-skill')?.({ sender }, { mdPath: builtInFile }),
- ).resolves.toMatchObject({ success: true, content: 'Learn' });
+ await expect(handlers.get('skillhub:read-skill')?.(
+ { sender },
+ { mdPath: builtInFile },
+ )).resolves.toMatchObject({ success: true, content: 'Learn' });
await handlers.get('skillhub:list-children')?.({ sender }, { dirPath: builtInRoot });
- await handlers.get('skillhub:read-sibling-file')?.({ sender }, { filePath: builtInNotes });
+ await handlers.get('skillhub:read-sibling-file')?.(
+ { sender },
+ { filePath: builtInNotes },
+ );
await handlers.get('skillhub:read-raw')?.({ sender }, { filePath: builtInFile });
expect(readSkillContent).toHaveBeenCalledWith({ mdPath: builtInFile, attestedRoot });
expect(listSkillFolderChildren).toHaveBeenCalledWith({
@@ -540,30 +441,20 @@ describe('registerSkillhubIpc usage handlers', () => {
attestedRoot,
});
- await expect(
- handlers.get('skillhub:write-file')?.(
- { sender },
- { filePath: builtInFile, content: '# changed' },
- ),
- ).resolves.toMatchObject({ success: false, error: expect.stringContaining('read-only') });
+ await expect(handlers.get('skillhub:write-file')?.(
+ { sender },
+ { filePath: builtInFile, content: '# changed' },
+ )).resolves.toMatchObject({ success: false, error: expect.stringContaining('read-only') });
expect(writeSkillFile).not.toHaveBeenCalled();
});
it.each(['unchanged', 'grant-wait', 'mutation-wait', 'boundary-pending'] as const)(
- 'guards local rename at its original owner generation: %s',
- async (transition) => {
+ 'guards local rename at its original owner generation: %s', async (transition) => {
const sender = { id: 71, on: vi.fn(), once: vi.fn() };
- scanAllSkills.mockResolvedValueOnce({
- skills: [
- {
- absolutePath: '/physical/demo',
- discoveredPath: '/repo/.pi/skills/authorized/demo',
- scope: 'project',
- projectRoot: '/repo',
- },
- ],
- sources: [],
- });
+ scanAllSkills.mockResolvedValueOnce({ skills: [{
+ absolutePath: '/physical/demo', discoveredPath: '/repo/.pi/skills/authorized/demo',
+ scope: 'project', projectRoot: '/repo',
+ }], sources: [] });
await handlers.get('skillhub:scan')!({ sender }, { projects: [] });
const mutate = vi.fn();
renameLocalSkill.mockImplementationOnce(async (_params, canMutate: () => boolean) => {
@@ -573,18 +464,13 @@ describe('registerSkillhubIpc usage handlers', () => {
mutate();
return { success: true, newAbsolutePath: '/physical/renamed' };
});
- if (transition === 'grant-wait')
- getAllowedProjectRoots.mockImplementationOnce(async () => {
- ownerState.generation += 1;
- return ['/repo'];
- });
- const result = await handlers.get('skillhub:rename-local')!(
- { sender },
- {
- absolutePath: '/repo/.pi/skills/authorized/demo',
- newName: 'renamed',
- },
- );
+ if (transition === 'grant-wait') getAllowedProjectRoots.mockImplementationOnce(async () => {
+ ownerState.generation += 1;
+ return ['/repo'];
+ });
+ const result = await handlers.get('skillhub:rename-local')!({ sender }, {
+ absolutePath: '/repo/.pi/skills/authorized/demo', newName: 'renamed',
+ });
expect(result).toMatchObject({ success: transition === 'unchanged' });
expect(mutate).toHaveBeenCalledTimes(transition === 'unchanged' ? 1 : 0);
if (transition === 'grant-wait') {
@@ -596,14 +482,12 @@ describe('registerSkillhubIpc usage handlers', () => {
it('revokes project scan grants after the last active project session disappears', async () => {
const sender = { id: 12, on: vi.fn(), once: vi.fn() };
scanAllSkills.mockResolvedValueOnce({
- skills: [
- {
- absolutePath: '/physical/demo',
- discoveredPath: '/repo/.pi/skills/authorized/demo',
- scope: 'project',
- projectRoot: '/repo',
- },
- ],
+ skills: [{
+ absolutePath: '/physical/demo',
+ discoveredPath: '/repo/.pi/skills/authorized/demo',
+ scope: 'project',
+ projectRoot: '/repo',
+ }],
sources: [],
});
readSkillRawFile.mockResolvedValue({ success: true, content: 'raw' });
@@ -612,43 +496,36 @@ describe('registerSkillhubIpc usage handlers', () => {
{ 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 });
+ 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 });
+ 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);
+ 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')),
- );
+ 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, on: vi.fn(), once: vi.fn() };
const scan = handlers.get('skillhub:scan');
@@ -656,70 +533,54 @@ describe('registerSkillhubIpc usage handlers', () => {
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' },
- ],
+ 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' },
- ],
+ 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 });
+ 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, on: vi.fn(), once: vi.fn() };
scanAllSkills.mockResolvedValueOnce({
- skills: [
- {
- absolutePath: '/physical/demo',
- discoveredPath: '/repo/.pi/skills/authorized/demo',
- },
- ],
+ 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 });
+ 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 });
+ 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 });
+ 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 () => {
@@ -852,7 +713,9 @@ describe('registerSkillhubIpc usage handlers', () => {
const readyClient = { id: 'ready-client' };
const firstSnapshot = { client: firstClient, userId: 'local-v1', clientEpoch: 1 };
const readySnapshot = { client: readyClient, userId: 'local-v1', clientEpoch: 2 };
- getCurrentDbClientSnapshot.mockReturnValueOnce(firstSnapshot).mockReturnValue(readySnapshot);
+ getCurrentDbClientSnapshot
+ .mockReturnValueOnce(firstSnapshot)
+ .mockReturnValue(readySnapshot);
getLocalSkillUsageSummary
.mockRejectedValueOnce(new Error('localDb not ready: pending'))
.mockResolvedValueOnce({ success: true, summary: { totalUseCount: 1 }, refreshing: false });
@@ -924,10 +787,7 @@ describe('registerSkillhubIpc usage handlers', () => {
});
const handler = handlers.get('skillhub:get-usage-diagnosis-context');
- const result = await handler?.(
- {},
- { name: 'word-doc', mdPath: 'C:\\skills\\word-doc\\SKILL.md' },
- );
+ const result = await handler?.({}, { name: 'word-doc', mdPath: 'C:\\skills\\word-doc\\SKILL.md' });
expect(readSkillRawFile).toHaveBeenCalledWith({ filePath: 'C:\\skills\\word-doc\\SKILL.md' });
expect(getLocalSkillUsageDiagnosisContext).toHaveBeenCalledWith({
@@ -1019,23 +879,12 @@ describe('registerSkillhubIpc usage handlers', () => {
fs.writeFileSync(path.join(source, 'SKILL.md'), 'local skill');
const absolutePath = fs.realpathSync.native(source);
getAllowedProjectRoots.mockResolvedValue([project]);
- scanAllSkills.mockResolvedValue({
- skills: [
- {
- kind: 'skill',
- scope: 'project',
- name: 'local',
- absolutePath,
- discoveredPath: source,
- projectRoot: project,
- },
- ],
- sources: [],
- });
+ scanAllSkills.mockResolvedValue({ skills: [{
+ kind: 'skill', scope: 'project', name: 'local', absolutePath,
+ discoveredPath: source, projectRoot: project,
+ }], sources: [] });
const event = { sender: { id: 71, on: vi.fn(), once: vi.fn() } };
- await handlers.get('skillhub:scan')!(event, {
- projects: [{ projectRoot: project, hash: 'fixture' }],
- });
+ await handlers.get('skillhub:scan')!(event, { projects: [{ projectRoot: project, hash: 'fixture' }] });
return { event, absolutePath, project };
}
@@ -1043,36 +892,27 @@ describe('registerSkillhubIpc usage handlers', () => {
const root = fs.mkdtempSync(path.join(fixtureRoot, 'shared-aliases-'));
const projects = [path.join(root, 'project-a'), path.join(root, 'project-b')];
const source = physicalProjectSkill
- ? path.join(projects[0]!, '.agents', 'skills', 'foo')
- : path.join(root, 'external', 'foo');
+ ? path.join(projects[0]!, '.agents', 'skills', 'foo') : path.join(root, 'external', 'foo');
fs.mkdirSync(source, { recursive: true });
fs.writeFileSync(path.join(source, 'SKILL.md'), 'fixture');
const absolutePath = fs.realpathSync.native(source);
- const aliases = [
- path.join(root, 'home', '.agents', 'skills', 'global-alias'),
- ...projects.map((project) => path.join(project, '.agents', 'skills', 'project-alias')),
- ];
+ const aliases = [path.join(root, 'home', '.agents', 'skills', 'global-alias'),
+ ...projects.map((project) => path.join(project, '.agents', 'skills', 'project-alias'))];
for (const alias of aliases) {
fs.mkdirSync(path.dirname(alias), { recursive: true });
fs.symlinkSync(source, alias, process.platform === 'win32' ? 'junction' : 'dir');
}
const records = aliases.map((alias, index) => ({
- id: `entry-${index}`,
- kind: 'skill',
- name: 'foo',
- absolutePath,
+ id: `entry-${index}`, kind: 'skill', name: 'foo', absolutePath,
scope: index === 0 ? 'global' : 'project',
- discoveredPath: alias,
- discoveryPaths: [alias],
+ discoveredPath: alias, discoveryPaths: [alias],
...(index > 0 ? { projectRoot: projects[index - 1] } : {}),
}));
if (physicalProjectSkill) records[1]!.discoveryPaths.push(source);
getAllowedProjectRoots.mockResolvedValue(projects);
scanAllSkills.mockResolvedValue({ skills: records, sources: [] });
const event = { sender: { id: 71, on: vi.fn(), once: vi.fn() } };
- await handlers.get('skillhub:scan')!(event, {
- projects: projects.map((projectRoot, index) => ({ projectRoot, hash: `p${index}` })),
- });
+ await handlers.get('skillhub:scan')!(event, { projects: projects.map((projectRoot, index) => ({ projectRoot, hash: `p${index}` })) });
return { absolutePath, aliases, records, projects, event };
}
@@ -1080,125 +920,70 @@ describe('registerSkillhubIpc usage handlers', () => {
const { absolutePath, aliases, projects, event } = await scanSharedAliases(false);
installServiceMocks.uninstall.mockResolvedValueOnce({ success: true });
await handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'entry-2' });
- expect(installServiceMocks.uninstall).toHaveBeenCalledWith(
- absolutePath,
- expect.objectContaining({ operationPath: aliases[2], aliases: [aliases[2]], linkOnly: true }),
- expect.any(Function),
- );
- await expect(
- handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'unknown' }),
- ).rejects.toThrow('PRECONDITION_FAILED');
+ expect(installServiceMocks.uninstall).toHaveBeenCalledWith(absolutePath,
+ expect.objectContaining({ operationPath: aliases[2], aliases: [aliases[2]], linkOnly: true }), expect.any(Function));
+ await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'unknown' }))
+ .rejects.toThrow('PRECONDITION_FAILED');
getAllowedProjectRoots.mockResolvedValue([projects[0]]);
- await expect(
- handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'entry-2' }),
- ).rejects.toThrow('PERMISSION_DENIED');
- await expect(
- handlers.get('skillhub:set-enabled')!(event, {
- absolutePath,
- skillId: 'entry-2',
- enabled: false,
- }),
- ).rejects.toThrow('PERMISSION_DENIED');
+ await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'entry-2' }))
+ .rejects.toThrow('PERMISSION_DENIED');
+ await expect(handlers.get('skillhub:set-enabled')!(event, { absolutePath, skillId: 'entry-2', enabled: false }))
+ .rejects.toThrow('PERMISSION_DENIED');
});
it('persists discovered aliases across scopes when disabling a physical Skill', async () => {
const { absolutePath, aliases, event } = await scanSharedAliases(false);
- await handlers.get('skillhub:set-enabled')!(event, {
- absolutePath,
- skillId: 'entry-2',
- enabled: false,
- });
- expect(setCindySkillEnabled).toHaveBeenCalledWith(
- absolutePath,
- false,
- expect.any(Function),
- aliases,
- );
+ await handlers.get('skillhub:set-enabled')!(event, { absolutePath, skillId: 'entry-2', enabled: false });
+ expect(setCindySkillEnabled).toHaveBeenCalledWith(absolutePath, false, expect.any(Function), aliases);
});
it('captures differently named discovery links across scopes for physical Skill removal', async () => {
const { absolutePath, aliases, event } = await scanSharedAliases(true);
installServiceMocks.uninstall.mockResolvedValueOnce({ success: true });
await handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'entry-1' });
- expect(installServiceMocks.uninstall).toHaveBeenCalledWith(
- absolutePath,
- expect.objectContaining({
- operationPath: absolutePath,
- aliases: expect.arrayContaining(aliases),
- linkOnly: false,
- }),
- expect.any(Function),
- );
+ expect(installServiceMocks.uninstall).toHaveBeenCalledWith(absolutePath,
+ expect.objectContaining({ operationPath: absolutePath, aliases: expect.arrayContaining(aliases), linkOnly: false }), expect.any(Function));
});
it('requires native confirmation for direct uninstall and never mutates on cancellation', async () => {
const { event, absolutePath } = await scanLocalFixture();
showMessageBox.mockResolvedValueOnce({ response: 1 });
- expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({
- success: false,
- errorCode: 'CANCELLED',
- message: '',
- });
+ expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath }))
+ .toEqual({ success: false, errorCode: 'CANCELLED', message: '' });
expect(installServiceMocks.uninstall).not.toHaveBeenCalled();
- expect(showMessageBox).toHaveBeenCalledWith(
- expect.any(Object),
- expect.objectContaining({
- defaultId: 1,
- cancelId: 1,
- detail: expect.stringContaining(absolutePath),
- }),
- );
+ expect(showMessageBox).toHaveBeenCalledWith(expect.any(Object), expect.objectContaining({
+ defaultId: 1, cancelId: 1, detail: expect.stringContaining(absolutePath),
+ }));
});
- it.each(['owner', 'reload', 'source', 'project'])(
- 'revokes confirmation when %s changes while native dialog is open',
- async (change) => {
- const { event, absolutePath } = await scanLocalFixture();
- let approve!: (value: { response: number }) => void;
- showMessageBox.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- approve = resolve;
- }),
- );
- const pending = handlers.get('skillhub:uninstall')!(event, { absolutePath });
- const rejected = expect(pending).rejects.toThrow();
- await vi.waitFor(() => expect(showMessageBox).toHaveBeenCalledOnce());
- expect(installServiceMocks.uninstall).not.toHaveBeenCalled();
- if (change === 'owner') getCurrentDataOwnerId.mockReturnValue('another-owner');
- if (change === 'project') getAllowedProjectRoots.mockResolvedValue([]);
- if (change === 'reload')
- event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation')![1](
- {},
- '',
- false,
- true,
- );
- if (change === 'source') {
- fs.renameSync(absolutePath, `${absolutePath}-old`);
- fs.mkdirSync(absolutePath);
- fs.writeFileSync(path.join(absolutePath, 'SKILL.md'), 'replacement');
- }
- approve({ response: 0 });
- await rejected;
- expect(installServiceMocks.uninstall).not.toHaveBeenCalled();
- },
- );
+ it.each(['owner', 'reload', 'source', 'project'])('revokes confirmation when %s changes while native dialog is open', async (change) => {
+ const { event, absolutePath } = await scanLocalFixture();
+ let approve!: (value: { response: number }) => void;
+ showMessageBox.mockImplementationOnce(() => new Promise((resolve) => { approve = resolve; }));
+ const pending = handlers.get('skillhub:uninstall')!(event, { absolutePath });
+ const rejected = expect(pending).rejects.toThrow();
+ await vi.waitFor(() => expect(showMessageBox).toHaveBeenCalledOnce());
+ expect(installServiceMocks.uninstall).not.toHaveBeenCalled();
+ if (change === 'owner') getCurrentDataOwnerId.mockReturnValue('another-owner');
+ if (change === 'project') getAllowedProjectRoots.mockResolvedValue([]);
+ if (change === 'reload') event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation')![1]({}, '', false, true);
+ if (change === 'source') {
+ fs.renameSync(absolutePath, `${absolutePath}-old`);
+ fs.mkdirSync(absolutePath);
+ fs.writeFileSync(path.join(absolutePath, 'SKILL.md'), 'replacement');
+ }
+ approve({ response: 0 });
+ await rejected;
+ expect(installServiceMocks.uninstall).not.toHaveBeenCalled();
+ });
it('does not queue repeated native uninstall dialogs from one renderer', async () => {
const { event, absolutePath } = await scanLocalFixture();
let cancel!: (value: { response: number }) => void;
- showMessageBox.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- cancel = resolve;
- }),
- );
+ showMessageBox.mockImplementationOnce(() => new Promise((resolve) => { cancel = resolve; }));
const pending = handlers.get('skillhub:uninstall')!(event, { absolutePath });
await vi.waitFor(() => expect(showMessageBox).toHaveBeenCalledOnce());
- await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath })).rejects.toThrow(
- 'PRECONDITION_FAILED',
- );
+ await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath })).rejects.toThrow('PRECONDITION_FAILED');
expect(showMessageBox).toHaveBeenCalledOnce();
cancel({ response: 1 });
await pending;
@@ -1206,119 +991,65 @@ describe('registerSkillhubIpc usage handlers', () => {
it('refreshes the Codex cwd cache after uninstalling a granted project skill', async () => {
const { event, absolutePath, project } = await scanLocalFixture();
- installServiceMocks.uninstall.mockResolvedValueOnce({
- success: true,
- projectWorkingDir: project,
- });
+ installServiceMocks.uninstall.mockResolvedValueOnce({ success: true, projectWorkingDir: project });
listAgentSkills.mockResolvedValueOnce({ skills: [] });
- expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({
- success: true,
- });
- expect(listAgentSkills).toHaveBeenCalledWith('codex', {
- workingDir: project,
- forceReload: true,
- });
- expect(installServiceMocks.uninstall).toHaveBeenCalledWith(
- absolutePath,
- expect.objectContaining({ sourcePath: absolutePath, linkOnly: false }),
- expect.any(Function),
- );
+ expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({ success: true });
+ expect(listAgentSkills).toHaveBeenCalledWith('codex', { workingDir: project, forceReload: true });
+ expect(installServiceMocks.uninstall).toHaveBeenCalledWith(absolutePath,
+ expect.objectContaining({ sourcePath: absolutePath, linkOnly: false }), expect.any(Function));
});
it('allows toggling an unregistered local Skill and rejects another renderer', async () => {
const { event, absolutePath } = await scanLocalFixture();
const handler = handlers.get('skillhub:set-enabled')!;
expect(await handler(event, { absolutePath, enabled: false })).toEqual({ cindyEnabled: false });
- expect(setCindySkillEnabled).toHaveBeenCalledWith(
- absolutePath,
- false,
- expect.any(Function),
- expect.any(Array),
- );
- await expect(handler({ sender: { id: 72 } }, { absolutePath, enabled: false })).rejects.toThrow(
- 'PRECONDITION_FAILED',
- );
+ expect(setCindySkillEnabled).toHaveBeenCalledWith(absolutePath, false, expect.any(Function), expect.any(Array));
+ await expect(handler({ sender: { id: 72 } }, { absolutePath, enabled: false }))
+ .rejects.toThrow('PRECONDITION_FAILED');
expect(setCindySkillEnabled).toHaveBeenCalledTimes(1);
});
- it.each(['destroyed', 'reload'] as const)(
- 'revokes window cleanup grants and reissues them after a fresh scan (%s)',
- async (lifecycle) => {
- const { event, absolutePath } = await scanLocalFixture();
- installServiceMocks.uninstall.mockResolvedValueOnce({
- success: true,
- cleanupToken: 'receipt',
- });
- await handlers.get('skillhub:uninstall')!(event, { absolutePath });
- if (lifecycle === 'destroyed') {
- event.sender.once.mock.calls.find(([name]) => name === 'destroyed')![1]();
- } else {
- event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation')![1](
- {},
- '',
- false,
- true,
- );
- }
- await expect(
- handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt'),
- ).rejects.toThrow('PRECONDITION_FAILED');
- expect(installServiceMocks.retryUninstallCleanup).not.toHaveBeenCalled();
- installServiceMocks.listPendingUninstallCleanups.mockReturnValue([
- { token: 'receipt', name: 'example' },
- ]);
- installServiceMocks.retryUninstallCleanup.mockResolvedValueOnce(true);
- expect(await handlers.get('skillhub:scan')!(event, {})).toMatchObject({
- success: true,
- pendingCleanups: [{ token: 'receipt', name: 'example' }],
- });
- expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({
- complete: true,
- });
- },
- );
+ it.each(['destroyed', 'reload'] as const)('revokes window cleanup grants and reissues them after a fresh scan (%s)', async (lifecycle) => {
+ const { event, absolutePath } = await scanLocalFixture();
+ installServiceMocks.uninstall.mockResolvedValueOnce({ success: true, cleanupToken: 'receipt' });
+ await handlers.get('skillhub:uninstall')!(event, { absolutePath });
+ if (lifecycle === 'destroyed') {
+ event.sender.once.mock.calls.find(([name]) => name === 'destroyed')![1]();
+ } else {
+ event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation')![1]({}, '', false, true);
+ }
+ await expect(handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).rejects.toThrow('PRECONDITION_FAILED');
+ expect(installServiceMocks.retryUninstallCleanup).not.toHaveBeenCalled();
+ installServiceMocks.listPendingUninstallCleanups.mockReturnValue([{ token: 'receipt', name: 'example' }]);
+ installServiceMocks.retryUninstallCleanup.mockResolvedValueOnce(true);
+ expect(await handlers.get('skillhub:scan')!(event, {})).toMatchObject({
+ success: true, pendingCleanups: [{ token: 'receipt', name: 'example' }],
+ });
+ expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({ complete: true });
+ });
it('issues independent recovery grants to two scanned windows and rejects account changes', async () => {
const { event } = await scanLocalFixture();
const second = { sender: { id: event.sender.id + 1, once: vi.fn(), on: vi.fn() } };
- installServiceMocks.listPendingUninstallCleanups.mockReturnValue([
- { token: 'receipt', name: 'example' },
- ]);
- installServiceMocks.retryUninstallCleanup.mockImplementation(async (_token, canMutate) =>
- canMutate(),
- );
+ installServiceMocks.listPendingUninstallCleanups.mockReturnValue([{ token: 'receipt', name: 'example' }]);
+ installServiceMocks.retryUninstallCleanup.mockImplementation(async (_token, canMutate) => canMutate());
await handlers.get('skillhub:scan')!(event, {});
await handlers.get('skillhub:scan')!(second, {});
- expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({
- complete: true,
- });
- expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(second, 'receipt')).toEqual({
- complete: true,
- });
+ expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({ complete: true });
+ expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(second, 'receipt')).toEqual({ complete: true });
await handlers.get('skillhub:scan')!(event, {});
getCurrentDataOwnerId.mockReturnValue('other-owner');
- await expect(
- handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt'),
- ).rejects.toThrow('PRECONDITION_FAILED');
+ await expect(handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).rejects.toThrow('PRECONDITION_FAILED');
});
it('withholds a late cleanup receipt when its window reloads during uninstall', async () => {
const { event, absolutePath } = await scanLocalFixture();
installServiceMocks.uninstall.mockImplementationOnce(async () => {
- event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation')![1](
- {},
- '',
- false,
- true,
- );
+ event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation')![1]({}, '', false, true);
return { success: true, cleanupToken: 'late-receipt' };
});
- expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({
- success: true,
- });
- await expect(
- handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'late-receipt'),
- ).rejects.toThrow('PRECONDITION_FAILED');
+ expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({ success: true });
+ await expect(handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'late-receipt')).rejects.toThrow('PRECONDITION_FAILED');
});
it('rejects direct uninstall of a plugin snapshot even when the scanned UI claims it is removable', async () => {
@@ -1330,29 +1061,17 @@ describe('registerSkillhubIpc usage handlers', () => {
fs.mkdirSync(path.dirname(alias), { recursive: true });
fs.symlinkSync(source, alias, process.platform === 'win32' ? 'junction' : 'dir');
getManagedSkillRoots.mockReturnValue([stateRoot]);
- scanAllSkills.mockResolvedValue({
- skills: [
- {
- kind: 'skill',
- scope: 'global',
- name: 'plugin--skill',
- canUninstall: true,
- absolutePath: source,
- discoveredPath: alias,
- discoveryPaths: [alias],
- },
- ],
- sources: [],
- });
+ scanAllSkills.mockResolvedValue({ skills: [{
+ kind: 'skill', scope: 'global', name: 'plugin--skill', canUninstall: true,
+ absolutePath: source, discoveredPath: alias, discoveryPaths: [alias],
+ }], sources: [] });
const event = { sender: { id: 73, on: vi.fn(), once: vi.fn() } };
await handlers.get('skillhub:scan')!(event, {});
- await expect(
- handlers.get('skillhub:uninstall')!(event, { absolutePath: source }),
- ).rejects.toThrow('PRECONDITION_FAILED');
+ await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath: source }))
+ .rejects.toThrow('PRECONDITION_FAILED');
expect(installServiceMocks.uninstall).not.toHaveBeenCalled();
- await expect(
- handlers.get('skillhub:set-enabled')!(event, { absolutePath: source, enabled: false }),
- ).rejects.toThrow('PRECONDITION_FAILED');
+ await expect(handlers.get('skillhub:set-enabled')!(event, { absolutePath: source, enabled: false }))
+ .rejects.toThrow('PRECONDITION_FAILED');
expect(setCindySkillEnabled).not.toHaveBeenCalled();
expect(fs.existsSync(alias)).toBe(true);
getManagedSkillRoots.mockReturnValue([]);
diff --git a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts
index c9834317cf..c621090355 100644
--- a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts
@@ -57,7 +57,16 @@ function createSymlinkedSkill() {
fs.mkdirSync(path.dirname(exposedDir), { recursive: true });
fs.writeFileSync(
path.join(actualDir, 'SKILL.md'),
- ['---', 'name: lark-drive', '---', '', '# Lark Drive', '', 'Original content', ''].join('\n'),
+ [
+ '---',
+ 'name: lark-drive',
+ '---',
+ '',
+ '# Lark Drive',
+ '',
+ 'Original content',
+ '',
+ ].join('\n'),
'utf-8',
);
fs.mkdirSync(path.join(actualDir, 'references'));
@@ -78,52 +87,26 @@ describe('scanAllSkills', () => {
tempRoots.push(root);
const builtIn = path.join(root, 'user-data', 'system-skills', 'cindy-skill-creator');
const userSkill = path.join(root, 'home', '.agents', 'skills', 'cindy-skill-creator');
- for (const [skillPath, description] of [
- [builtIn, 'Cindy copy'],
- [userSkill, 'User copy'],
- ] as const) {
+ for (const [skillPath, description] of [[builtIn, 'Cindy copy'], [userSkill, 'User copy']] as const) {
fs.mkdirSync(skillPath, { recursive: true });
- fs.writeFileSync(
- path.join(skillPath, 'SKILL.md'),
- `---\nname: cindy-skill-creator\ndescription: ${description}\n---\nBody\n`,
- );
+ fs.writeFileSync(path.join(skillPath, 'SKILL.md'), `---\nname: cindy-skill-creator\ndescription: ${description}\n---\nBody\n`);
}
- const maker = {
- listCustomizations: vi.fn(async () => ({
- errors: [],
- items: [
- {
- engine: 'codex' as const,
- kind: 'skill',
- scope: 'user',
- name: 'cindy-skill-creator',
- description: 'User copy',
- absolutePath: userSkill,
- mdPath: path.join(userSkill, 'SKILL.md'),
- files: [],
- },
- ],
- })),
- } as unknown as Maker;
+ const maker = { listCustomizations: vi.fn(async () => ({ errors: [], items: [{
+ engine: 'codex' as const,
+ kind: 'skill',
+ scope: 'user',
+ name: 'cindy-skill-creator',
+ description: 'User copy',
+ absolutePath: userSkill,
+ mdPath: path.join(userSkill, 'SKILL.md'),
+ files: [],
+ }] })) } as unknown as Maker;
- const result = await scanAllSkills(
- {},
- maker,
- [],
- [
- {
- name: 'cindy-skill-creator',
- absolutePath: builtIn,
- nativeClaudePath: path.join(
- root,
- 'user-data',
- 'claude-home',
- 'skills',
- 'cindy-skill-creator',
- ),
- },
- ],
- );
+ const result = await scanAllSkills({}, maker, [], [{
+ name: 'cindy-skill-creator',
+ absolutePath: builtIn,
+ nativeClaudePath: path.join(root, 'user-data', 'claude-home', 'skills', 'cindy-skill-creator'),
+ }]);
expect(result.skills).toHaveLength(2);
expect(result.skills.find((skill) => skill.builtIn)).toMatchObject({
@@ -145,10 +128,7 @@ describe('scanAllSkills', () => {
tempRoots.push(root);
const builtIn = path.join(root, 'shared-system-skills', 'learn');
fs.mkdirSync(builtIn, { recursive: true });
- fs.writeFileSync(
- path.join(builtIn, 'SKILL.md'),
- '---\nname: learn\ndescription: Learn\n---\nBody\n',
- );
+ fs.writeFileSync(path.join(builtIn, 'SKILL.md'), '---\nname: learn\ndescription: Learn\n---\nBody\n');
const items = (['codex', 'pi'] as const).map((engine) => ({
engine,
kind: 'skill' as const,
@@ -163,18 +143,11 @@ describe('scanAllSkills', () => {
listCustomizations: vi.fn(async () => ({ errors: [], items })),
} as unknown as Maker;
- const result = await scanAllSkills(
- {},
- maker,
- [],
- [
- {
- name: 'learn',
- absolutePath: builtIn,
- nativeClaudePath: path.join(root, 'claude-home', 'skills', 'learn'),
- },
- ],
- );
+ const result = await scanAllSkills({}, maker, [], [{
+ name: 'learn',
+ absolutePath: builtIn,
+ nativeClaudePath: path.join(root, 'claude-home', 'skills', 'learn'),
+ }]);
expect(result.skills).toHaveLength(1);
expect(result.skills[0]).toMatchObject({
@@ -189,10 +162,7 @@ describe('scanAllSkills', () => {
it('projects the registry slug joined by physical path without replacing native directory names', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-registry-slug-'));
tempRoots.push(root);
- const paths = [
- path.join(root, '.agents', 'skills', 'Foo'),
- path.join(root, '.claude', 'skills', 'foo'),
- ];
+ const paths = [path.join(root, '.agents', 'skills', 'Foo'), path.join(root, '.claude', 'skills', 'foo')];
for (const skillPath of paths) {
fs.mkdirSync(skillPath, { recursive: true });
fs.writeFileSync(path.join(skillPath, 'SKILL.md'), '---\nname: fixture\n---\nFixture');
@@ -202,27 +172,16 @@ describe('scanAllSkills', () => {
{ skillName: 'foo', installPath: paths[0], entry },
{ skillName: 'different-skill', installPath: paths[1], entry },
]);
- const maker = {
- listCustomizations: vi.fn(async () => ({
- errors: [],
- items: paths.map((absolutePath) => ({
- engine: 'claude-code',
- kind: 'skill',
- scope: 'user',
- name: 'fixture',
- absolutePath,
- mdPath: path.join(absolutePath, 'SKILL.md'),
- files: [],
- })),
- })),
- } as unknown as Maker;
+ const maker = { listCustomizations: vi.fn(async () => ({ errors: [], items: paths.map((absolutePath) => ({
+ engine: 'claude-code', kind: 'skill', scope: 'user', name: 'fixture', absolutePath,
+ mdPath: path.join(absolutePath, 'SKILL.md'), files: [],
+ })) })) } as unknown as Maker;
const result = await scanAllSkills({}, maker);
expect(result.skills).toHaveLength(2);
for (const [index, skillPath] of paths.entries()) {
const physical = fs.realpathSync(skillPath);
expect(result.skills.find((skill) => skill.absolutePath === physical)).toMatchObject({
- name: path.basename(physical),
- registryEntry: entry,
+ name: path.basename(physical), registryEntry: entry,
registrySkillName: index === 0 ? 'foo' : 'different-skill',
});
}
@@ -238,22 +197,10 @@ describe('scanAllSkills', () => {
fs.mkdirSync(path.dirname(alias), { recursive: true });
fs.writeFileSync(path.join(source, 'SKILL.md'), '---\nname: example\n---\nExample');
fs.symlinkSync(source, alias, process.platform === 'win32' ? 'junction' : 'dir');
- const maker = {
- listCustomizations: vi.fn(async () => ({
- errors: [],
- items: [
- {
- engine: 'pi',
- kind: 'skill',
- scope: 'user',
- name: 'example',
- absolutePath: alias,
- mdPath: path.join(alias, 'SKILL.md'),
- files: [],
- },
- ],
- })),
- } as unknown as Maker;
+ const maker = { listCustomizations: vi.fn(async () => ({ errors: [], items: [{
+ engine: 'pi', kind: 'skill', scope: 'user', name: 'example', absolutePath: alias,
+ mdPath: path.join(alias, 'SKILL.md'), files: [],
+ }] })) } as unknown as Maker;
const result = await scanAllSkills({}, maker, [stateRoot]);
expect(result.skills).toHaveLength(1);
expect(result.skills[0]).toMatchObject({ managedByPlugin: true, canUninstall: false });
@@ -281,12 +228,9 @@ describe('scanAllSkills', () => {
})),
} as unknown as Maker;
- const result = await scanAllSkills(
- {
- projects: [{ projectRoot, hash: 'abcd1234' }],
- },
- maker,
- );
+ const result = await scanAllSkills({
+ projects: [{ projectRoot, hash: 'abcd1234' }],
+ }, maker);
expect(maker.listCustomizations).toHaveBeenCalledWith({
workingDirs: [projectRoot],
@@ -366,24 +310,22 @@ describe('scanAllSkills', () => {
})),
} as unknown as Maker;
- const result = await scanAllSkills(
- {
- projects: [
- { projectRoot: firstRoot, hash: 'first123' },
- { projectRoot: secondRoot, hash: 'second456' },
- ],
- },
- 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(),
- );
+ 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 () => {
@@ -398,28 +340,23 @@ describe('scanAllSkills', () => {
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: [],
- },
- ],
+ 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,
- );
+ const result = await scanAllSkills({
+ projects: [{ projectRoot, hash: 'linked123' }],
+ }, maker);
expect(result.skills[0]).toMatchObject({
scope: 'project',
@@ -455,23 +392,18 @@ describe('scanAllSkills', () => {
})),
} as unknown as Maker;
- const result = await scanAllSkills(
- {
- projects: [
- { projectRoot, hash: 'real1234' },
- { projectRoot: linkedRoot, hash: 'link5678' },
- ],
- },
- 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(),
- );
+ 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();
});
@@ -480,12 +412,9 @@ describe('scanAllSkills', () => {
listCustomizations: vi.fn(async () => ({ errors: [], items: [] })),
} as unknown as Maker;
- await scanAllSkills(
- {
- projects: [{ projectRoot: 'relative/project', hash: 'badroot' }],
- },
- maker,
- );
+ await scanAllSkills({
+ projects: [{ projectRoot: 'relative/project', hash: 'badroot' }],
+ }, maker);
expect(maker.listCustomizations).toHaveBeenCalledWith({
workingDirs: [],
@@ -562,28 +491,23 @@ describe('scanAllSkills', () => {
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: [],
- },
- ],
+ 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,
- );
+ const result = await scanAllSkills({
+ projects: [{ projectRoot, hash: 'pi123456' }],
+ }, maker);
expect(result.skills[0]).toMatchObject({
engine: 'pi',
@@ -610,9 +534,7 @@ describe('scanAllSkills', () => {
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({
+ 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');
@@ -630,27 +552,19 @@ describe('scanAllSkills', () => {
fs.writeFileSync(notes, 'notes\n', 'utf-8');
fs.writeFileSync(outside, 'private\n', 'utf-8');
- await expect(
- readSkillContent({ mdPath: skillMd, attestedRoot: builtInRoot }),
- ).resolves.toMatchObject({
+ await expect(readSkillContent({ mdPath: skillMd, attestedRoot: builtInRoot })).resolves.toMatchObject({
success: true,
content: '\n# Learn\n',
});
- await expect(
- listSkillFolderChildren({ dirPath: builtInRoot, attestedRoot: builtInRoot }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: builtInRoot, attestedRoot: builtInRoot })).resolves.toMatchObject({
success: true,
entries: expect.arrayContaining([{ name: 'SKILL.md', kind: 'file' }]),
});
- await expect(
- readSkillSiblingFile({ filePath: notes, attestedRoot: builtInRoot }),
- ).resolves.toMatchObject({
+ await expect(readSkillSiblingFile({ filePath: notes, attestedRoot: builtInRoot })).resolves.toMatchObject({
success: true,
content: 'notes\n',
});
- await expect(
- readSkillRawFile({ filePath: skillMd, attestedRoot: builtInRoot }),
- ).resolves.toMatchObject({
+ await expect(readSkillRawFile({ filePath: skillMd, attestedRoot: builtInRoot })).resolves.toMatchObject({
success: true,
content: expect.stringContaining('# Learn'),
});
@@ -658,9 +572,7 @@ describe('scanAllSkills', () => {
if (canLinkFile) {
const escape = path.join(builtInRoot, 'escape.txt');
fs.symlinkSync(outside, escape, 'file');
- await expect(
- readSkillSiblingFile({ filePath: escape, attestedRoot: builtInRoot }),
- ).resolves.toMatchObject({
+ await expect(readSkillSiblingFile({ filePath: escape, attestedRoot: builtInRoot })).resolves.toMatchObject({
success: false,
error: 'path is not under a recognized skills directory',
});
@@ -719,12 +631,10 @@ describe('skill file access', () => {
fs.writeFileSync(outsideMd, '# Outside\n', 'utf-8');
fs.symlinkSync(outsideMd, exposedMd, 'file');
- await expect(
- writeSkillFile({
- filePath: exposedMd,
- content: '# Changed\n',
- }),
- ).resolves.toEqual({
+ await expect(writeSkillFile({
+ filePath: exposedMd,
+ content: '# Changed\n',
+ })).resolves.toEqual({
success: false,
error: 'refusing to write through a symbolic link',
});
@@ -740,48 +650,37 @@ describe('skill file access', () => {
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.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: [],
- },
- ],
+ 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,
- );
+ 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 });
+ 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(
@@ -799,12 +698,10 @@ describe('skill file access', () => {
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 });
+ 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');
@@ -824,21 +721,11 @@ describe('skill file access', () => {
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 });
+ 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');
});
@@ -856,24 +743,17 @@ describe('skill file access', () => {
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 });
+ 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 { actualSkillMd, exposedDir, exposedPricingJson, exposedSkillMd } = createSymlinkedSkill();
const grantedRoot = resolveExistingSkillPathForGrant(exposedDir);
expect(grantedRoot).toBe(fs.realpathSync.native(exposedDir));
@@ -903,21 +783,15 @@ describe('skill file access', () => {
content: '{"tier":"internal"}\n',
});
fs.writeFileSync(path.join(exposedDir, '.env'), 'TOKEN=secret\n', 'utf-8');
- await expect(
- readSkillSiblingFile({ filePath: path.join(exposedDir, '.env') }),
- ).resolves.toMatchObject({
+ await expect(readSkillSiblingFile({ filePath: path.join(exposedDir, '.env') })).resolves.toMatchObject({
success: false,
error: 'path is excluded from SkillHub packages',
});
- await expect(
- readSkillRawFile({ filePath: path.join(exposedDir, '.env') }),
- ).resolves.toMatchObject({
+ await expect(readSkillRawFile({ filePath: path.join(exposedDir, '.env') })).resolves.toMatchObject({
success: false,
error: 'path is excluded from SkillHub packages',
});
- await expect(
- writeSkillFile({ filePath: path.join(exposedDir, '.env'), content: 'TOKEN=changed\n' }),
- ).resolves.toEqual({
+ await expect(writeSkillFile({ filePath: path.join(exposedDir, '.env'), content: 'TOKEN=changed\n' })).resolves.toEqual({
success: false,
error: 'path is excluded from SkillHub packages',
});
@@ -926,9 +800,7 @@ describe('skill file access', () => {
content: expect.stringContaining('Original content'),
});
- await expect(
- writeSkillFile({ filePath: exposedSkillMd, content: '# Updated\n' }),
- ).resolves.toEqual({
+ await expect(writeSkillFile({ filePath: exposedSkillMd, content: '# Updated\n' })).resolves.toEqual({
success: true,
});
@@ -939,41 +811,21 @@ describe('skill file access', () => {
const { exposedDir } = createSymlinkedSkill();
fs.writeFileSync(path.join(exposedDir, '.cca-bindings.json'), '{"task":"demo"}\n', 'utf-8');
fs.mkdirSync(path.join(exposedDir, '.cca-state', 'task'), { recursive: true });
- fs.writeFileSync(
- path.join(exposedDir, '.cca-state', 'task', 'current-goal.md'),
- 'goal\n',
- 'utf-8',
- );
+ fs.writeFileSync(path.join(exposedDir, '.cca-state', 'task', 'current-goal.md'), 'goal\n', 'utf-8');
fs.writeFileSync(path.join(exposedDir, '.env'), 'TOKEN=secret\n', 'utf-8');
fs.writeFileSync(path.join(exposedDir, '.envrc'), 'export TOKEN=secret\n', 'utf-8');
fs.writeFileSync(path.join(exposedDir, '.npmrc'), '//registry/:_authToken=secret\n', 'utf-8');
- fs.writeFileSync(
- path.join(exposedDir, '.netrc'),
- 'machine example.com password secret\n',
- 'utf-8',
- );
+ fs.writeFileSync(path.join(exposedDir, '.netrc'), 'machine example.com password secret\n', 'utf-8');
fs.writeFileSync(path.join(exposedDir, '.pypirc'), '[pypi]\npassword=secret\n', 'utf-8');
fs.writeFileSync(path.join(exposedDir, '.DS_Store'), 'metadata', 'utf-8');
fs.mkdirSync(path.join(exposedDir, '.ssh'), { recursive: true });
fs.writeFileSync(path.join(exposedDir, '.ssh', 'id_rsa'), 'private key\n', 'utf-8');
fs.mkdirSync(path.join(exposedDir, '.aws'), { recursive: true });
- fs.writeFileSync(
- path.join(exposedDir, '.aws', 'credentials'),
- 'aws_secret_access_key=secret\n',
- 'utf-8',
- );
+ fs.writeFileSync(path.join(exposedDir, '.aws', 'credentials'), 'aws_secret_access_key=secret\n', 'utf-8');
fs.mkdirSync(path.join(exposedDir, '.docker'), { recursive: true });
- fs.writeFileSync(
- path.join(exposedDir, '.docker', 'config.json'),
- '{"auths":{"example.com":{}}}\n',
- 'utf-8',
- );
+ fs.writeFileSync(path.join(exposedDir, '.docker', 'config.json'), '{"auths":{"example.com":{}}}\n', 'utf-8');
fs.mkdirSync(path.join(exposedDir, '.gem'), { recursive: true });
- fs.writeFileSync(
- path.join(exposedDir, '.gem', 'credentials'),
- ':rubygems_api_key: secret\n',
- 'utf-8',
- );
+ fs.writeFileSync(path.join(exposedDir, '.gem', 'credentials'), ':rubygems_api_key: secret\n', 'utf-8');
fs.mkdirSync(path.join(exposedDir, '.config', 'gcloud'), { recursive: true });
fs.writeFileSync(
path.join(exposedDir, '.config', 'gcloud', 'application_default_credentials.json'),
@@ -983,19 +835,11 @@ describe('skill file access', () => {
fs.mkdirSync(path.join(exposedDir, '.kube'), { recursive: true });
fs.writeFileSync(path.join(exposedDir, '.kube', 'config'), 'token: secret\n', 'utf-8');
fs.mkdirSync(path.join(exposedDir, '.config', 'gh'), { recursive: true });
- fs.writeFileSync(
- path.join(exposedDir, '.config', 'gh', 'hosts.yml'),
- 'oauth_token: secret\n',
- 'utf-8',
- );
+ fs.writeFileSync(path.join(exposedDir, '.config', 'gh', 'hosts.yml'), 'oauth_token: secret\n', 'utf-8');
fs.mkdirSync(path.join(exposedDir, '.azure'), { recursive: true });
fs.writeFileSync(path.join(exposedDir, '.azure', 'accessTokens.json'), '[]\n', 'utf-8');
fs.mkdirSync(path.join(exposedDir, '.config', 'tool'), { recursive: true });
- fs.writeFileSync(
- path.join(exposedDir, '.config', 'tool', 'settings.json'),
- '{"fixture":true}\n',
- 'utf-8',
- );
+ fs.writeFileSync(path.join(exposedDir, '.config', 'tool', 'settings.json'), '{"fixture":true}\n', 'utf-8');
fs.mkdirSync(path.join(exposedDir, 'node_modules', 'pkg'), { recursive: true });
const result = await listSkillFolderChildren({ dirPath: exposedDir });
@@ -1020,64 +864,41 @@ describe('skill file access', () => {
]),
);
- await expect(
- listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'gcloud') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'gcloud') })).resolves.toMatchObject({
success: true,
entries: [],
});
- await expect(
- listSkillFolderChildren({ dirPath: path.join(exposedDir, '.docker') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.docker') })).resolves.toMatchObject({
success: true,
entries: [],
});
- await expect(
- listSkillFolderChildren({ dirPath: path.join(exposedDir, '.gem') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.gem') })).resolves.toMatchObject({
success: true,
entries: [],
});
- await expect(
- listSkillFolderChildren({ dirPath: path.join(exposedDir, '.kube') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.kube') })).resolves.toMatchObject({
success: true,
entries: [],
});
- await expect(
- listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'gh') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'gh') })).resolves.toMatchObject({
success: true,
entries: [],
});
- await expect(
- listSkillFolderChildren({ dirPath: path.join(exposedDir, '.azure') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.azure') })).resolves.toMatchObject({
success: true,
entries: [],
});
- await expect(
- listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config') })).resolves.toMatchObject({
success: true,
entries: [{ name: 'tool', kind: 'dir' }],
});
- await expect(
- listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'tool') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'tool') })).resolves.toMatchObject({
success: true,
entries: [{ name: 'settings.json', kind: 'file' }],
});
- await expect(
- readSkillSiblingFile({
- filePath: path.join(
- exposedDir,
- '.config',
- 'gcloud',
- 'application_default_credentials.json',
- ),
- }),
- ).resolves.toMatchObject({
+ await expect(readSkillSiblingFile({
+ filePath: path.join(exposedDir, '.config', 'gcloud', 'application_default_credentials.json'),
+ })).resolves.toMatchObject({
success: false,
error: 'path is excluded from SkillHub packages',
});
@@ -1094,21 +915,13 @@ describe('skill file access', () => {
'utf-8',
);
fs.mkdirSync(path.join(commandDir, '.config', 'tool'), { recursive: true });
- fs.writeFileSync(
- path.join(commandDir, '.config', 'tool', 'settings.json'),
- '{"fixture":true}\n',
- 'utf-8',
- );
+ fs.writeFileSync(path.join(commandDir, '.config', 'tool', 'settings.json'), '{"fixture":true}\n', 'utf-8');
- await expect(
- listSkillFolderChildren({ dirPath: path.join(commandDir, '.config', 'gcloud') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(commandDir, '.config', 'gcloud') })).resolves.toMatchObject({
success: true,
entries: [],
});
- await expect(
- listSkillFolderChildren({ dirPath: path.join(commandDir, '.config', 'tool') }),
- ).resolves.toMatchObject({
+ await expect(listSkillFolderChildren({ dirPath: path.join(commandDir, '.config', 'tool') })).resolves.toMatchObject({
success: true,
entries: [{ name: 'settings.json', kind: 'file' }],
});
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index 12b8acc4c1..3f41105148 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -2,12 +2,7 @@ import fs from 'node:fs';
import { t } from '../i18n.js';
import { throwIpcError } from '../utils/ipcValidate';
import { setCindySkillEnabled } from './activationPreferences';
-import {
- inspectLocalSkillTarget,
- isLocalSkillTargetCurrent,
- isPluginManagedSkillPath,
- type LocalSkillTarget,
-} from './localSkillTarget';
+import { inspectLocalSkillTarget, isLocalSkillTargetCurrent, isPluginManagedSkillPath, type LocalSkillTarget } from './localSkillTarget';
import { tryAcquireSkillInstallLock } from './installLock';
import { randomUUID } from 'node:crypto';
import path from 'node:path';
@@ -15,21 +10,14 @@ import type { Maker } from '@cindy/maker-core';
import type { BuiltInSkillDescriptor } from '../maker-host/built-in-skills';
import { BrowserWindow, dialog, ipcMain } from 'electron';
import { getCurrentDataOwnerId } from '../authManager';
-import {
- activeOwnerScopeKey,
- getActiveDataOwnerPushStamp,
- isAppSessionBoundaryPending,
-} from '../appSessionState';
+import { activeOwnerScopeKey, getActiveDataOwnerPushStamp, isAppSessionBoundaryPending } from '../appSessionState';
import { ensureReady as ensureLocalDbReady } from '../localDb';
import {
getCurrentDbClientSnapshot,
type CurrentDbClientSnapshot,
} from '../localDb/client/current.js';
import { createLogger } from '../logger';
-import {
- assertTrustedAppRendererEvent,
- isTrustedAppRendererWindow,
-} from '../security/trustedAppRenderer.js';
+import { assertTrustedAppRendererEvent, isTrustedAppRendererWindow } from '../security/trustedAppRenderer.js';
import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
import { isSkillhubCatalogScope } from '../../shared/skillhubCatalog.js';
import { computeFolderHashDetailed } from './folderHash';
@@ -90,16 +78,10 @@ function reviewReadParams(value: unknown, nameField: 'name' | 'slug') {
// Existing scan callers may use an empty optional version to request the latest release.
const version = params.version === '' ? undefined : params.version;
const catalogScope = params.catalogScope;
- const validText = (text: unknown): text is string =>
- typeof text === 'string' &&
- text.trim().length > 0 &&
- text.length <= 128 &&
- !/[\u0000-\u001f\u007f]/.test(text);
- if (
- !validText(slug) ||
- (version !== undefined && !validText(version)) ||
- (catalogScope !== undefined && !isSkillhubCatalogScope(catalogScope))
- ) {
+ const validText = (text: unknown): text is string => typeof text === 'string'
+ && text.trim().length > 0 && text.length <= 128 && !/[\u0000-\u001f\u007f]/.test(text);
+ if (!validText(slug) || (version !== undefined && !validText(version))
+ || (catalogScope !== undefined && !isSkillhubCatalogScope(catalogScope))) {
throwIpcError('INVALID_PARAMS', 'Invalid Skill review request');
}
return {
@@ -172,14 +154,11 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const cleanupGrantKey = (senderId: number, token: string) => `${senderId}:${token}`;
const cleanupGrants = new Map<string, { ownerId: string | null; senderId: number }>();
const scannedSkillRootsBySender = new Map<number, ScannedSkillGrant>();
- const localSkillsBySender = new Map<
- number,
- Array<{
- skill: import('./scanner').Skill;
- target: LocalSkillTarget | null;
- physicalIdentity: string;
- }>
- >();
+ const localSkillsBySender = new Map<number, Array<{
+ skill: import('./scanner').Skill;
+ target: LocalSkillTarget | null;
+ physicalIdentity: string;
+ }>>();
const physicalIdentity = (source: string): string => {
const st = fs.statSync(source);
return JSON.stringify([fs.realpathSync.native(source), st.dev, st.ino]);
@@ -187,40 +166,24 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const broadcastLocalChange = () => {
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {
- try {
- win.webContents.send('skillhub:local-state-changed');
- } catch {
- /* Window closed. */
- }
+ try { win.webContents.send('skillhub:local-state-changed'); } catch { /* Window closed. */ }
}
}
};
- const requireLocalSkill = async (
- event: Electron.IpcMainInvokeEvent,
- source: string,
- skillId?: string,
- ) => {
+ const requireLocalSkill = async (event: Electron.IpcMainInvokeEvent, source: string, skillId?: string) => {
assertTrustedAppRendererEvent(event);
- if (typeof source !== 'string' || !path.isAbsolute(source))
- throwIpcError('INVALID_PARAMS', 'Invalid Skill');
- if (skillId !== undefined && (typeof skillId !== 'string' || !skillId))
- throwIpcError('INVALID_PARAMS', 'Invalid Skill identity');
+ if (typeof source !== 'string' || !path.isAbsolute(source)) throwIpcError('INVALID_PARAMS', 'Invalid Skill');
+ if (skillId !== undefined && (typeof skillId !== 'string' || !skillId)) throwIpcError('INVALID_PARAMS', 'Invalid Skill identity');
const ownerId = getCurrentDataOwnerId();
const grant = scannedSkillRootsBySender.get(event.sender.id);
- const record = localSkillsBySender
- .get(event.sender.id)
- ?.find(
- ({ skill }) =>
- skill.absolutePath === source && (skillId === undefined || skill.id === skillId),
- );
+ const record = localSkillsBySender.get(event.sender.id)?.find(({ skill }) =>
+ skill.absolutePath === source && (skillId === undefined || skill.id === skillId));
if (!record || !ownerId || grant?.ownerId !== ownerId || isAppSessionBoundaryPending()) {
throwIpcError('PRECONDITION_FAILED', 'Refresh the Skill list and retry');
}
if (record.skill.scope === 'project') {
const roots = await options.getAllowedProjectRoots();
- if (
- !roots.some((root) => projectRootKey(root) === projectRootKey(record.skill.projectRoot))
- ) {
+ if (!roots.some((root) => projectRootKey(root) === projectRootKey(record.skill.projectRoot))) {
throwIpcError('PERMISSION_DENIED', 'Project is no longer available');
}
}
@@ -232,9 +195,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
for (const alias of record.skill.discoveryPaths ?? [record.skill.discoveredPath]) {
if (physicalIdentity(alias) !== record.physicalIdentity) throw new Error('changed');
}
- } catch {
- throwIpcError('PRECONDITION_FAILED', 'Skill source changed; refresh and retry');
- }
+ } catch { throwIpcError('PRECONDITION_FAILED', 'Skill source changed; refresh and retry'); }
return record;
};
const scanGenerationBySender = new Map<number, number>();
@@ -245,20 +206,14 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
if (scanGrantCleanupRegistered.has(event.sender)) return;
scanGrantCleanupRegistered.add(event.sender);
const revokeWindowGrants = () => {
- cleanupGenerationBySender.set(
- event.sender,
- (cleanupGenerationBySender.get(event.sender) ?? 0) + 1,
- );
+ cleanupGenerationBySender.set(event.sender, (cleanupGenerationBySender.get(event.sender) ?? 0) + 1);
for (const [token, grant] of cleanupGrants) {
if (grant.senderId !== event.sender.id) continue;
cleanupGrants.delete(token);
}
scannedSkillRootsBySender.delete(event.sender.id);
localSkillsBySender.delete(event.sender.id);
- scanGenerationBySender.set(
- event.sender.id,
- (scanGenerationBySender.get(event.sender.id) ?? 0) + 1,
- );
+ scanGenerationBySender.set(event.sender.id, (scanGenerationBySender.get(event.sender.id) ?? 0) + 1);
};
event.sender.once('destroyed', () => {
revokeWindowGrants();
@@ -277,8 +232,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const entries: ScannedSkillGrant['entries'] = [];
const seenEntries = new Set<string>();
for (const skill of skills) {
- const skillProjectRootKey =
- skill.scope === 'project' ? projectRootKey(skill.projectRoot) : undefined;
+ 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.
@@ -314,20 +270,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const records = skills.flatMap((skill) => {
if (skill.kind !== 'skill') return [];
try {
- return [
- {
- skill,
- physicalIdentity: physicalIdentity(skill.absolutePath),
- target: inspectLocalSkillTarget(
- skill.absolutePath,
- skill.discoveryPaths ?? [skill.discoveredPath],
- options.getManagedSkillRoots(),
- ),
- },
- ];
- } catch {
- return [];
- }
+ return [{ skill, physicalIdentity: physicalIdentity(skill.absolutePath),
+ target: inspectLocalSkillTarget(skill.absolutePath, skill.discoveryPaths ?? [skill.discoveredPath], options.getManagedSkillRoots()) }];
+ } catch { return []; }
});
const aliasesByIdentity = new Map<string, Set<string>>();
for (const record of records) {
@@ -352,15 +297,20 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
assertTrustedAppRendererEvent(event);
const grant = scannedSkillRootsBySender.get(event.sender.id);
const ownerId = getCurrentDataOwnerId();
- if (!grant || !ownerId || isAppSessionBoundaryPending() || grant.ownerId !== ownerId) {
+ if (
+ !grant
+ || !ownerId
+ || isAppSessionBoundaryPending()
+ || grant.ownerId !== ownerId
+ ) {
if (grant) scannedSkillRootsBySender.delete(event.sender.id);
return null;
}
- const matchingEntries = grant.entries.filter(({ root, builtIn }) =>
+ const matchingEntries = grant.entries.filter(({ root, builtIn }) => (
builtIn
? isSameOrInside(realPathOrResolved(targetPath), root)
- : isExistingSkillPathGranted(targetPath, new Set([root])),
- );
+ : isExistingSkillPathGranted(targetPath, new Set([root]))
+ ));
const globalEntry = matchingEntries.find(({ projectRootKey: key }) => !key);
if (globalEntry) return globalEntry;
@@ -369,11 +319,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const allowedKeys = new Set(
roots.map(projectRootKey).filter((key): key is string => key !== null),
);
- return (
- matchingEntries.find(
- ({ projectRootKey: key }) => key !== undefined && allowedKeys.has(key),
- ) ?? null
- );
+ return matchingEntries.find(({ projectRootKey: key }) => (
+ key !== undefined && allowedKeys.has(key)
+ )) ?? null;
} catch {
return null;
}
@@ -381,47 +329,41 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const scanGrantDenied = () => ({
success: false as const,
- error: "path was not granted by this renderer's latest SkillHub scan",
+ error: 'path was not granted by this renderer\'s latest SkillHub scan',
});
const normalizePathForCompare = (value: string): string => {
- const withoutWindowsNamespace =
- process.platform === 'win32'
- ? value.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')
- : value;
+ const withoutWindowsNamespace = process.platform === 'win32'
+ ? value.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')
+ : value;
const normalized = path.resolve(withoutWindowsNamespace);
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
};
const realPathOrResolved = (value: string): string => {
- try {
- return normalizePathForCompare(fs.realpathSync.native(value));
- } catch {
- return normalizePathForCompare(value);
- }
+ try { return normalizePathForCompare(fs.realpathSync.native(value)); }
+ catch { return normalizePathForCompare(value); }
};
const isSameOrInside = (candidate: string, root: string): boolean => {
const relative = path.relative(root, candidate);
- return (
- relative === '' ||
- (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
+ return relative === '' || (
+ relative !== '..'
+ && !relative.startsWith(`..${path.sep}`)
+ && !path.isAbsolute(relative)
);
};
const configuredBuiltInRoot = (source: string): string | null => {
const physicalSource = realPathOrResolved(source);
- const descriptor = (options.getBuiltInSkills?.() ?? []).find(
- (skill) => realPathOrResolved(skill.absolutePath) === physicalSource,
- );
+ const descriptor = (options.getBuiltInSkills?.() ?? []).find((skill) => (
+ realPathOrResolved(skill.absolutePath) === physicalSource
+ ));
return descriptor ? realPathOrResolved(descriptor.absolutePath) : null;
};
- const isBuiltInSkillPath = (targetPath: string): boolean =>
+ const isBuiltInSkillPath = (targetPath: string): boolean => (
(options.getBuiltInSkills?.() ?? []).some((skill) => {
const root = realPathOrResolved(skill.absolutePath);
- return (
- isSameOrInside(
- normalizePathForCompare(targetPath),
- normalizePathForCompare(skill.absolutePath),
- ) || isSameOrInside(realPathOrResolved(targetPath), root)
- );
- });
+ return isSameOrInside(normalizePathForCompare(targetPath), normalizePathForCompare(skill.absolutePath))
+ || isSameOrInside(realPathOrResolved(targetPath), root);
+ })
+ );
const sweepLocalImportGrants = () => {
const now = Date.now();
@@ -458,8 +400,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const stampedPayload = { ...payload, ownerStamp: getActiveDataOwnerPushStamp() };
for (const win of BrowserWindow.getAllWindows()) {
try {
- if (isTrustedAppRendererWindow(win))
- win.webContents.send('skillhub:publish-progress', stampedPayload);
+ if (isTrustedAppRendererWindow(win)) win.webContents.send('skillhub:publish-progress', stampedPayload);
} catch {
// Window teardown can race with background scan reconciliation.
}
@@ -474,11 +415,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
}
}
};
- const publishService =
- options.publishService ??
- new SkillPublishService({
- onProgress: broadcastPublishProgress,
- });
+ const publishService = options.publishService ?? new SkillPublishService({
+ onProgress: broadcastPublishProgress,
+ });
let usageRefreshBroadcastPromise: Promise<void> | null = null;
const captureUsageDbSnapshot = (): CurrentDbClientSnapshot => {
if (isAppSessionBoundaryPending()) {
@@ -491,11 +430,11 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const assertUsageDbSnapshotCurrent = (snapshot: CurrentDbClientSnapshot): void => {
const current = getCurrentDbClientSnapshot();
if (
- isAppSessionBoundaryPending() ||
- !current ||
- current.client !== snapshot.client ||
- current.clientEpoch !== snapshot.clientEpoch ||
- current.userId !== snapshot.userId
+ isAppSessionBoundaryPending()
+ || !current
+ || current.client !== snapshot.client
+ || current.clientEpoch !== snapshot.clientEpoch
+ || current.userId !== snapshot.userId
) {
throw new Error('localDb not ready: app session switched during Skill usage query');
}
@@ -506,18 +445,15 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
usageRefreshBroadcastPromise = promise;
void promise
.catch((err) => {
- log.warn(
- '[skillhub:usage-refresh] failed:',
- err instanceof Error ? err.message : String(err),
- );
+ log.warn('[skillhub:usage-refresh] failed:', err instanceof Error ? err.message : String(err));
})
.finally(() => {
const current = getCurrentDbClientSnapshot();
if (
- !isAppSessionBoundaryPending() &&
- current?.client === snapshot.client &&
- current.clientEpoch === snapshot.clientEpoch &&
- current.userId === snapshot.userId
+ !isAppSessionBoundaryPending()
+ && current?.client === snapshot.client
+ && current.clientEpoch === snapshot.clientEpoch
+ && current.userId === snapshot.userId
) {
broadcastUsageAnalyticsRefreshed();
}
@@ -530,7 +466,10 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// 本 handler 只负责 join registry / 补 SkillhubSkill 字段 (id / projectHash)。
ipcMain.handle(
'skillhub:scan',
- async (event, params: { projects?: import('./scanner').ProjectInput[] }) => {
+ async (
+ event,
+ params: { projects?: import('./scanner').ProjectInput[] },
+ ) => {
assertTrustedAppRendererEvent(event);
ensureScanGrantCleanup(event);
const scanGeneration = (scanGenerationBySender.get(event.sender.id) ?? 0) + 1;
@@ -554,17 +493,14 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
options.getBuiltInSkills?.() ?? [],
);
if (
- scanGenerationBySender.get(event.sender.id) === scanGeneration &&
- !isAppSessionBoundaryPending() &&
- getCurrentDataOwnerId() === scanOwnerId
+ scanGenerationBySender.get(event.sender.id) === scanGeneration
+ && !isAppSessionBoundaryPending()
+ && getCurrentDataOwnerId() === scanOwnerId
) {
rememberScannedSkillRoots(event, scanOwnerId, result.skills);
const pendingCleanups = installService.listPendingUninstallCleanups();
for (const { token } of pendingCleanups) {
- cleanupGrants.set(cleanupGrantKey(event.sender.id, token), {
- ownerId: scanOwnerId,
- senderId: event.sender.id,
- });
+ cleanupGrants.set(cleanupGrantKey(event.sender.id, token), { ownerId: scanOwnerId, senderId: event.sender.id });
}
return { success: true, ...result, pendingCleanups };
}
@@ -580,57 +516,69 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// Read a single .md's markdown body (frontmatter stripped) for the detail
// view. Path validation lives in the scanner module to keep this channel
// from devolving into a generic file-read API.
- ipcMain.handle('skillhub:read-skill', async (event, params: { mdPath: string }) => {
- const grant = await findScannedSkillGrant(event, params.mdPath);
- if (!grant) return scanGrantDenied();
- return readSkillContent({
- mdPath: params.mdPath,
- ...(grant.builtIn ? { attestedRoot: grant.root } : {}),
- });
- });
+ ipcMain.handle(
+ 'skillhub:read-skill',
+ async (event, params: { mdPath: string }) => {
+ const grant = await findScannedSkillGrant(event, params.mdPath);
+ if (!grant) return scanGrantDenied();
+ return readSkillContent({
+ mdPath: params.mdPath,
+ ...(grant.builtIn ? { attestedRoot: grant.root } : {}),
+ });
+ },
+ );
// Lazy-list children of a subfolder inside a skill. The FILES panel only
// ships a one-level-deep listing in the scan result; expanding a folder
// calls back into here for its contents.
- ipcMain.handle('skillhub:list-children', async (event, params: { dirPath: string }) => {
- const grant = await findScannedSkillGrant(event, params.dirPath);
- if (!grant) return scanGrantDenied();
- return listSkillFolderChildren({
- dirPath: params.dirPath,
- ...(grant.builtIn ? { attestedRoot: grant.root } : {}),
- });
- });
+ ipcMain.handle(
+ 'skillhub:list-children',
+ async (event, params: { dirPath: string }) => {
+ const grant = await findScannedSkillGrant(event, params.dirPath);
+ if (!grant) return scanGrantDenied();
+ return listSkillFolderChildren({
+ dirPath: params.dirPath,
+ ...(grant.builtIn ? { attestedRoot: grant.root } : {}),
+ });
+ },
+ );
// Read a sibling file inside a skill folder for in-pane preview. Used
// when the user clicks a non-SKILL.md file in the FILES list.
- ipcMain.handle('skillhub:read-sibling-file', async (event, params: { filePath: string }) => {
- const grant = await findScannedSkillGrant(event, params.filePath);
- if (!grant) return scanGrantDenied();
- return readSkillSiblingFile({
- filePath: params.filePath,
- ...(grant.builtIn ? { attestedRoot: grant.root } : {}),
- });
- });
+ ipcMain.handle(
+ 'skillhub:read-sibling-file',
+ async (event, params: { filePath: string }) => {
+ const grant = await findScannedSkillGrant(event, params.filePath);
+ if (!grant) return scanGrantDenied();
+ return readSkillSiblingFile({
+ filePath: params.filePath,
+ ...(grant.builtIn ? { attestedRoot: grant.root } : {}),
+ });
+ },
+ );
// ── v0.2.2: in-app md edit ──────────────────────────────────────────────
// read-raw returns the file verbatim (frontmatter intact) so the editor
// can round-trip without losing YAML. Path whitelist covers all three
// kinds (skills / commands / agents) since the editor is opened on a
// .md across kind boundaries.
- ipcMain.handle('skillhub:read-raw', async (event, params: { filePath: string }) => {
- const grant = await findScannedSkillGrant(event, params.filePath);
- if (!grant) return scanGrantDenied();
- return readSkillRawFile({
- filePath: params.filePath,
- ...(grant.builtIn ? { attestedRoot: grant.root } : {}),
- });
- });
+ ipcMain.handle(
+ 'skillhub:read-raw',
+ async (event, params: { filePath: string }) => {
+ const grant = await findScannedSkillGrant(event, params.filePath);
+ if (!grant) return scanGrantDenied();
+ return readSkillRawFile({
+ filePath: params.filePath,
+ ...(grant.builtIn ? { attestedRoot: grant.root } : {}),
+ });
+ },
+ );
// write-file: atomic tmp+rename, file-must-exist (no creation), 1MB cap,
// realpath check defends against symlink-out-of-tree. See scanner module.
ipcMain.handle(
'skillhub:write-file',
async (event, params: { filePath: string; content: string }) => {
- if (!(await findScannedSkillGrant(event, params.filePath))) return scanGrantDenied();
+ if (!await findScannedSkillGrant(event, params.filePath)) return scanGrantDenied();
if (isBuiltInSkillPath(params.filePath)) {
return { success: false, error: 'Cindy built-in Skills are read-only' };
}
@@ -657,9 +605,8 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
'skillhub:rename-local',
async (event, params: { absolutePath: string; newName: string }) => {
const ownerScope = activeOwnerScopeKey();
- const canMutate = () =>
- ownerScope === activeOwnerScopeKey() && !isAppSessionBoundaryPending();
- if (!(await findScannedSkillGrant(event, params.absolutePath))) return scanGrantDenied();
+ const canMutate = () => ownerScope === activeOwnerScopeKey() && !isAppSessionBoundaryPending();
+ if (!await findScannedSkillGrant(event, params.absolutePath)) return scanGrantDenied();
if (isBuiltInSkillPath(params.absolutePath)) {
return { success: false, error: 'Cindy built-in Skills are read-only' };
}
@@ -701,10 +648,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
'skillhub:info',
async (_event, { name, catalogScope }: { name: string; catalogScope?: unknown }) => {
try {
- return await marketService.info(
- name,
- isSkillhubCatalogScope(catalogScope) ? catalogScope : undefined,
- );
+ return await marketService.info(name, isSkillhubCatalogScope(catalogScope) ? catalogScope : undefined);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const code = (err as { code?: string }).code;
@@ -723,9 +667,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
return await marketService.getPublishedFiles({
name: params.name,
...(params.version !== undefined ? { version: params.version } : {}),
- ...(isSkillhubCatalogScope(params.catalogScope)
- ? { catalogScope: params.catalogScope }
- : {}),
+ ...(isSkillhubCatalogScope(params.catalogScope) ? { catalogScope: params.catalogScope } : {}),
});
} catch (err) {
return skillhubIpcError(err);
@@ -735,18 +677,13 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
ipcMain.handle(
'skillhub:read-published-file',
- async (
- _event,
- params: { name: string; path: string; version?: string; catalogScope?: unknown },
- ) => {
+ async (_event, params: { name: string; path: string; version?: string; catalogScope?: unknown }) => {
try {
return await marketService.readPublishedFile({
name: params.name,
path: params.path,
...(params.version !== undefined ? { version: params.version } : {}),
- ...(isSkillhubCatalogScope(params.catalogScope)
- ? { catalogScope: params.catalogScope }
- : {}),
+ ...(isSkillhubCatalogScope(params.catalogScope) ? { catalogScope: params.catalogScope } : {}),
});
} catch (err) {
return skillhubIpcError(err);
@@ -754,32 +691,29 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
},
);
- ipcMain.handle('skillhub:list-published-versions', async (event, params: unknown) => {
- assertTrustedAppRendererEvent(event);
- const { slug, catalogScope } = reviewReadParams(params, 'name');
- const ownerScope = activeOwnerScopeKey();
- try {
- assertReviewOwnerCurrent(ownerScope);
- const result = await marketService.listPublishedVersions(slug, catalogScope);
- assertReviewOwnerCurrent(ownerScope);
- return result;
- } catch (err) {
- return skillhubIpcError(err);
- }
- });
+ ipcMain.handle(
+ 'skillhub:list-published-versions',
+ async (event, params: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const { slug, catalogScope } = reviewReadParams(params, 'name');
+ const ownerScope = activeOwnerScopeKey();
+ try {
+ assertReviewOwnerCurrent(ownerScope);
+ const result = await marketService.listPublishedVersions(slug, catalogScope);
+ assertReviewOwnerCurrent(ownerScope);
+ return result;
+ } catch (err) {
+ return skillhubIpcError(err);
+ }
+ },
+ );
ipcMain.handle(
'skillhub:update-published',
- async (
- _event,
- {
- name,
- fields,
- }: {
- name: string;
- fields: Parameters<SkillhubMarketService['updatePublished']>[1];
- },
- ) => {
+ async (_event, { name, fields }: {
+ name: string;
+ fields: Parameters<SkillhubMarketService['updatePublished']>[1];
+ }) => {
try {
return await marketService.updatePublished(name, fields);
} catch (err) {
@@ -788,31 +722,31 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
},
);
- ipcMain.handle('skillhub:delete-published', async (_event, { name }: { name: string }) => {
- try {
- return await marketService.deletePublished(name);
- } catch (err) {
- return skillhubIpcError(err);
- }
- });
+ ipcMain.handle(
+ 'skillhub:delete-published',
+ async (_event, { name }: { name: string }) => {
+ try {
+ return await marketService.deletePublished(name);
+ } catch (err) {
+ return skillhubIpcError(err);
+ }
+ },
+ );
- ipcMain.handle('skillhub:unpublish-published', async (_event, { name }: { name: string }) => {
- try {
- return await marketService.unpublishPublished(name);
- } catch (err) {
- return skillhubIpcError(err);
- }
- });
+ ipcMain.handle(
+ 'skillhub:unpublish-published',
+ async (_event, { name }: { name: string }) => {
+ try {
+ return await marketService.unpublishPublished(name);
+ } catch (err) {
+ return skillhubIpcError(err);
+ }
+ },
+ );
ipcMain.handle(
'skillhub:set-published-visibility',
- async (
- _event,
- params: Omit<
- Parameters<SkillhubMarketService['setPublishedVisibility']>[0],
- 'previousCatalogScope'
- > & { previousCatalogScope?: unknown },
- ) => {
+ async (_event, params: Omit<Parameters<SkillhubMarketService['setPublishedVisibility']>[0], 'previousCatalogScope'> & { previousCatalogScope?: unknown }) => {
try {
const { previousCatalogScope, ...fields } = params;
return await marketService.setPublishedVisibility({
@@ -838,21 +772,24 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
);
// 拉当前用户所属一级部门(PublishDialog 打开前触发,按需获取)
- ipcMain.handle('skillhub:get-my-depts', async () => {
- log.debug('get-my-depts requested');
- try {
- const result = await marketService.getMyDepts();
- log.debug('get-my-depts succeeded', {
- deptCount: result.ids.length,
- hasNames: result.names.length > 0,
- });
- return result;
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- log.warn('get-my-depts failed', message);
- return { success: false, error: message, ids: [], names: [] };
- }
- });
+ ipcMain.handle(
+ 'skillhub:get-my-depts',
+ async () => {
+ log.debug('get-my-depts requested');
+ try {
+ const result = await marketService.getMyDepts();
+ log.debug('get-my-depts succeeded', {
+ deptCount: result.ids.length,
+ hasNames: result.names.length > 0,
+ });
+ return result;
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ log.warn('get-my-depts failed', message);
+ return { success: false, error: message, ids: [], names: [] };
+ }
+ },
+ );
// Market 分类列表 — 若 broker / 网络不可用,降级空数组
ipcMain.handle(
@@ -872,31 +809,37 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
);
// 拉当前用户所属团队列表(PublishDialog 选多团队可见时触发)
- ipcMain.handle('skillhub:list-user-teams', async () => {
- try {
- return await marketService.listUserTeams();
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- log.warn('list-user-teams failed', message);
- return { success: false, error: message, teams: [] };
- }
- });
+ ipcMain.handle(
+ 'skillhub:list-user-teams',
+ async () => {
+ try {
+ return await marketService.listUserTeams();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ log.warn('list-user-teams failed', message);
+ return { success: false, error: message, teams: [] };
+ }
+ },
+ );
// 查询发布后的安全扫描状态(renderer 轮询用)
- ipcMain.handle('skillhub:get-scan-status', async (event, params: unknown) => {
- assertTrustedAppRendererEvent(event);
- const request = reviewReadParams(params, 'slug');
- const ownerScope = activeOwnerScopeKey();
- try {
- assertReviewOwnerCurrent(ownerScope);
- const result = await marketService.getScanStatus(request);
- assertReviewOwnerCurrent(ownerScope);
- return result;
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- return { success: false, error: message, status: 'unknown' };
- }
- });
+ ipcMain.handle(
+ 'skillhub:get-scan-status',
+ async (event, params: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const request = reviewReadParams(params, 'slug');
+ const ownerScope = activeOwnerScopeKey();
+ try {
+ assertReviewOwnerCurrent(ownerScope);
+ const result = await marketService.getScanStatus(request);
+ assertReviewOwnerCurrent(ownerScope);
+ return result;
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return { success: false, error: message, status: 'unknown' };
+ }
+ },
+ );
ipcMain.handle('skillhub:stop-scan-poll', () => {
publishService.stopScanPoll();
@@ -944,9 +887,12 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// 仅查 snapshot 是否存在 — DetailView 状态机判断"hash 不一致但本地无快照"用,
// 一次 fs.stat,比上面的 diff IPC 轻得多,适合每次进 detail 都打。
- ipcMain.handle('skillhub:has-snapshot', (_event, { name }: { name: string }) => {
- return { success: true, exists: snapshotExists(name) };
- });
+ ipcMain.handle(
+ 'skillhub:has-snapshot',
+ (_event, { name }: { name: string }) => {
+ return { success: true, exists: snapshotExists(name) };
+ },
+ );
// 读取单个 skill 的本地真实使用表现。只返回派生统计;原始 transcript 内容仍留在
// Claude/Codex 自己的 JSONL 文件里,不复制进 Cindy DB。
@@ -1024,17 +970,16 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
);
// 发布 skill(renderer 点"发布"按钮时触发)
- ipcMain.handle('skillhub:publish', async (event, params: PublishParams) => {
- assertTrustedAppRendererEvent(event);
- if (isBuiltInSkillPath(params.absolutePath)) {
- return {
- success: false as const,
- errorCode: 'INTERNAL' as const,
- message: 'Cindy built-in Skills cannot be published',
- };
- }
- return publishService.publish(params);
- });
+ ipcMain.handle(
+ 'skillhub:publish',
+ async (event, params: PublishParams) => {
+ assertTrustedAppRendererEvent(event);
+ if (isBuiltInSkillPath(params.absolutePath)) {
+ return { success: false as const, errorCode: 'INTERNAL' as const, message: 'Cindy built-in Skills cannot be published' };
+ }
+ return publishService.publish(params);
+ },
+ );
// 取消当前发布(renderer 点"取消"时触发)
ipcMain.handle('skillhub:cancel-publish', () => {
@@ -1043,45 +988,51 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
});
// ── Local import (zip / SKILL.md) ────────────────────────────────────────
- ipcMain.handle('skillhub:pick-local', async (event) => {
- assertTrustedAppRendererEvent(event);
- const owner = BrowserWindow.fromWebContents(event.sender);
- if (!owner || owner.isDestroyed()) {
- return { success: false, errorCode: 'INTERNAL', message: '无法打开文件选择器' };
- }
- const picked = await dialog.showOpenDialog(owner, {
- properties: ['openFile'],
- filters: [{ name: 'Skill package', extensions: ['zip', 'md'] }],
- });
- const filePath = picked.filePaths[0];
- if (picked.canceled || !filePath) {
- return { success: true, canceled: true };
- }
+ ipcMain.handle(
+ 'skillhub:pick-local',
+ async (event) => {
+ assertTrustedAppRendererEvent(event);
+ const owner = BrowserWindow.fromWebContents(event.sender);
+ if (!owner || owner.isDestroyed()) {
+ return { success: false, errorCode: 'INTERNAL', message: '无法打开文件选择器' };
+ }
+ const picked = await dialog.showOpenDialog(owner, {
+ properties: ['openFile'],
+ filters: [{ name: 'Skill package', extensions: ['zip', 'md'] }],
+ });
+ const filePath = picked.filePaths[0];
+ if (picked.canceled || !filePath) {
+ return { success: true, canceled: true };
+ }
- const inspected = await importLocalSkill.inspectLocalSkill({ filePath });
- if (!inspected.success) return inspected;
+ const inspected = await importLocalSkill.inspectLocalSkill({ filePath });
+ if (!inspected.success) return inspected;
- sweepLocalImportGrants();
- makeRoomForLocalImportGrant();
- const grantToken = randomUUID();
- localImportGrants.set(grantToken, {
- filePath,
- senderId: event.sender.id,
- expiresAt: Date.now() + LOCAL_IMPORT_GRANT_TTL_MS,
- });
- return {
- success: true,
- canceled: false,
- grantToken,
- name: inspected.name,
- description: inspected.description,
- version: inspected.version,
- };
- });
+ sweepLocalImportGrants();
+ makeRoomForLocalImportGrant();
+ const grantToken = randomUUID();
+ localImportGrants.set(grantToken, {
+ filePath,
+ senderId: event.sender.id,
+ expiresAt: Date.now() + LOCAL_IMPORT_GRANT_TTL_MS,
+ });
+ return {
+ success: true,
+ canceled: false,
+ grantToken,
+ name: inspected.name,
+ description: inspected.description,
+ version: inspected.version,
+ };
+ },
+ );
ipcMain.handle(
'skillhub:import-local',
- async (event, params: { grantToken?: unknown; installPath?: unknown; force?: unknown }) => {
+ async (
+ event,
+ params: { grantToken?: unknown; installPath?: unknown; force?: unknown },
+ ) => {
assertTrustedAppRendererEvent(event);
sweepLocalImportGrants();
if (
@@ -1127,9 +1078,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const publicParams: import('./installService').InstallParams = {
name: params.name,
...(params.version !== undefined ? { version: params.version } : {}),
- ...(isSkillhubCatalogScope(params.catalogScope)
- ? { catalogScope: params.catalogScope }
- : {}),
+ ...(isSkillhubCatalogScope(params.catalogScope) ? { catalogScope: params.catalogScope } : {}),
...(params.force !== undefined ? { force: params.force } : {}),
...(params.installPath !== undefined ? { installPath: params.installPath } : {}),
...(params.skipBackup !== undefined ? { skipBackup: params.skipBackup } : {}),
@@ -1150,71 +1099,49 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
);
// 取消正在进行的 install(按 name 索引)
- ipcMain.handle('skillhub:cancel-install', (_event, { name }: { name: string }) => {
- const ok = installService.cancelInstall(name);
- return { success: ok };
- });
-
ipcMain.handle(
- 'skillhub:set-enabled',
- async (event, params: { absolutePath: string; skillId?: string; enabled: boolean }) => {
- if (typeof params?.enabled !== 'boolean')
- throwIpcError('INVALID_PARAMS', 'Invalid Skill state');
- const record = await requireLocalSkill(event, params.absolutePath, params.skillId);
- const { skill } = record;
- if (
- skill.managedByPlugin ||
- isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())
- ) {
- throwIpcError('PRECONDITION_FAILED', 'Manage this Skill in its plugin');
- }
- const discoveryPaths = (localSkillsBySender.get(event.sender.id) ?? [])
- .filter((item) => item.physicalIdentity === record.physicalIdentity)
- .flatMap((item) => item.skill.discoveryPaths ?? [item.skill.discoveredPath]);
- const ownerId = getCurrentDataOwnerId();
- const canMutate = () => {
- if (
- ownerId !== getCurrentDataOwnerId() ||
- isAppSessionBoundaryPending() ||
- isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())
- )
- return false;
- try {
- return (
- physicalIdentity(skill.absolutePath) === record.physicalIdentity &&
- (skill.discoveryPaths ?? [skill.discoveredPath]).every(
- (alias) => physicalIdentity(alias) === record.physicalIdentity,
- )
- );
- } catch {
- return false;
- }
- };
- const release = tryAcquireSkillInstallLock(skill.name, 'market-uninstall');
- if (!release) throwIpcError('PRECONDITION_FAILED', 'Skill is being changed; retry shortly');
- try {
- await setCindySkillEnabled(skill.absolutePath, params.enabled, canMutate, discoveryPaths);
- } catch {
- throwIpcError('INTERNAL', 'Could not save Skill state; retry');
- } finally {
- release();
- }
- broadcastLocalChange();
- return { cindyEnabled: params.enabled };
+ 'skillhub:cancel-install',
+ (_event, { name }: { name: string }) => {
+ const ok = installService.cancelInstall(name);
+ return { success: ok };
},
);
+ ipcMain.handle('skillhub:set-enabled', async (event, params: { absolutePath: string; skillId?: string; enabled: boolean }) => {
+ if (typeof params?.enabled !== 'boolean') throwIpcError('INVALID_PARAMS', 'Invalid Skill state');
+ const record = await requireLocalSkill(event, params.absolutePath, params.skillId);
+ const { skill } = record;
+ if (skill.managedByPlugin || isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())) {
+ throwIpcError('PRECONDITION_FAILED', 'Manage this Skill in its plugin');
+ }
+ const discoveryPaths = (localSkillsBySender.get(event.sender.id) ?? [])
+ .filter((item) => item.physicalIdentity === record.physicalIdentity)
+ .flatMap((item) => item.skill.discoveryPaths ?? [item.skill.discoveredPath]);
+ const ownerId = getCurrentDataOwnerId();
+ const canMutate = () => {
+ if (ownerId !== getCurrentDataOwnerId() || isAppSessionBoundaryPending()
+ || isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())) return false;
+ try {
+ return physicalIdentity(skill.absolutePath) === record.physicalIdentity
+ && (skill.discoveryPaths ?? [skill.discoveredPath]).every((alias) => physicalIdentity(alias) === record.physicalIdentity);
+ } catch { return false; }
+ };
+ const release = tryAcquireSkillInstallLock(skill.name, 'market-uninstall');
+ if (!release) throwIpcError('PRECONDITION_FAILED', 'Skill is being changed; retry shortly');
+ try {
+ await setCindySkillEnabled(skill.absolutePath, params.enabled, canMutate, discoveryPaths);
+ } catch { throwIpcError('INTERNAL', 'Could not save Skill state; retry'); }
+ finally { release(); }
+ broadcastLocalChange();
+ return { cindyEnabled: params.enabled };
+ });
+
// Main resolves the exact scanned entity; no arbitrary renderer path deletion.
ipcMain.handle(
'skillhub:uninstall',
async (event, { absolutePath, skillId }: { absolutePath: string; skillId?: string }) => {
const { target, skill } = await requireLocalSkill(event, absolutePath, skillId);
- if (
- skill.builtIn ||
- !target ||
- !isLocalSkillTargetCurrent(target) ||
- isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots())
- ) {
+ if (skill.builtIn || !target || !isLocalSkillTargetCurrent(target) || isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots())) {
throwIpcError('PRECONDITION_FAILED', 'Skill cannot be uninstalled; refresh and retry');
}
const ownerId = getCurrentDataOwnerId();
@@ -1233,53 +1160,28 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
title: t('skillhub.detail.uninstallDialog.title').replace('{{name}}', () => skill.name),
message: t('skillhub.detail.uninstallDialog.title').replace('{{name}}', () => skill.name),
detail: [
- t(
- target.linkOnly
- ? 'skillhub.management.unlinkDescription'
- : 'skillhub.management.trashDescription',
- ),
- t(
- skill.scope === 'project'
- ? 'skillhub.management.projectScope'
- : 'skillhub.management.globalScope',
- ).replace('{{project}}', () => skill.projectRoot ?? ''),
- t('skillhub.management.sharedImpact'),
- target.operationPath,
+ t(target.linkOnly ? 'skillhub.management.unlinkDescription' : 'skillhub.management.trashDescription'),
+ t(skill.scope === 'project' ? 'skillhub.management.projectScope' : 'skillhub.management.globalScope')
+ .replace('{{project}}', () => skill.projectRoot ?? ''),
+ t('skillhub.management.sharedImpact'), target.operationPath,
].join('\n\n'),
- buttons: [
- t('skillhub.detail.uninstallDialog.confirm'),
- t('skillhub.detail.uninstallDialog.cancel'),
- ],
- defaultId: 1,
- cancelId: 1,
- noLink: true,
+ buttons: [t('skillhub.detail.uninstallDialog.confirm'), t('skillhub.detail.uninstallDialog.cancel')],
+ defaultId: 1, cancelId: 1, noLink: true,
}));
- } catch {
- throwIpcError('INTERNAL', 'Could not confirm Skill uninstall; retry');
- } finally {
- uninstallConfirmations.delete(event.sender.id);
- }
+ } catch { throwIpcError('INTERNAL', 'Could not confirm Skill uninstall; retry'); }
+ finally { uninstallConfirmations.delete(event.sender.id); }
if (response !== 0) return { success: false, errorCode: 'CANCELLED', message: '' };
const current = await requireLocalSkill(event, absolutePath, skillId);
- const approvalCurrent = () =>
- !parent.isDestroyed() &&
- cleanupGeneration === (cleanupGenerationBySender.get(event.sender) ?? 0) &&
- ownerId === getCurrentDataOwnerId() &&
- !isAppSessionBoundaryPending();
- if (
- !approvalCurrent() ||
- current.target?.identity !== target.identity ||
- JSON.stringify(current.target.aliases) !== JSON.stringify(target.aliases)
- ) {
+ const approvalCurrent = () => !parent.isDestroyed()
+ && cleanupGeneration === (cleanupGenerationBySender.get(event.sender) ?? 0)
+ && ownerId === getCurrentDataOwnerId() && !isAppSessionBoundaryPending();
+ if (!approvalCurrent() || current.target?.identity !== target.identity
+ || JSON.stringify(current.target.aliases) !== JSON.stringify(target.aliases)) {
throwIpcError('PRECONDITION_FAILED', 'Skill confirmation expired; refresh and retry');
}
- const result = await installService.uninstall(
- absolutePath,
- target,
- () =>
- approvalCurrent() &&
- !isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots()),
- );
+ const result = await installService.uninstall(absolutePath, target,
+ () => approvalCurrent()
+ && !isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots()));
if (!result.success) {
// A failed trash/preparation can still leave durable rollback work.
broadcastLocalChange();
@@ -1291,15 +1193,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
if (!approvalCurrent()) {
return { success: true };
}
- cleanupGrants.set(cleanupGrantKey(event.sender.id, result.cleanupToken), {
- ownerId,
- senderId: event.sender.id,
- });
+ cleanupGrants.set(cleanupGrantKey(event.sender.id, result.cleanupToken), { ownerId, senderId: event.sender.id });
}
- return {
- success: true,
- ...(result.cleanupToken ? { cleanupToken: result.cleanupToken } : {}),
- };
+ return { success: true, ...(result.cleanupToken ? { cleanupToken: result.cleanupToken } : {}) };
},
);
@@ -1307,12 +1203,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
assertTrustedAppRendererEvent(event);
const key = cleanupGrantKey(event.sender.id, token);
const grant = cleanupGrants.get(key);
- const canMutate = () =>
- !!grant &&
- grant.ownerId === getCurrentDataOwnerId() &&
- cleanupGrants.get(key) === grant &&
- grant.senderId === event.sender.id &&
- !isAppSessionBoundaryPending();
+ const canMutate = () => !!grant && grant.ownerId === getCurrentDataOwnerId()
+ && cleanupGrants.get(key) === grant
+ && grant.senderId === event.sender.id && !isAppSessionBoundaryPending();
if (!canMutate()) throwIpcError('PRECONDITION_FAILED', 'Cleanup is no longer available');
const complete = await installService.retryUninstallCleanup(token, canMutate);
if (complete) cleanupGrants.delete(key);
@@ -1334,13 +1227,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
{
items,
}: {
- items: Array<{
- name: string;
- absolutePath: string;
- version: string;
- authorId: string;
- folderHash?: string;
- }>;
+ items: Array<{ name: string; absolutePath: string; version: string; authorId: string; folderHash?: string }>;
},
) => {
return reconcileMineRegistry(items);
@@ -1348,16 +1235,19 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
);
// ── SkillHub Registry IPC(v0.6 重构新增) ────────────────────────────────
- ipcMain.handle('skillhub:registry:get-by-name', async (_event, { name }: { name: string }) => {
- try {
- const manifest = await registryService.readManifest(name);
- return { success: true, manifest };
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- log.error('[skillhub:registry:get-by-name] failed:', err);
- return { success: false, error: message };
- }
- });
+ ipcMain.handle(
+ 'skillhub:registry:get-by-name',
+ async (_event, { name }: { name: string }) => {
+ try {
+ const manifest = await registryService.readManifest(name);
+ return { success: true, manifest };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ log.error('[skillhub:registry:get-by-name] failed:', err);
+ return { success: false, error: message };
+ }
+ },
+ );
}
function isLocalDbNotReady(err: unknown): boolean {
@@ -1365,9 +1255,7 @@ function isLocalDbNotReady(err: unknown): boolean {
return /localDb not ready/i.test(message);
}
-async function ensureSkillUsageLocalDbReady(): Promise<
- { success: true } | { success: false; error: string }
-> {
+async function ensureSkillUsageLocalDbReady(): Promise<{ success: true } | { success: false; error: string }> {
if (isAppSessionBoundaryPending()) {
return { success: false, error: 'localDb not ready: app session is switching' };
}
diff --git a/apps/desktop/src/main/skillhub/scanner.ts b/apps/desktop/src/main/skillhub/scanner.ts
index 818a066602..00e435b50d 100644
--- a/apps/desktop/src/main/skillhub/scanner.ts
+++ b/apps/desktop/src/main/skillhub/scanner.ts
@@ -118,7 +118,9 @@ export interface Skill {
}
export type SourceStatus =
- { state: 'ok'; count: number } | { state: 'missing' } | { state: 'error'; message: string };
+ | { state: 'ok'; count: number }
+ | { state: 'missing' }
+ | { state: 'error'; message: string };
export interface SourceReport {
kind: SkillKind;
@@ -177,7 +179,10 @@ function realPathOrNormalized(value: string): string {
}
function normalizeSkillEntityPath(c: AgentCustomization): AgentCustomization {
- if (c.kind === 'skill' && path.basename(c.absolutePath).toLowerCase() === 'skill.md') {
+ if (
+ c.kind === 'skill' &&
+ path.basename(c.absolutePath).toLowerCase() === 'skill.md'
+ ) {
return {
...c,
absolutePath: path.dirname(c.absolutePath),
@@ -187,10 +192,7 @@ function normalizeSkillEntityPath(c: AgentCustomization): AgentCustomization {
return c;
}
-function filterSkillPackageFileEntries(
- rootDir: string,
- entries: SkillFileEntry[],
-): SkillFileEntry[] {
+function filterSkillPackageFileEntries(rootDir: string, entries: SkillFileEntry[]): SkillFileEntry[] {
return entries.filter((entry) => {
const childPath = path.join(rootDir, entry.name);
return !isIgnoredSkillPackagePath(skillPackageRelPath(rootDir, childPath, entry.name));
@@ -212,13 +214,9 @@ function readBuiltInCustomization(descriptor: BuiltInSkillDescriptor): AgentCust
} catch (error) {
parseError = error instanceof Error ? error.message : String(error);
}
- const files = fs
- .readdirSync(descriptor.absolutePath, { withFileTypes: true })
+ const files = fs.readdirSync(descriptor.absolutePath, { withFileTypes: true })
.sort((a, b) => a.name.localeCompare(b.name))
- .map((entry) => ({
- name: entry.name,
- kind: entry.isDirectory() ? ('dir' as const) : ('file' as const),
- }));
+ .map((entry) => ({ name: entry.name, kind: entry.isDirectory() ? 'dir' as const : 'file' as const }));
return {
engine: 'claude-code',
kind: 'skill',
@@ -310,10 +308,7 @@ 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[]; realPath: string }
- >();
+ 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;
@@ -346,11 +341,10 @@ export async function scanAllSkills(
// used as fallback cwd. If the workingDir doesn't map to a tracked project,
// treat the skill as global — it's effectively user-level.
const rawScope = normalizeScope(engine, c.scope);
- const scope: SkillScope = rawScope === 'project' && !projectHash ? 'global' : rawScope;
- const urlKey =
- scope === 'global'
- ? `${c.kind}:global:${canonicalName}`
- : `${c.kind}:project:${projectHash}:${canonicalName}`;
+ const scope: SkillScope = (rawScope === 'project' && !projectHash) ? 'global' : rawScope;
+ const urlKey = scope === 'global'
+ ? `${c.kind}:global:${canonicalName}`
+ : `${c.kind}:project:${projectHash}:${canonicalName}`;
return { c, all, realPath, engine, project, projectHash, canonicalName, scope, urlKey };
});
const identityCounts = new Map<string, number>();
@@ -359,75 +353,75 @@ export async function scanAllSkills(
identityCounts.set(identity, (identityCounts.get(identity) ?? 0) + 1);
}
- const skills: Skill[] = candidates.map(
- ({ c, all, realPath, engine, project, projectHash, canonicalName, scope, urlKey }) => {
- const builtIn = builtInRealPaths.has(realPath);
- 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;
- if (!engineSet.has(eng)) {
- engineSet.set(eng, {
- engine: eng,
- label: eng === 'claude-code' ? 'Claude' : eng === 'codex' ? 'Codex' : 'Pi',
- ...(item.runtimeStatus ? { runtimeStatus: item.runtimeStatus } : {}),
- });
- }
+ const skills: Skill[] = candidates.map(({
+ c,
+ all,
+ realPath,
+ engine,
+ project,
+ projectHash,
+ canonicalName,
+ scope,
+ urlKey,
+ }) => {
+ const builtIn = builtInRealPaths.has(realPath);
+ 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;
+ if (!engineSet.has(eng)) {
+ engineSet.set(eng, {
+ engine: eng,
+ label: eng === 'claude-code' ? 'Claude' : eng === 'codex' ? 'Codex' : 'Pi',
+ ...(item.runtimeStatus ? { runtimeStatus: item.runtimeStatus } : {}),
+ });
}
- const linkedEngines = builtIn
- ? Array.from(discoveredEnginesByRealPath.get(realPath)?.values() ?? [])
- : Array.from(engineSet.values());
-
- const skill: Skill = {
- id,
- urlKey,
- ...(sourceKey ? { sourceKey } : {}),
- ...(hasIdentityCollision ? { requiresSourceKey: true } : {}),
- engine,
- linkedEngines,
- kind: c.kind as SkillKind,
- scope,
- name: canonicalName,
- description: c.description,
- absolutePath: realPath,
- discoveredPath: c.absolutePath,
- mdPath: c.mdPath ?? realPath,
- files:
- c.kind === 'skill'
- ? filterSkillPackageFileEntries(realPath, (c.files ?? []) as SkillFileEntry[])
- : [],
- frontmatter: c.frontmatter,
- parseError: c.parseError,
- registryEntry: null, // 下面 join 阶段填
- ...(c.kind === 'skill'
- ? (() => {
- const discoveryPaths = [...new Set(all.map((item) => item.absolutePath))];
- const target = inspectLocalSkillTarget(realPath, discoveryPaths, managedSkillRoots);
- return {
- cindyEnabled: isCindySkillEnabled(realPath),
- discoveryPaths,
- ...(builtIn ? { builtIn: true } : {}),
- managedByPlugin: isPluginManagedSkillPath(realPath, managedSkillRoots),
- canUninstall: !builtIn && target !== null,
- uninstallLinkOnly: target?.linkOnly ?? false,
- };
- })()
- : {}),
- ...(project ? { projectRoot: project.projectRoot } : {}),
- ...(projectHash ? { projectHash } : {}),
- };
- return skill;
- },
- );
+ }
+ const linkedEngines = builtIn
+ ? Array.from(discoveredEnginesByRealPath.get(realPath)?.values() ?? [])
+ : Array.from(engineSet.values());
+
+ const skill: Skill = {
+ id,
+ urlKey,
+ ...(sourceKey ? { sourceKey } : {}),
+ ...(hasIdentityCollision ? { requiresSourceKey: true } : {}),
+ engine,
+ linkedEngines,
+ kind: c.kind as SkillKind,
+ scope,
+ name: canonicalName,
+ description: c.description,
+ absolutePath: realPath,
+ discoveredPath: c.absolutePath,
+ mdPath: c.mdPath ?? realPath,
+ files: c.kind === 'skill'
+ ? filterSkillPackageFileEntries(realPath, (c.files ?? []) as SkillFileEntry[])
+ : [],
+ frontmatter: c.frontmatter,
+ parseError: c.parseError,
+ registryEntry: null, // 下面 join 阶段填
+ ...(c.kind === 'skill' ? (() => {
+ const discoveryPaths = [...new Set(all.map((item) => item.absolutePath))];
+ const target = inspectLocalSkillTarget(realPath, discoveryPaths, managedSkillRoots);
+ return { cindyEnabled: isCindySkillEnabled(realPath), discoveryPaths,
+ ...(builtIn ? { builtIn: true } : {}),
+ managedByPlugin: isPluginManagedSkillPath(realPath, managedSkillRoots),
+ canUninstall: !builtIn && target !== null, uninstallLinkOnly: target?.linkOnly ?? false };
+ })() : {}),
+ ...(project ? { projectRoot: project.projectRoot } : {}),
+ ...(projectHash ? { projectHash } : {}),
+ };
+ return skill;
+ });
// ── join registry ──────────────────────────────────────────────────────────
let registryEntries: Awaited<ReturnType<typeof registryService.listAllInstalls>>;
@@ -472,12 +466,10 @@ export async function scanAllSkills(
// Maintenance uses the same mutation protocol as install/uninstall and
// revalidates each registry/source snapshot after acquiring the lease.
- void Promise.all(
- registryEntries.map((record) => {
- const key = path.normalize(record.installPath);
- return reconcileScannedInstall(record, !liveRealPaths.has(registryLiveKeys.get(key) ?? key));
- }),
- );
+ void Promise.all(registryEntries.map((record) => {
+ const key = path.normalize(record.installPath);
+ return reconcileScannedInstall(record, !liveRealPaths.has(registryLiveKeys.get(key) ?? key));
+ }));
// ── sources[] 兼容 (renderer 只存不读) ─────────────────────────────────────
const sources: SourceReport[] = listed.errors.map((e) => ({
@@ -543,10 +535,7 @@ export async function readSkillContent(params: { mdPath: string; attestedRoot?:
*/
const PREVIEW_SIZE_CAP = 1024 * 1024; // 1 MB
-export async function readSkillSiblingFile(params: {
- filePath: string;
- attestedRoot?: string;
-}): Promise<{
+export async function readSkillSiblingFile(params: { filePath: string; attestedRoot?: string }): Promise<{
success: boolean;
content?: string;
error?: string;
@@ -571,10 +560,7 @@ export async function readSkillSiblingFile(params: {
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,无法在面板中预览`,
- };
+ return { success: false, error: `文件超过 ${Math.round(PREVIEW_SIZE_CAP / 1024)} KB,无法在面板中预览` };
}
const content = fs.readFileSync(resolvedFilePath, 'utf-8');
return { success: true, content };
@@ -593,10 +579,7 @@ export async function readSkillSiblingFile(params: {
* — only paths within a skill folder are accepted, so commands / agents
* (single .md files) can't trigger directory traversal here.
*/
-export async function listSkillFolderChildren(params: {
- dirPath: string;
- attestedRoot?: string;
-}): Promise<{
+export async function listSkillFolderChildren(params: { dirPath: string; attestedRoot?: string }): Promise<{
success: boolean;
entries?: SkillFileEntry[];
error?: string;
@@ -648,13 +631,12 @@ export async function listSkillFolderChildren(params: {
// readSkillContent for view (frontmatter stripped) and readRawFile here for
// edit (frontmatter intact). Writes are gated by SKILL_PATH_WHITELIST.
-const EDIT_SIZE_CAP_READ = 256 * 1024; // 256 KB read cap (matches detail-view edit-button gate)
+const EDIT_SIZE_CAP_READ = 256 * 1024; // 256 KB read cap (matches detail-view edit-button gate)
const EDIT_SIZE_CAP_WRITE = 1024 * 1024; // 1 MB write cap (defensive against paste-of-binary)
// 统一白名单:所有引擎的 skill/command/agent 目录共用。
// 新增引擎时只需在此 regex 加一个分支。
-const SKILL_PATH_WHITELIST =
- /\/(\.(claude\/(skills|commands|agents)|agents\/skills|codex\/skills|pi\/skills)|codex-home\/skills)\//;
+const SKILL_PATH_WHITELIST = /\/(\.(claude\/(skills|commands|agents)|agents\/skills|codex\/skills|pi\/skills)|codex-home\/skills)\//;
function isLexicallyAllowedSkillPath(absolutePath: string): boolean {
// path.resolve 解析 .. 和 . 段,防止遍历绕过白名单
@@ -664,9 +646,10 @@ function isLexicallyAllowedSkillPath(absolutePath: string): boolean {
function isPathWithin(root: string, candidate: string): boolean {
const relative = path.relative(root, candidate);
- return (
- relative === '' ||
- (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
+ return relative === '' || (
+ relative !== '..'
+ && !relative.startsWith(`..${path.sep}`)
+ && !path.isAbsolute(relative)
);
}
@@ -696,8 +679,10 @@ function resolveAllowedExistingSkillPath(absolutePath: string): string | null {
try {
const realProjectRoot = fs.realpathSync.native(lexicalProjectRoot);
const realSkillRoot = fs.realpathSync.native(lexicalSkillRoot);
- if (!isPathWithin(realProjectRoot, realSkillRoot) || !isPathWithin(realSkillRoot, realTarget))
- return null;
+ if (
+ !isPathWithin(realProjectRoot, realSkillRoot)
+ || !isPathWithin(realSkillRoot, realTarget)
+ ) return null;
} catch {
return null;
}
@@ -750,10 +735,7 @@ export function isExistingSkillPathGranted(
function findSkillRootForPath(absolutePath: string): string | null {
const norm = path.resolve(absolutePath).replace(/\\/g, '/');
- const markerMatch =
- /\/(?:\.claude\/(?:skills|commands|agents)|\.agents\/skills|\.codex\/skills|\.pi\/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);
@@ -763,11 +745,7 @@ function findSkillRootForPath(absolutePath: string): string | null {
return norm.slice(0, (markerMatch.index ?? 0) + markerMatch[0].length) + skillName;
}
-function skillPackageRelPath(
- rootDir: string | null,
- childPath: string,
- fallbackName: string,
-): string {
+function skillPackageRelPath(rootDir: string | null, childPath: string, fallbackName: string): string {
if (!rootDir) return fallbackName;
const rel = path.relative(rootDir, childPath).split(path.sep).join('/');
return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : fallbackName;
@@ -776,21 +754,12 @@ function skillPackageRelPath(
function isIgnoredSkillFilePath(filePath: string, attestedRoot?: string): boolean {
let skillRoot = attestedRoot ?? findSkillRootForPath(filePath);
if (attestedRoot) {
- try {
- skillRoot = fs.realpathSync.native(attestedRoot);
- } catch {
- return true;
- }
+ try { skillRoot = fs.realpathSync.native(attestedRoot); } catch { return true; }
}
- return isIgnoredSkillPackagePath(
- skillPackageRelPath(skillRoot, filePath, path.basename(filePath)),
- );
+ return isIgnoredSkillPackagePath(skillPackageRelPath(skillRoot, filePath, path.basename(filePath)));
}
-export async function readSkillRawFile(params: {
- filePath: string;
- attestedRoot?: string;
-}): Promise<{
+export async function readSkillRawFile(params: { filePath: string; attestedRoot?: string }): Promise<{
success: boolean;
content?: string;
error?: string;
@@ -814,10 +783,7 @@ export async function readSkillRawFile(params: {
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,请用外部编辑器`,
- };
+ return { success: false, error: `文件超过 ${Math.round(EDIT_SIZE_CAP_READ / 1024)} KB,请用外部编辑器` };
}
const content = fs.readFileSync(resolvedFilePath, 'utf-8');
return { success: true, content };
@@ -869,10 +835,7 @@ export async function writeSkillFile(params: { filePath: string; content: string
}
const byteLen = Buffer.byteLength(content, 'utf-8');
if (byteLen > EDIT_SIZE_CAP_WRITE) {
- return {
- success: false,
- error: `内容超过 ${Math.round(EDIT_SIZE_CAP_WRITE / 1024)} KB,拒绝写入`,
- };
+ return { success: false, error: `内容超过 ${Math.round(EDIT_SIZE_CAP_WRITE / 1024)} KB,拒绝写入` };
}
// 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.
@@ -889,11 +852,7 @@ export async function writeSkillFile(params: { filePath: string; content: string
return { success: true };
} catch (err) {
// Best-effort tmp cleanup — ignore failures.
- try {
- fs.unlinkSync(tmpPath);
- } catch {
- /* noop */
- }
+ try { fs.unlinkSync(tmpPath); } catch { /* noop */ }
return { success: false, error: err instanceof Error ? err.message : String(err) };
}
}
@@ -906,13 +865,10 @@ export async function writeSkillFile(params: { filePath: string; content: string
*
* 仅支持 kind=skill (folder-shaped). command/agent 是单 .md 文件,本期不需要。
*/
-export async function renameLocalSkill(
- params: {
- absolutePath: string;
- newName: string;
- },
- canMutate: () => boolean = () => true,
-): Promise<{ success: true; newAbsolutePath: string } | { success: false; error: string }> {
+export async function renameLocalSkill(params: {
+ absolutePath: string;
+ newName: string;
+}, canMutate: () => boolean = () => true): Promise<{ success: true; newAbsolutePath: string } | { success: false; error: string }> {
const { absolutePath, newName } = params;
if (!absolutePath || !path.isAbsolute(absolutePath)) {
@@ -988,8 +944,7 @@ export async function renameLocalSkill(
let releaseShared: SkillMutationRelease | null = null;
try {
releaseShared = await acquireSharedSkillMutationLease([oldName, newName]);
- if (!releaseShared)
- return { success: false, error: 'Skill is busy; retry after the current operation' };
+ if (!releaseShared) return { success: false, error: 'Skill is busy; retry after the current operation' };
await renameSkillWithActivation(absolutePath, newAbsolutePath, () => {
if (!canMutate()) throw new Error('Skill mutation context changed');
// Recheck after waiting for the preferences lock; never replace a new entity.
@@ -998,40 +953,25 @@ export async function renameLocalSkill(
throw new Error('Skill changed; refresh and retry');
}
const currentMd = fs.lstatSync(oldSkillMd);
- if (
- currentMd.isSymbolicLink() ||
- currentMd.dev !== skillMdStat.dev ||
- currentMd.ino !== skillMdStat.ino
- ) {
+ if (currentMd.isSymbolicLink() || currentMd.dev !== skillMdStat.dev || currentMd.ino !== skillMdStat.ino) {
throw new Error('Skill content changed; refresh and retry');
}
const parsed = matter(fs.readFileSync(oldSkillMd, 'utf-8'));
- const data = (parsed.data && typeof parsed.data === 'object' ? parsed.data : {}) as Record<
- string,
- unknown
- >;
+ const data = (parsed.data && typeof parsed.data === 'object' ? parsed.data : {}) as Record<string, unknown>;
data.name = newName;
const next = matter.stringify(parsed.content, data);
fs.renameSync(absolutePath, newAbsolutePath);
renamed = true;
const fd = fs.openSync(tmpPath, 'w');
- try {
- fs.writeSync(fd, next);
- fs.fsyncSync(fd);
- } finally {
- fs.closeSync(fd);
- }
+ try { fs.writeSync(fd, next); fs.fsyncSync(fd); }
+ finally { fs.closeSync(fd); }
fs.renameSync(newSkillMd, backupPath);
backedUp = true;
fs.renameSync(tmpPath, newSkillMd);
});
// packageIgnore excludes this reserved backup from browsing, hashes,
// snapshots and ZIPs even if Windows keeps it locked after commit.
- try {
- fs.unlinkSync(backupPath);
- } catch {
- /* Do not roll back committed preferences. */
- }
+ try { fs.unlinkSync(backupPath); } catch { /* Do not roll back committed preferences. */ }
return { success: true, newAbsolutePath };
} catch (err) {
if (renamed) {
@@ -1039,17 +979,10 @@ export async function renameLocalSkill(
// Keep the original file until preferences commit, so even a full disk
// can roll back with renames instead of writing the contents again.
if (backedUp) fs.renameSync(backupPath, newSkillMd);
- try {
- fs.unlinkSync(tmpPath);
- } catch {
- /* No staging file after a completed switch. */
- }
+ try { fs.unlinkSync(tmpPath); } catch { /* No staging file after a completed switch. */ }
fs.renameSync(newAbsolutePath, absolutePath);
} catch (rollbackError) {
- return {
- success: false,
- error: `Skill rename and rollback failed: ${String(rollbackError)}`,
- };
+ return { success: false, error: `Skill rename and rollback failed: ${String(rollbackError)}` };
}
}
return { success: false, error: `Skill rename failed: ${String(err)}` };