Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): enforce plugin Cindy version compatibility (#2010)
GaoWei Liufcc3c92a64a4
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex c5f724e4be..05d2bada7c 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1064,6 +1064,7 @@ my-ghost/"ko": "locales/ko.json"},"version": "1.0.0",+ "minCindyVersion": "1.2.3", // 可选:安装所需最低 Cindy 正式版本(SemVer)。不写=兼容所有版本;只在确实使用了新版宿主能力时声明"entry": "main.js", // 电子脑入口(kind 字段已无需填写:意识只有芯片一种形态,缺省即 chip;写了也只认 "chip")"launch": "on-demand", // 可选:电子脑启动模式。on-demand(缺省)=被需要才拉起;resident=唤醒即常驻(确认框会如实标注"常驻运行",绝大多数意识不需要,仅订阅型/需秒响应的场景用)"slots": ["tool", "cindy", "panel"], // 能力白名单,没声明的槽运行时不存在@@ -1096,6 +1097,9 @@ my-ghost/}\`\`\`+不要为“当前开发环境版本”机械填写 \`minCindyVersion\`。旧插件和不依赖新版宿主能力的+插件应省略它;只有确认更早版本无法解析或安装时,才填写能工作的最早正式版本。+### 2.1 本地化资源(locales)插件语言**只跟随 Cindy 宿主当前语言**。不要读取 \`navigator.language\`、操作系统语言或diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 94fc57d68f..a80395c110 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -3,6 +3,8 @@ import fs from 'node:fs';import path from 'node:path';import { isDeepStrictEqual } from 'node:util';+import { supportsCindyVersion } from '@cindy/plugin-protocol';+import { createLogger } from '../logger.js';import { throwIpcError } from '../utils/ipcValidate.js';import {@@ -3498,6 +3500,14 @@ function throwUninstallError(rejection: UninstallRejection): never {}}+function assertGhostSupportsCurrentCindy(manifest: GhostManifest): void {+ if (supportsCindyVersion(app.getVersion(), manifest.minCindyVersion)) return;+ throwIpcError(+ 'GHOST_FILE_INVALID',+ `该插件需要 Cindy ${manifest.minCindyVersion} 或更高版本`,+ );+}+/*** 装入 + 停靠(共享主体):ghosts:install(显式路径)、* ghosts:install-via-dialog(系统文件选择框)与双击 .cindy@@ -3604,6 +3614,7 @@ async function installOrUpdateMarketGhostPackageLocked(const manager = getGhostManager();const inspected = await manager.inspect(cindyFilePath);if ('rejection' in inspected) throwInstallError(inspected.rejection);+ assertGhostSupportsCurrentCindy(inspected.canonicalManifest);if (inspected.canonicalManifest.id !== expected.ghostId ||inspected.canonicalManifest.version !== expected.version@@ -4864,6 +4875,7 @@ export function registerGhostIpc(): void {}const probe = await manager.inspect(lizFilePath);if ('rejection' in probe) throwInstallError(probe.rejection);+ assertGhostSupportsCurrentCindy(probe.canonicalManifest);if (probe.packageSha256 !== expectedPackageSha256) {throwIpcError('GHOST_FILE_INVALID', '插件文件在确认后发生了变化,请重新选择并确认');}@@ -4900,6 +4912,7 @@ export function registerGhostIpc(): void {}const inspected = await manager.inspect(lizFilePath);if ('rejection' in inspected) throwInstallError(inspected.rejection);+ assertGhostSupportsCurrentCindy(inspected.canonicalManifest);if (inspected.packageSha256 !== expectedPackageSha256) {throwIpcError('GHOST_FILE_INVALID', '插件文件在确认后发生了变化,请重新选择并确认');}@@ -4969,6 +4982,7 @@ export function registerGhostIpc(): void {}const result = await manager.inspect(lizFilePath);if ('rejection' in result) throwInstallError(result.rejection);+ assertGhostSupportsCurrentCindy(result.canonicalManifest);// 官方前缀在 inspect 就拒(确认弹窗都不该弹出来),install/update 双保险再拦。rejectReservedGhostId(result.manifest.id);rejectUnauthorizedTokenBroker(result.manifest);diff --git a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts b/apps/desktop/src/main/plugin-market/__tests__/api.test.tsindex 958a14b850..3edb4b5b7f 100644--- a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/api.test.ts@@ -79,13 +79,16 @@ describe('PluginMarketApi', () => {nextCursor: null,},);- const api = new PluginMarketApi(fetcher);+ const api = new PluginMarketApi(fetcher, () => '1.2.3');await expect(api.listAll()).resolves.toMatchObject({plugins: [{ id: PLUGIN_A }, { id: PLUGIN_B }],removals: [],});expect(fetcher.mock.calls[1]?.[0]).toContain(`cursor=${PLUGIN_A}`);+ expect(fetcher.mock.calls[0]?.[1]).toMatchObject({+ headers: { 'x-cindy-version': '1.2.3' },+ });});it('deduplicates removals by pluginId across pages keeping the first-seen notice', async () => {diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.tsindex 9a20503cd5..79dd710a6e 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts@@ -30,7 +30,10 @@ const pickerDialog = vi.hoisted(() => ({showOpenDialog: vi.fn(async () => ({ canceled: true, filePaths: [] as string[] })),}));vi.mock('electron', () => ({- app: { getPath: vi.fn(() => os.tmpdir()) },+ app: {+ getPath: vi.fn(() => os.tmpdir()),+ getVersion: vi.fn(() => '1.0.0'),+ },dialog: pickerDialog,}));vi.mock('../../authManager.js', () => ({@@ -129,7 +132,7 @@ function serverSummary(overrides: Partial<VisiblePluginSummary> = {}): VisiblePlfunction writeLocalMarket(root: string,marketName: string,- plugins: Array<{ rel: string; id: string; version?: string }>,+ plugins: Array<{ rel: string; id: string; version?: string; minCindyVersion?: string }>,): string {const dir = path.join(root, marketName);for (const plugin of plugins) {@@ -137,7 +140,12 @@ function writeLocalMarket(fs.mkdirSync(pluginDir, { recursive: true });fs.writeFileSync(path.join(pluginDir, 'ghost.json'),- JSON.stringify(ghostManifest(plugin.id, plugin.version ?? '1.0.0')),+ JSON.stringify({+ ...ghostManifest(plugin.id, plugin.version ?? '1.0.0'),+ ...(plugin.minCindyVersion+ ? { minCindyVersion: plugin.minCindyVersion }+ : {}),+ }),);fs.writeFileSync(path.join(pluginDir, 'main.js'), '// entry');}@@ -217,6 +225,24 @@ describe('PluginMarketService 自定义市场聚合', () => {});});+ it('does not expose custom market releases that require a newer Cindy version', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [+ { rel: 'plugins/compatible', id: 'compatible' },+ {+ rel: 'plugins/requires-newer',+ id: 'requires-newer',+ minCindyVersion: '2.0.0',+ },+ ]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ const snapshot = await h.service.snapshot();++ expect(snapshot.items.map((item) => item.ghostId)).toEqual(['compatible']);+ });+it('strips bidi/control chars from custom plugin name/description/author in snapshot', async () => {// ghost.json 来自不受信市场仓库,双向控制符会在卡片上伪造署名/说明。const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 8c4c3378c0..6b82679059 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -29,7 +29,10 @@ const runtime = vi.hoisted(() => ({}));vi.mock('electron', () => ({- app: { getPath: vi.fn(() => os.tmpdir()) },+ app: {+ getPath: vi.fn(() => os.tmpdir()),+ getVersion: vi.fn(() => '1.0.0'),+ },}));vi.mock('../../authManager.js', () => ({getCurrentUserId: vi.fn(() =>@@ -511,6 +514,43 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.ledger.installationForGhost(item.ghostId)?.manifestDigest).toBeUndefined();});+ it('rejects an incompatible official Plugin detail', async () => {+ const item = summary();+ const incompatibleManifest = { ...manifest(), minCindyVersion: '2.0.0' };+ const h = harness([item]);+ h.api.detail.mockResolvedValueOnce({+ ...item,+ currentRelease: {+ ...item.currentRelease,+ manifest: incompatibleManifest,+ },+ } satisfies VisiblePluginDetail);++ await expect(h.service.detail(item.id)).rejects.toThrow('[NOT_FOUND]');+ });++ it('rejects an incompatible official Plugin before download', async () => {+ const item = summary();+ const incompatibleManifest = { ...manifest(), minCindyVersion: '2.0.0' };+ const h = harness([item]);+ h.api.detail.mockResolvedValueOnce({+ ...item,+ currentRelease: {+ ...item.currentRelease,+ manifest: incompatibleManifest,+ },+ } satisfies VisiblePluginDetail);++ await expect(+ h.service.install(item.id, {+ expectedReleaseId: item.currentRelease.id,+ expectedManifest: incompatibleManifest,+ }),+ ).rejects.toThrow('[NOT_FOUND]');+ expect(h.api.download).not.toHaveBeenCalled();+ expect(runtime.install).not.toHaveBeenCalled();+ });+// 2026-07-26 定案:市场首装一律装完即开,手动安装与 defaultInstall 归一,// 不再向装入入口透传 initiallyEnabled(启用语义收敛在市场装入入口本身)。it('manual market install goes through the auto-enable install entry', async () => {diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.tsindex f768d111bb..ed34be54c3 100644--- a/apps/desktop/src/main/plugin-market/api.ts+++ b/apps/desktop/src/main/plugin-market/api.ts@@ -1,4 +1,5 @@import {+ CINDY_CLIENT_VERSION_HEADER,parseGetPluginResponse,parseListPluginsResponse,parsePluginDownloadResponse,@@ -32,7 +33,17 @@ const defaultFetcher: Fetcher = (apiPath, options) =>/** plugin-server 普通客户端 API;每个响应都经过共享 v2 parser fail-closed。 */export class PluginMarketApi {- constructor(private readonly fetcher: Fetcher = defaultFetcher) {}+ constructor(+ private readonly fetcher: Fetcher = defaultFetcher,+ private readonly getClientVersion: () => string = () => '0.0.0',+ ) {}++ private requestOptions(): Omit<ApiFetchOptions, 'baseUrl'> {+ return {+ cache: 'no-store',+ headers: { [CINDY_CLIENT_VERSION_HEADER]: this.getClientVersion() },+ };+ }async listAll(query?: string,@@ -46,9 +57,10 @@ export class PluginMarketApi {if (query?.trim()) search.set('query', query.trim());if (cursor) search.set('cursor', cursor);const response = parseListPluginsResponse(- await this.fetcher<unknown>(`/api/plugins?${search.toString()}`, {- cache: 'no-store',- }),+ await this.fetcher<unknown>(+ `/api/plugins?${search.toString()}`,+ this.requestOptions(),+ ),);for (const plugin of response.plugins) {if (seen.has(plugin.id)) continue;@@ -81,9 +93,10 @@ export class PluginMarketApi {async detail(pluginId: string): Promise<GetPluginResponse['plugin']> {return parseGetPluginResponse(- await this.fetcher<unknown>(`/api/plugins/${encodeURIComponent(pluginId)}`, {- cache: 'no-store',- }),+ await this.fetcher<unknown>(+ `/api/plugins/${encodeURIComponent(pluginId)}`,+ this.requestOptions(),+ ),).plugin;}@@ -94,7 +107,7 @@ export class PluginMarketApi {return parsePluginDownloadResponse(await this.fetcher<unknown>(`/api/plugins/${encodeURIComponent(pluginId)}/releases/${encodeURIComponent(releaseId)}/download`,- { cache: 'no-store' },+ this.requestOptions(),),);}diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex a7c5dcfe3b..995959aecb 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -4,6 +4,7 @@ import crypto from 'node:crypto';import {isValidPluginResourceId,+ supportsCindyVersion,type PluginRemovalNotice,type VisiblePluginDetail,type VisiblePluginSummary,@@ -237,6 +238,10 @@ function ghostIdCounts(return counts;}+function manifestSupportsCurrentCindy(manifest: GhostManifest): boolean {+ return supportsCindyVersion(app.getVersion(), manifest.minCindyVersion);+}+/** 自定义市场发现到的单个插件条目(快照投影的原料)。 */interface CustomMarketEntry {config: MarketSourceConfig;@@ -329,7 +334,7 @@ export class PluginMarketService {private readonly pendingRemovalNotices = new Map<string, PluginRemovalUserNotice>();constructor(- private readonly api = new PluginMarketApi(),+ private readonly api = new PluginMarketApi(undefined, () => app.getVersion()),private readonly ledger = new PluginMarketLedger(() =>ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),),@@ -456,6 +461,9 @@ export class PluginMarketService {if (!compatible.ok) {throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');}+ if (!manifestSupportsCurrentCindy(compatible.manifest)) {+ throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');+ }return {...this.toItem(plugin, this.localInstallSnapshot(this.ledgerForOwner(owner))),manifest: compatible.manifest,@@ -512,6 +520,9 @@ export class PluginMarketService {'Plugin manifest changed after permission review',);}+ if (!manifestSupportsCurrentCindy(compatible.manifest)) {+ throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');+ }const existing = getGhostManager().list().find((ghost) => ghost.manifest.id === plugin.ghostId);@@ -682,6 +693,9 @@ export class PluginMarketService {if (!plugin) {throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');}+ if (!manifestSupportsCurrentCindy(plugin.manifest)) {+ throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');+ }return {...this.customToItem({ config: discovered.config, plugin },@@ -727,6 +741,9 @@ export class PluginMarketService {if (!plugin) {throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');}+ if (!manifestSupportsCurrentCindy(plugin.manifest)) {+ throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');+ }const pluginId = customMarketPluginId(ref.marketName, plugin.ghostId);const releaseId = customMarketReleaseId(ref.marketName, plugin.ghostId, plugin.version);if (releaseId !== options.expectedReleaseId) {@@ -903,6 +920,7 @@ export class PluginMarketService {});}for (const plugin of result.marketplace.plugins) {+ if (!manifestSupportsCurrentCindy(plugin.manifest)) continue;entries.push({ config, plugin });}}diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 3fa7df3101..e247472870 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -158,6 +158,14 @@ describe('ghost · 清单校验', () => {expect(validateGhostManifest({ ...goodManifest(), version: 'v'.repeat(33) }).ok).toBe(false);});+ it('minCindyVersion 缺省兼容旧插件,声明时只接受 SemVer', () => {+ expect(validateGhostManifest(goodManifest()).ok).toBe(true);+ const declared = validateGhostManifest({ ...goodManifest(), minCindyVersion: '1.2.3' });+ expect(declared.ok && declared.manifest.minCindyVersion).toBe('1.2.3');+ expect(validateGhostManifest({ ...goodManifest(), minCindyVersion: 'v1.2.3' }).ok).toBe(false);+ expect(validateGhostManifest({ ...goodManifest(), minCindyVersion: '1.2' }).ok).toBe(false);+ });+it('kind 可省略:缺省归一化为 chip(2026-07-12 晚定案,单形态后纯冗余)', () => {const m = goodManifest();delete m.kind;diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 29d0d846ec..5bfcdcf021 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1,4 +1,4 @@-import { GHOST_OAUTH_SCOPES_MAX } from '@cindy/plugin-protocol';+import { GHOST_OAUTH_SCOPES_MAX, isValidCindyVersion } from '@cindy/plugin-protocol';import { findSplitChildByPanelKind, insertRootSplitPane, type Layout } from './layoutTree';import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from './locale';@@ -1264,6 +1264,8 @@ export interface GhostManifest {name: string;/** 版本字符串(不强制 semver,仅展示用)。 */version: string;+ /** 安装此 Release 所需的最低 Cindy 客户端 SemVer;缺省表示不限制。 */+ minCindyVersion?: string;/** 作者展示名(仅展示用)。 */author?: string;/**@@ -2709,6 +2711,9 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (typeof raw.version !== 'string' || raw.version.trim().length === 0 || raw.version.length > 32) {return { ok: false, reason: 'version 必须是 1–32 字符的非空字符串' };}+ if (raw.minCindyVersion !== undefined && !isValidCindyVersion(raw.minCindyVersion)) {+ return { ok: false, reason: 'minCindyVersion 必须是合法的 SemVer 字符串' };+ }// kind 可省略(2026-07-12 晚定案:单形态后字段纯冗余,缺省即 chip);// 写了就必须是 chip——写错值仍拒,不静默纠正(规则 9)。if (raw.kind !== undefined && raw.kind !== 'chip') {@@ -4438,6 +4443,9 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {id: raw.id,name: raw.name,version: raw.version,+ ...(raw.minCindyVersion !== undefined+ ? { minCindyVersion: raw.minCindyVersion as string }+ : {}),kind: 'chip',...(raw.author !== undefined ? { author: raw.author as string } : {}),...(locales !== undefined ? { locales } : {}),diff --git a/cindy-protocol b/cindy-protocolindex 298cd35924..0cb87cb524 160000--- a/cindy-protocol+++ b/cindy-protocol@@ -1 +1 @@-Subproject commit 298cd359246c7497dd683d3318f72be252b4a94f+Subproject commit 0cb87cb52427fbebd8a3d85a271847d06bfb2ac6