Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): preserve legacy plugin permission approvals (#1657)

DavidShenXD5c4124601a4a
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 689450c216..2436f65c50 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -13,8 +13,8 @@ import {
GHOST_CARD_HEIGHT_MIN,
GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,
GHOST_NOTIFY_MIN_INTERVAL_MS,
- diffGhostPermissionItems,
ghostPermissionBaselineKey,
+ unreviewedGhostPermissionItems,
ghostWebviewEntryPaths,
isCindyAccountGhostId,
isOfficialGhostId,
@@ -3174,6 +3174,11 @@ export async function installOrUpdateMarketGhostPackage(
* 本地 `.cindy` 装入不经此出口,确认框读的就是包本身,没有这层漂移。
*/
reviewedManifest?: GhostManifest;
+ /**
+ * 经市场账本摘要认证的旧版已安装清单。历史详情投影漏掉、但用户此前
+ * 已批准的权限可继续作为基线;未被该基线覆盖的真实包权限仍走复核。
+ */
+ previouslyInstalledManifest?: GhostManifest;
/** 用户确认过的真实下载包 SHA 与确认时的已装权限基线。 */
approvedPackageSha256?: string;
reviewedBaseline?: string;
@@ -3193,6 +3198,7 @@ async function installOrUpdateMarketGhostPackageLocked(
ghostId: string;
version: string;
reviewedManifest?: GhostManifest;
+ previouslyInstalledManifest?: GhostManifest;
approvedPackageSha256?: string;
reviewedBaseline?: string;
},
@@ -3245,10 +3251,11 @@ async function installOrUpdateMarketGhostPackageLocked(
'Downloaded Plugin package changed after permission review',
);
}
- const added = diffGhostPermissionItems(
+ const added = unreviewedGhostPermissionItems(
expected.reviewedManifest,
+ expected.previouslyInstalledManifest,
inspected.canonicalManifest,
- ).added;
+ );
if (added.length > 0) {
const review: PluginMarketPackageReview = {
manifest: inspected.manifest,
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index d8bd711687..95d1823f21 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -61,7 +61,7 @@ import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-pr
import { withGhostInstallLock } from '../../cindy-brain/ghostInstallLock';
import { GhostPackagePermissionReviewRequiredError } from '../../cindy-brain/packagePermissionReview';
-import { PluginMarketLedger } from '../ledger';
+import { PluginMarketLedger, ghostManifestDigest } from '../ledger';
import { PluginMarketService } from '../service';
import type { PluginMarketApi } from '../api';
@@ -508,6 +508,95 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
+ it('uses a digest-matched installed manifest as the legacy approval baseline', async () => {
+ const item = summary({
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const installed = manifest(item.ghostId, '1.0.0', ['notify', 'fs']);
+ const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-ghost-'));
+ roots.push(installedDir);
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installed));
+ runtime.ghosts = [
+ {
+ manifest: { ...installed, name: 'Localized Test Plugin' },
+ dir: installedDir,
+ enabled: true,
+ },
+ ];
+ runtime.install.mockResolvedValue({
+ manifest: manifest(item.ghostId, '2.0.0', ['notify', 'fs']),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(installed),
+ });
+
+ await h.service.install(item.id, { expectedReleaseId: item.currentRelease.id });
+
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ previouslyInstalledManifest: installed,
+ });
+ });
+
+ it('does not use a changed installed manifest as an approval baseline', async () => {
+ const item = summary({
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const installed = manifest(item.ghostId, '1.0.0', ['notify', 'fs']);
+ const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-ghost-'));
+ roots.push(installedDir);
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installed));
+ runtime.ghosts = [{ manifest: installed, dir: installedDir, enabled: true }];
+ runtime.install.mockResolvedValue({
+ manifest: manifest(item.ghostId, '2.0.0', ['notify']),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest({ ...installed, slots: ['notify'] }),
+ });
+
+ await h.service.install(item.id, { expectedReleaseId: item.currentRelease.id });
+
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('previouslyInstalledManifest');
+ });
+
+ it('does not use a legacy ledger record without an authenticated manifest digest', async () => {
+ const item = summary({
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const installed = manifest(item.ghostId, '1.0.0', ['notify', 'fs']);
+ const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-ghost-'));
+ roots.push(installedDir);
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installed));
+ runtime.ghosts = [{ manifest: installed, dir: installedDir, enabled: true }];
+ runtime.install.mockResolvedValue({
+ manifest: manifest(item.ghostId, '2.0.0', ['notify']),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ source: 'legacy-adopted',
+ releaseId: 'legacy-unresolved:1.0.0',
+ version: '1.0.0',
+ });
+
+ await h.service.install(item.id, { expectedReleaseId: item.currentRelease.id });
+
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('previouslyInstalledManifest');
+ });
+
it('installs and enables a public defaultInstall package in local mode', async () => {
runtime.session = {
mode: 'local',
@@ -569,7 +658,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
it('服务端安装持 ghostId 锁,覆盖落位到溯源写入整段', async () => {
// 少了这把锁,本地 .cindy 装入能在包检查窗口里落入同 id 的包,随后被本次安装
// 当作更新目标覆盖;账本写入若在锁外,本地装入还能插在"落位"与"写溯源"之间,
- // 让账本认领一个已被替换的包(服务端记录不带 manifestDigest,投影判不出来)。
+ // 让账本认领一个已被替换的包(账本摘要若未对上当前安装内容,投影不会认领)。
// 这里用真实的 withGhostInstallLock(service 直接 import,未被 mock)观察:
// 安装在飞行中时,外部同 id 请求必须进不来;账本已写入后才放行。
const item = summary();
diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.ts
index c5d0f61f8a..26291c06ef 100644
--- a/apps/desktop/src/main/plugin-market/ledger.ts
+++ b/apps/desktop/src/main/plugin-market/ledger.ts
@@ -37,7 +37,7 @@ export interface PluginMarketInstallationRecord {
* "我装过"的声明,运行时的包在降级窗口可以被旧版换成任何东西(旧版不认识
* custom 账本,卸载/本地重装都不会更新它)——认领运行时安装必须同时对上这个
* 摘要,只凭 ghostId 存在就恢复所有权会把别人的包错误归属给本来源并放行其
- * 更新覆盖。仅自定义安装记录携带。
+ * 更新覆盖。新写入的市场、自定义市场和 legacy adoption 记录均应携带。
*/
manifestDigest?: string;
}
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index c0f0720709..3e9d589fc9 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -158,7 +158,9 @@ function defaultInstallSubject(owner: ActiveAppSession): string {
function recordFrom(
plugin: VisiblePluginSummary | VisiblePluginDetail,
source: PluginMarketInstallationRecord['source'],
+ installed: InstalledGhost,
): PluginMarketInstallationRecord {
+ const rawManifest = installedGhostRawManifest(installed.dir);
return {
pluginId: plugin.id,
ghostId: plugin.ghostId,
@@ -170,6 +172,7 @@ function recordFrom(
source,
installed: true,
updatedAt: new Date().toISOString(),
+ ...(rawManifest ? { manifestDigest: ghostManifestDigest(rawManifest) } : {}),
};
}
@@ -183,6 +186,7 @@ function legacyRecordFrom(
plugin: VisiblePluginSummary,
ghost: InstalledGhost,
): PluginMarketInstallationRecord {
+ const rawManifest = installedGhostRawManifest(ghost.dir);
return {
pluginId: plugin.id,
ghostId: plugin.ghostId,
@@ -194,6 +198,7 @@ function legacyRecordFrom(
source: 'legacy-adopted',
installed: true,
updatedAt: new Date().toISOString(),
+ ...(rawManifest ? { manifestDigest: ghostManifestDigest(rawManifest) } : {}),
};
}
@@ -244,7 +249,7 @@ function stripDirectionalControls(text: string): string {
return text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
}
-function installedGhostRawManifestDigest(dir: string): string | null {
+function installedGhostRawManifest(dir: string): GhostManifest | null {
try {
// 安装目录也可能被外部进程/同步盘改动,且本函数每次市场快照都会执行:
// 与市场目录同一把单句柄限量闸,拒链接、超限即拒,不让无界字节进快照路径。
@@ -255,12 +260,17 @@ function installedGhostRawManifestDigest(dir: string): string | null {
if (bytes === null) return null;
const raw = JSON.parse(bytes.toString('utf8')) as unknown;
const validated = validateGhostManifest(raw);
- return validated.ok ? ghostManifestDigest(validated.manifest) : null;
+ return validated.ok ? validated.manifest : null;
} catch {
return null;
}
}
+function installedGhostRawManifestDigest(dir: string): string | null {
+ const manifest = installedGhostRawManifest(dir);
+ return manifest ? ghostManifestDigest(manifest) : null;
+}
+
/** Stable local facts reused while projecting one market catalog response. */
interface LocalInstallSnapshot {
/** Installed Ghost runtime facts indexed once for one market operation. */
@@ -1167,7 +1177,7 @@ export class PluginMarketService {
// 互斥。少了它,本地装入能在包检查窗口里落入同 id 的包,随后被本次安装当作
// 更新目标覆盖,而权限差异确认因审阅时目标不存在而没跑过。账本写入也必须在
// 锁内:否则本地装入可以插在"落位"与"写溯源"之间,让账本认领一个其实已被
- // 替换掉的包(服务端记录不带 manifestDigest,投影时判不出来)。
+ // 替换掉的包(账本摘要若未对上当前安装内容,投影时不会认领)。
// 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation,不可反向。
const ghost = await this.withMutation(SOURCE_MUTATION_KEY, () =>
withGhostInstallLock(plugin.ghostId, async () => {
@@ -1177,11 +1187,21 @@ export class PluginMarketService {
// 权限扩权的**权威**判定点:锁内按当前已装 manifest 重算。锁外那次
// 只是快速失败;下载窗口期本地装入/更新若换掉了已装包,旧批准在这里
// 被基线比对拦下,并发替换绕不过去(落位就在下面几行)。
- assertExpansionApproved(
- getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === plugin.ghostId)?.manifest ?? null,
- );
+ const installedNow = getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === plugin.ghostId);
+ assertExpansionApproved(installedNow?.manifest ?? null);
+ const currentRecordNow = ledger.installationForGhost(plugin.ghostId);
+ const installedRawManifest = installedNow
+ ? installedGhostRawManifest(installedNow.dir)
+ : null;
+ const previouslyInstalledManifest =
+ installedRawManifest &&
+ currentRecordNow?.installed &&
+ (currentRecordNow.source === 'market' || currentRecordNow.source === 'legacy-adopted') &&
+ currentRecordNow.manifestDigest === ghostManifestDigest(installedRawManifest)
+ ? installedRawManifest
+ : undefined;
// 市场首装一律装完即开(2026-07-26 定案,见 installOrUpdateMarketGhostPackage);
// 已装过则走原位更新,唤醒/沉睡状态延续当前值。
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
@@ -1191,6 +1211,7 @@ export class PluginMarketService {
// 暂停落位并返回真实包权限——服务端投影层与客户端清单契约漂移时,
// 必须让用户按实际要安装的能力面重新确认。
reviewedManifest: compatible.manifest,
+ ...(previouslyInstalledManifest ? { previouslyInstalledManifest } : {}),
...(options.approvedPackageSha256 !== undefined
? {
approvedPackageSha256: options.approvedPackageSha256,
@@ -1203,7 +1224,7 @@ export class PluginMarketService {
// changes. The bound ledger prevents this write from leaking into the
// new owner.
await this.withCapturedLedgerMutation(ledger, () => {
- ledger.upsertInstallation(recordFrom(plugin, 'market'));
+ ledger.upsertInstallation(recordFrom(plugin, 'market', installed));
});
return installed;
}),
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index 1cd3620c40..6b69f0a8be 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -16,6 +16,7 @@ import {
parseGhostNodeChildToHostMessage,
ghostPartition,
ghostPermissionItems,
+ unreviewedGhostPermissionItems,
ghostWebviewEntryPaths,
isGhostCallToolName,
isValidGhostId,
@@ -122,6 +123,38 @@ describe('ghost · id 规则', () => {
});
describe('ghost · 清单校验', () => {
+ it('更新保留已安装清单中已批准的权限,即使发布元数据遗漏这些权限', () => {
+ const makeToolManifest = (tools: Array<{ name: string; description: string }>) => {
+ const raw = { ...goodManifest(), slots: ['tool'], tools } as Record<string, unknown>;
+ delete raw.panel;
+ const result = validateGhostManifest(raw);
+ if (!result.ok) throw new Error(result.reason);
+ return result.manifest;
+ };
+ const installed = makeToolManifest([{ name: 'gen_image', description: 'Generate images' }]);
+ const reviewed = makeToolManifest([{ name: 'gen_image', description: 'Projected description' }]);
+ const samePackage = makeToolManifest([{ name: 'gen_image', description: 'Generate images' }]);
+ const expandedPackage = makeToolManifest([
+ { name: 'gen_image', description: 'Generate images' },
+ { name: 'edit_image', description: 'Edit images' },
+ ]);
+ const changedPackage = makeToolManifest([
+ { name: 'gen_image', description: 'A third, unreviewed description' },
+ ]);
+
+ expect(unreviewedGhostPermissionItems(reviewed, installed, samePackage)).toEqual([]);
+ expect(
+ unreviewedGhostPermissionItems(reviewed, installed, expandedPackage).map((item) => item.key),
+ ).toEqual([
+ 'tool:edit_image',
+ ]);
+ expect(
+ unreviewedGhostPermissionItems(reviewed, installed, changedPackage).map((item) => item.key),
+ ).toEqual([
+ 'tool:gen_image',
+ ]);
+ });
+
it('全字段合法清单通过,并按已知字段收窄输出', () => {
const v = validateGhostManifest({ ...goodManifest(), unknownField: 'ignored' });
expect(v.ok).toBe(true);
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index b9417371b6..e7790afb2d 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -1893,6 +1893,26 @@ export function diffGhostPermissionItems(
return { added, removed, unchanged };
}
+/**
+ * 返回未被发布清单或已批准旧版本覆盖的包权限。
+ *
+ * 第二个来源用于兼容旧市场元数据:旧详情投影可能漏掉已存在的权限,
+ * 但这些权限此前已经被用户批准,更新时应继续保留。
+ */
+export function unreviewedGhostPermissionItems(
+ reviewed: GhostManifest,
+ previouslyInstalled: GhostManifest | undefined,
+ actual: GhostManifest,
+): GhostPermissionItem[] {
+ const approvalKey = (item: GhostPermissionItem): string =>
+ JSON.stringify([item.key, item.detail ?? '']);
+ const approved = new Set(ghostPermissionItems(reviewed).map(approvalKey));
+ for (const item of ghostPermissionItems(previouslyInstalled ?? reviewed)) {
+ approved.add(approvalKey(item));
+ }
+ return ghostPermissionItems(actual).filter((item) => !approved.has(approvalKey(item)));
+}
+
/**
* icon 允许的图片扩展名 → mime(校验与 main 读盘供图共用同一口径)。
* 不收 svg:svg 可携带脚本,虽经 <img> 渲染不执行,仍不给这个面。