Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(skillhub): 按企业部门策略自动安装技能 (#4815)

此间少年abe0601dbd26
diff --git a/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterUtilityProcess.test.ts b/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterUtilityProcess.test.ts
index 472778bbba..2c580f038c 100644
--- a/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterUtilityProcess.test.ts
+++ b/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterUtilityProcess.test.ts
@@ -237,6 +237,7 @@ describe('docs output cwd-bound writer', () => {
[
'--import',
tsxLoader,
+ '--input-type=module',
'-e',
`
const fs = (await import('node:fs')).default;
diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/loopbackListener.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/loopbackListener.test.ts
index 9d520ece52..108d033ec6 100644
--- a/apps/desktop/src/main/plugin-oauth/__tests__/loopbackListener.test.ts
+++ b/apps/desktop/src/main/plugin-oauth/__tests__/loopbackListener.test.ts
@@ -12,13 +12,18 @@ beforeEach(() => {
});
const state = 's'.repeat(43);
const resources: Array<{ close(): unknown }> = [];
-afterEach(() => {
- for (const resource of resources.splice(0)) resource.close();
- for (const server of sockets.servers.values()) {
- server.close();
- server.closeAllConnections();
+afterEach(async () => {
+ try {
+ await Promise.all([...resources.splice(0), ...sockets.servers.values()].map((resource) => {
+ if (!(resource instanceof http.Server)) return resource.close();
+ return new Promise<void>((resolve) => {
+ resource.close(() => resolve());
+ resource.closeAllConnections();
+ });
+ }));
+ } finally {
+ vi.restoreAllMocks();
}
- vi.restoreAllMocks();
});
function offer(port: number, hostname = 'localhost'): PluginOauthOffer {
@@ -68,8 +73,9 @@ it.each(['127.0.0.1', '::1'])(
const other = first === '::1' ? '127.0.0.1' : '::1';
expect(await request(other, port)).toBe(409);
expect(deliver).toHaveBeenCalledExactlyOnceWith({ state, error: 'access_denied' });
- listener.close();
- listener.close();
+ const closing = listener.close();
+ expect(listener.close()).toBe(closing);
+ await closing;
// Both ports are released, including on an idempotent cancellation.
expect([...sockets.servers.values()].every((server) => !server.listening)).toBe(true);
},
@@ -210,3 +216,38 @@ it.each(['EAFNOSUPPORT', 'EADDRNOTAVAIL'])(
).rejects.toThrow('OAUTH_BRIDGE_UNAVAILABLE');
},
);
+
+it('waits for both server close callbacks, including repeated cancellation', async () => {
+ const port = 12345;
+ const listener = await listenForOauthCallback(offer(port), async () => {}, () => {});
+ resources.push(listener);
+ const original = http.Server.prototype.close;
+ const completions: Array<() => void> = [];
+ vi.spyOn(http.Server.prototype, 'close').mockImplementation(function (
+ this: http.Server,
+ callback?: (error?: Error) => void,
+ ) {
+ return original.call(this, (error) => {
+ completions.push(() => callback?.(error));
+ });
+ });
+ let finished = false;
+ const closing = listener.close();
+ try {
+ expect(closing).toBeInstanceOf(Promise);
+ expect(listener.close()).toBe(closing);
+ void closing.then(() => { finished = true; });
+ await vi.waitFor(() => expect(completions).toHaveLength(2));
+ expect(finished).toBe(false);
+ completions.shift()!();
+ await Promise.resolve();
+ expect(finished).toBe(false);
+ completions.shift()!();
+ await closing;
+ expect(finished).toBe(true);
+ } finally {
+ vi.restoreAllMocks();
+ for (const complete of completions.splice(0)) complete();
+ }
+ expect([...sockets.servers.values()].every((server) => !server.listening)).toBe(true);
+});
diff --git a/apps/desktop/src/main/plugin-oauth/loopbackListener.ts b/apps/desktop/src/main/plugin-oauth/loopbackListener.ts
index 5e6b1d7646..98fbdea56e 100644
--- a/apps/desktop/src/main/plugin-oauth/loopbackListener.ts
+++ b/apps/desktop/src/main/plugin-oauth/loopbackListener.ts
@@ -20,7 +20,7 @@ export async function listenForOauthCallback(
deliver: (value: PluginOauthCallback) => Promise<void>,
assertCurrent: () => void,
expectedState: string = offer.state,
-): Promise<{ close(): void }> {
+): Promise<{ close(): Promise<void> }> {
const endpoint = new URL(offer.callbackUrl);
let consumed = false;
let closed = false;
@@ -131,13 +131,17 @@ export async function listenForOauthCallback(
reply(410);
}
};
- const close = () => {
- if (closed) return;
+ let closing: Promise<void> | undefined;
+ const close = (): Promise<void> => {
+ if (closing) return closing;
closed = true;
- for (const server of servers) {
- server.close();
+ // Stop accepting callbacks immediately, but let callers wait until both
+ // families have released their sockets before reusing the callback port.
+ closing = Promise.all(servers.map((server) => new Promise<void>((resolve) => {
+ server.close(() => resolve());
server.closeAllConnections();
- }
+ }))).then(() => {});
+ return closing;
};
try {
for (const host of hosts) {
@@ -173,7 +177,7 @@ export async function listenForOauthCallback(
ready = true;
return { close };
} catch {
- close();
+ await close();
throw fail();
}
}
diff --git a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
index c682e85589..b819e4fb5a 100644
--- a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
@@ -112,7 +112,7 @@ describe('Skill activation preferences', () => {
const descriptor = (await import('../../maker-host/built-in-skills')).builtInSkillDescriptors(root, root)[0]!;
fs.mkdirSync(descriptor.absolutePath, { recursive: true });
fs.mkdirSync(path.dirname(descriptor.nativeClaudePath), { recursive: true });
- fs.rmSync(descriptor.nativeClaudePath, { force: true });
+ fs.rmSync(descriptor.nativeClaudePath, { recursive: true, force: true });
fs.symlinkSync(
descriptor.absolutePath,
descriptor.nativeClaudePath,
diff --git a/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts b/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts
index fecd9ee81e..567ae1e29c 100644
--- a/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts
@@ -153,6 +153,43 @@ function makeService(options: {
}
describe('SkillhubAutoSyncService', () => {
+ it('refreshes department policies after signing out and back into the same identity', async () => {
+ const setup = makeService({ configSkills: [] });
+ await setup.service.runOnceAfterLogin();
+ await setup.service.runOnceAfterLogin();
+ expect(setup.fetchConfig).toHaveBeenCalledTimes(1);
+ setup.service.cancelInFlight();
+ await setup.service.runOnceAfterLogin();
+ expect(setup.fetchConfig).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not restore completion when cancellation precedes auth cleanup', async () => {
+ let release!: (value: []) => void;
+ const setup = makeService({ fetchConfigImpl: () => new Promise<[]>((resolve) => { release = resolve; }) });
+ const first = setup.service.runOnceAfterLogin();
+ await vi.waitFor(() => expect(setup.fetchConfig).toHaveBeenCalledTimes(1));
+ setup.service.cancelInFlight();
+ release([]);
+ await first;
+ expect(setup.recordCandidateSkills).not.toHaveBeenCalled();
+ setup.fetchConfig.mockResolvedValue([]);
+ await setup.service.runOnceAfterLogin();
+ expect(setup.fetchConfig).toHaveBeenCalledTimes(2);
+ });
+
+ it('queues same-account login behind a cancelled pending run', async () => {
+ let release!: (value: []) => void;
+ const setup = makeService({ fetchConfigImpl: () => new Promise<[]>((resolve) => { release = resolve; }) });
+ const first = setup.service.runOnceAfterLogin();
+ await vi.waitFor(() => expect(setup.fetchConfig).toHaveBeenCalledTimes(1));
+ setup.service.cancelInFlight();
+ setup.fetchConfig.mockResolvedValue([]);
+ const relogin = setup.service.runOnceAfterLogin();
+ release([]);
+ await Promise.all([first, relogin]);
+ expect(setup.fetchConfig).toHaveBeenCalledTimes(2);
+ });
+
afterAll(() => fs.rmSync(TEST_ROOT, { recursive: true, force: true }));
it('defers automatic cancellation cleanup behind a pending uninstall and retries after release', async () => {
diff --git a/apps/desktop/src/main/skillhub/__tests__/organizationAutoInstall.test.ts b/apps/desktop/src/main/skillhub/__tests__/organizationAutoInstall.test.ts
new file mode 100644
index 0000000000..3aa59e5fec
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/__tests__/organizationAutoInstall.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it, vi } from 'vitest';
+vi.mock('../hubApi', () => ({ skillhubApiFetch: vi.fn() }));
+import { fetchOrganizationAutoInstallSkills } from '../organizationAutoInstall';
+
+const skill = { name: 'department-skill', version: '1.0.0', catalogScope: 'team' };
+describe('organization skill distribution', () => {
+ it('bounds a stalled lookup and does not fetch further pages after its deadline', async () => {
+ vi.useFakeTimers();
+ try {
+ let resolve!: (value: unknown) => void;
+ const fetch = vi.fn((_path: string, _options: { timeoutMs: number }) => new Promise<unknown>((done) => { resolve = done; }));
+ const pending = fetchOrganizationAutoInstallSkills(fetch);
+ const rejected = expect(pending).rejects.toThrow('timed out');
+ await vi.advanceTimersByTimeAsync(5_000);
+ await rejected;
+ resolve({ skills: [skill], nextCursor: skill.name });
+ await vi.advanceTimersByTimeAsync(1);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch.mock.calls[0][1]).toEqual({ timeoutMs: 5_000 });
+ } finally { vi.useRealTimers(); }
+ });
+ it('loads every page without sending department identities', async () => {
+ const fetch = vi.fn().mockResolvedValueOnce({ skills: [skill], nextCursor: 'department-skill' })
+ .mockResolvedValueOnce({ skills: [{ ...skill, name: 'second' }], nextCursor: null });
+ expect(await fetchOrganizationAutoInstallSkills(fetch)).toEqual([skill, { ...skill, name: 'second' }]);
+ expect(fetch.mock.calls.map(([path]) => path)).toEqual(['/api/skills-hub/auto-install', '/api/skills-hub/auto-install?cursor=department-skill']);
+ for (const [, options] of fetch.mock.calls) expect(options.timeoutMs).toBeGreaterThan(0);
+ });
+ it.each([{ ...skill, name: '../unsafe' }, { ...skill, version: 'bad' }, { ...skill, catalogScope: 'market' }])(
+ 'rejects invalid entries atomically', async (bad) => {
+ await expect(fetchOrganizationAutoInstallSkills(vi.fn().mockResolvedValue({ skills: [skill, bad], nextCursor: null })))
+ .rejects.toThrow();
+ });
+ it('stops cyclic pagination', async () => {
+ const fetch = vi.fn().mockResolvedValue({ skills: [skill], nextCursor: 'same' });
+ await expect(fetchOrganizationAutoInstallSkills(fetch)).rejects.toThrow('pagination');
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+ it('returns no candidates for an empty or personal audience', async () => {
+ expect(await fetchOrganizationAutoInstallSkills(vi.fn().mockResolvedValue({ skills: [], nextCursor: null }))).toEqual([]);
+ });
+ it('does not return partial candidates if a later page fails', async () => {
+ const fetch = vi.fn().mockResolvedValueOnce({ skills: [skill], nextCursor: skill.name }).mockRejectedValueOnce(new Error('offline'));
+ await expect(fetchOrganizationAutoInstallSkills(fetch)).rejects.toThrow('offline');
+ });
+});
diff --git a/apps/desktop/src/main/skillhub/autoSyncService.ts b/apps/desktop/src/main/skillhub/autoSyncService.ts
index c89760d6f5..15b1e3931d 100644
--- a/apps/desktop/src/main/skillhub/autoSyncService.ts
+++ b/apps/desktop/src/main/skillhub/autoSyncService.ts
@@ -5,6 +5,7 @@
* product-owned whitelist against SkillHub, reusing the existing installer so
* zip verification, registry writes, and global skill links stay centralized.
*/
+import { fetchOrganizationAutoInstallSkills } from './organizationAutoInstall';
import os from 'node:os';
import path from 'node:path';
import fs from 'node:fs';
@@ -130,7 +131,7 @@ export class SkillhubAutoSyncService {
if (!userId) return Promise.resolve();
if (this.completedUserId === userId) return Promise.resolve();
if (this.inFlight) {
- if (this.inFlightUserId === userId) return this.inFlight;
+ if (this.inFlightUserId === userId && !this.externalCancelRequested) return this.inFlight;
return this.inFlight.finally(() => this.runOnceAfterLogin());
}
@@ -138,6 +139,7 @@ export class SkillhubAutoSyncService {
this.inFlightUserId = userId;
this.inFlight = this.run()
.then(() => {
+ this.assertAuthUnchanged();
this.completedUserId = userId;
})
.catch((err) => {
@@ -153,6 +155,7 @@ export class SkillhubAutoSyncService {
}
cancelInFlight(): void {
+ this.completedUserId = null;
this.externalCancelRequested = true;
if (this.activeInstallSlug) {
this.deps.cancelInstall(this.activeInstallSlug);
@@ -172,6 +175,7 @@ export class SkillhubAutoSyncService {
});
return { skills: defaultAutoSyncSkills(), usingFallbackConfig: true };
});
+ this.assertAuthUnchanged();
const { skills, usingFallbackConfig } = config;
if (skills.length === 0) {
await this.recordCandidateSkills(userId, [], { replace: !usingFallbackConfig });
@@ -482,7 +486,7 @@ export class SkillhubAutoSyncService {
private assertAuthUnchanged(): void {
const currentUserId = this.deps.getCurrentUserId();
- if (!currentUserId || currentUserId !== this.inFlightUserId) {
+ if (this.externalCancelRequested || !currentUserId || currentUserId !== this.inFlightUserId) {
throw new Error('auth user changed during auto sync');
}
}
@@ -504,6 +508,23 @@ async function pathExists(p: string): Promise<boolean> {
}
async function fetchRemoteAutoSyncConfig(): Promise<AutoSyncConfigResult> {
+ const [product, organization] = await Promise.allSettled([
+ fetchProductAutoSyncConfig(), fetchOrganizationAutoInstallSkills(),
+ ]);
+ const productConfig = product.status === 'fulfilled' ? product.value
+ : { skills: defaultAutoSyncSkills(), usingFallbackConfig: true };
+ const skills = new Map(productConfig.skills.map((skill) => [skill.name, skill]));
+ if (organization.status === 'fulfilled') {
+ for (const skill of organization.value) skills.set(skill.name, skill);
+ } else {
+ // Old servers and transient errors must not erase persisted ignore preferences.
+ log.warn('organization skill distribution unavailable');
+ }
+ return { skills: [...skills.values()], usingFallbackConfig:
+ productConfig.usingFallbackConfig || organization.status === 'rejected' };
+}
+
+async function fetchProductAutoSyncConfig(): Promise<AutoSyncConfigResult> {
const url = process.env.XDT_SKILLHUB_AUTO_SYNC_CONFIG_URL
?? `${(await ensureBaseUrl()).replace(/\/+$/, '')}/${SKILLHUB_AUTO_SYNC_CONFIG_PATH}`;
const response = await fetchJsonWithTimeout(url, CONFIG_FETCH_TIMEOUT_MS);
diff --git a/apps/desktop/src/main/skillhub/organizationAutoInstall.ts b/apps/desktop/src/main/skillhub/organizationAutoInstall.ts
new file mode 100644
index 0000000000..322ffc9b41
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/organizationAutoInstall.ts
@@ -0,0 +1,61 @@
+import { skillhubApiFetch } from './hubApi';
+
+export interface OrganizationAutoInstallSkill {
+ name: string;
+ version: string;
+ catalogScope: 'team';
+}
+
+const DISTRIBUTION_TIMEOUT_MS = 5_000;
+type FetchPage = (path: string, options: { timeoutMs: number }) => Promise<unknown>;
+
+/** Bound the entire paginated lookup, including authentication refresh. */
+export async function fetchOrganizationAutoInstallSkills(
+ fetchPage: FetchPage = (path, options) => skillhubApiFetch(path, options),
+): Promise<OrganizationAutoInstallSkill[]> {
+ const deadline = Date.now() + DISTRIBUTION_TIMEOUT_MS;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ loadPages(fetchPage, deadline),
+ new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error('Organization skill distribution timed out')), DISTRIBUTION_TIMEOUT_MS);
+ }),
+ ]);
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+}
+
+/** Server owns the department decision; never send client-supplied department IDs. */
+async function loadPages(fetchPage: FetchPage, deadline: number): Promise<OrganizationAutoInstallSkill[]> {
+ const skills = new Map<string, OrganizationAutoInstallSkill>();
+ let cursor: string | null = null;
+ const seen = new Set<string>();
+ do {
+ const path = '/api/skills-hub/auto-install' + (cursor ? `?cursor=${encodeURIComponent(cursor)}` : '');
+ const timeoutMs = deadline - Date.now();
+ if (timeoutMs <= 0) throw new Error('Organization skill distribution timed out');
+ const raw = await fetchPage(path, { timeoutMs });
+ if (!raw || typeof raw !== 'object') throw new Error('Invalid organization skill distribution');
+ const page = raw as Record<string, unknown>;
+ if (!Array.isArray(page.skills) || page.skills.length > 100
+ || !(page.nextCursor === null || (typeof page.nextCursor === 'string' && /^[a-z0-9][a-z0-9-]{0,127}$/.test(page.nextCursor)))) {
+ throw new Error('Invalid organization skill distribution');
+ }
+ for (const value of page.skills) {
+ if (!value || typeof value !== 'object') throw new Error('Invalid organization skill');
+ const skill = value as Record<string, unknown>;
+ if (typeof skill.name !== 'string' || !/^[a-z0-9][a-z0-9-]{0,127}$/.test(skill.name)
+ || typeof skill.version !== 'string' || skill.version.length > 32 || !/^\d+\.\d+\.\d+$/.test(skill.version)
+ || skill.catalogScope !== 'team') throw new Error('Invalid organization skill');
+ skills.set(skill.name, skill as unknown as OrganizationAutoInstallSkill);
+ }
+ cursor = page.nextCursor as string | null;
+ if (cursor) {
+ if (seen.has(cursor) || seen.size >= 100) throw new Error('Invalid organization skill pagination');
+ seen.add(cursor);
+ }
+ } while (cursor);
+ return [...skills.values()];
+}
diff --git a/docs/skillhub-organization-distribution.md b/docs/skillhub-organization-distribution.md
new file mode 100644
index 0000000000..8ef92224cc
--- /dev/null
+++ b/docs/skillhub-organization-distribution.md
@@ -0,0 +1,14 @@
+# Organization Skill distribution
+
+The enterprise Console manages visibility and automatic installation audiences for organization-owned native skills.
+The desktop reads `GET /api/skills-hub/auto-install` from the existing `cindySkillHubApiBaseUrl` after login or identity changes.
+The additive response is `{ skills: [{ name, version, catalogScope: "team" }], nextCursor }`; each page contains at most 100 skills.
+Department IDs are never submitted by the desktop. The server selects candidates using authenticated membership and both audiences.
+
+Organization candidates take precedence over same-slug product defaults. Existing installers, digest verification, local registry,
+conflict protection, ignore preferences and cancellation cleanup remain in use. Policy changes do not uninstall existing files.
+A transient error or old server returning 404 does not clear stored preferences or prevent product defaults from being processed.
+Users can sign out and back in (or restart Cindy) to pick up changed policies; no live policy polling is introduced.
+Older desktop versions retain manual installation but do not consume the new automatic distribution endpoint.
+
+Deploy the server and its migration first, then release the desktop consumer. New endpoint failures are isolated from manual installation.