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): isolate plugin markets and simplify permission review (#1917)

GaoWei Liu83ce33a19dbc
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 605afcba72..0f35048bb8 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -15,6 +15,7 @@ import {
GHOST_MANIFEST_FILE,
GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,
GHOST_NOTIFY_MIN_INTERVAL_MS,
+ diffGhostPermissionItems,
ghostPermissionBaselineKey,
unreviewedGhostPermissionItems,
ghostWebviewEntryPaths,
@@ -33,7 +34,7 @@ import {
type GhostVideoResultParams,
type InstalledGhost,
} from '../../shared/ghost.js';
-import type { PluginMarketPackageReview } from '../../shared/pluginMarket.js';
+import type { PluginMarketPackageReviewFacts } from '../../shared/pluginMarket.js';
import { getAppCapabilities } from '../appCapabilities.js';
import {
activeOwnerScopeKey,
@@ -3514,16 +3515,12 @@ export async function installOrUpdateMarketGhostPackage(
ghostId: string;
version: string;
/**
- * 装入确认框实际展示给用户的那份 manifest(来源方给的)。给了就逐项比对:
- * 包里多出来的权限会暂停落位并交由上层复核。两条市场路径都必须给;
- * 本地 `.cindy` 装入不经此出口,确认框读的就是包本身,没有这层漂移。
+ * 安装前实际展示给用户的 manifest。真实包若声明了未展示权限,会在
+ * 落盘前暂停并把同一份已验证包交给上层复核。
*/
reviewedManifest?: GhostManifest;
- /**
- * 经市场账本摘要认证的旧版已安装清单。历史详情投影漏掉、但用户此前
- * 已批准的权限可继续作为基线;未被该基线覆盖的真实包权限仍走复核。
- */
- previouslyInstalledManifest?: GhostManifest;
+ /** 经来源账本摘要认证的已装清单;缺失时不得回退到可变运行时清单。 */
+ permissionBaselineManifest?: GhostManifest;
/** 用户确认过的真实下载包 SHA 与确认时的已装权限基线。 */
approvedPackageSha256?: string;
reviewedBaseline?: string;
@@ -3543,7 +3540,7 @@ async function installOrUpdateMarketGhostPackageLocked(
ghostId: string;
version: string;
reviewedManifest?: GhostManifest;
- previouslyInstalledManifest?: GhostManifest;
+ permissionBaselineManifest?: GhostManifest;
approvedPackageSha256?: string;
reviewedBaseline?: string;
},
@@ -3564,28 +3561,13 @@ async function installOrUpdateMarketGhostPackageLocked(
);
}
requireGhostAvailableForActiveSession(expected.ghostId);
- /**
- * 「审阅过的」与「真要装的」权限必须一致(2026-08-03,codex review P1)。
- *
- * 装入确认框渲染的是**来源方给的 manifest**(服务端市场 = release manifest,
- * 自定义市场 = 抓到的 ghost.json),而真正落地的是 `.cindy` 包里的 ghost.json。
- * 两者本该同一份,但来源方的投影层可能与客户端的清单契约漂移——`cindy-protocol`
- * 那份平行校验器就已经缺了 `confirm` 槽;新登记的槽(如 `badge`)在它眼里是
- * 未知槽名,投影时会被丢掉或整份拒绝。结果:确认框漏列该项权限,包却原样带着
- * 它装进来,用户**从没审过就多出一个常驻能力面**。
- *
- * 这里按权限项逐项比对。包里多出来的权限先暂停落位,由 Renderer 按真实包
- * 重新展示;用户批准后携带包 SHA 和已装权限基线重试。
- * 卡点落在 inspect 之后、任何落地动作之前,所以等待复核时磁盘上什么都没动。
- */
const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
if (expected.reviewedManifest) {
- const installedBaseline = installed
- ? ghostPermissionBaselineKey(installed.manifest)
+ const baselineManifest = expected.permissionBaselineManifest ?? null;
+ const installedBaseline = baselineManifest
+ ? ghostPermissionBaselineKey(baselineManifest)
: null;
- // 真实包复核的批准必须始终绑定当时那份包与已装权限面,不能只在
- // 当前仍存在来源清单差异时才校验。否则两次请求间包字节发生变化、
- // 新包恰好不再多权限时,会绕过旧批准的 SHA/基线绑定直接落位。
+ // 批准始终绑定 Main 实际检查过的包 SHA 与本地已装权限基线。
if (
expected.approvedPackageSha256 !== undefined &&
(expected.approvedPackageSha256 !== inspected.packageSha256 ||
@@ -3596,21 +3578,24 @@ async function installOrUpdateMarketGhostPackageLocked(
'Downloaded Plugin package changed after permission review',
);
}
- const added = unreviewedGhostPermissionItems(
+ const unreviewed = unreviewedGhostPermissionItems(
expected.reviewedManifest,
- expected.previouslyInstalledManifest,
+ baselineManifest ?? undefined,
inspected.canonicalManifest,
);
- if (added.length > 0) {
- const review: PluginMarketPackageReview = {
+ if (unreviewed.length > 0) {
+ const review: PluginMarketPackageReviewFacts = {
manifest: inspected.manifest,
+ permissionDiff: baselineManifest
+ ? diffGhostPermissionItems(baselineManifest, inspected.canonicalManifest)
+ : null,
packageSha256: inspected.packageSha256,
installedBaseline,
};
if (expected.approvedPackageSha256 === undefined) {
- log.warn('market package declares unreviewed permissions', {
+ log.info('market package requires permission review', {
ghostId: expected.ghostId,
- keys: added.map((item) => item.key),
+ keys: unreviewed.map((item) => item.key),
});
throw new GhostPackagePermissionReviewRequiredError(review);
}
diff --git a/apps/desktop/src/main/cindy-brain/packagePermissionReview.ts b/apps/desktop/src/main/cindy-brain/packagePermissionReview.ts
index c6a74e75d9..fc00661af2 100644
--- a/apps/desktop/src/main/cindy-brain/packagePermissionReview.ts
+++ b/apps/desktop/src/main/cindy-brain/packagePermissionReview.ts
@@ -1,8 +1,8 @@
-import type { PluginMarketPackageReview } from '../../shared/pluginMarket.js';
+import type { PluginMarketPackageReviewFacts } from '../../shared/pluginMarket.js';
-/** 安装包权限与市场展示不一致时,交给 PluginMarketService 转成可恢复结果。 */
+/** 真实安装包需要用户复核时,交给 PluginMarketService 转成可恢复结果。 */
export class GhostPackagePermissionReviewRequiredError extends Error {
- constructor(readonly review: PluginMarketPackageReview) {
+ constructor(readonly review: PluginMarketPackageReviewFacts) {
super('The downloaded Plugin package requires permission review');
}
}
diff --git a/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.ts b/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.ts
new file mode 100644
index 0000000000..a630cd405f
--- /dev/null
+++ b/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PluginMarketPackageReviewFacts } from '../../../shared/pluginMarket';
+import { PluginMarketPackagePermissionReviewBridge } from '../packagePermissionReviewBridge';
+
+const facts: PluginMarketPackageReviewFacts = {
+ manifest: {
+ schemaVersion: 2,
+ id: 'cindy-test',
+ name: 'Test Plugin',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['notify'],
+ },
+ permissionDiff: null,
+ packageSha256: 'a'.repeat(64),
+ installedBaseline: null,
+};
+
+describe('PluginMarketPackagePermissionReviewBridge', () => {
+ it('only accepts the answer from the requesting window and hides approval bindings', async () => {
+ const bridge = new PluginMarketPackagePermissionReviewBridge();
+ let request: Parameters<Parameters<typeof bridge.request>[2]>[0] | undefined;
+ const decision = bridge.request(7, facts, (next) => {
+ request = next;
+ return true;
+ });
+
+ expect(request).not.toHaveProperty('packageSha256');
+ expect(request).not.toHaveProperty('installedBaseline');
+ expect(bridge.resolve(8, request!.requestId, true)).toBe(false);
+ expect(bridge.resolve(7, request!.requestId, true)).toBe(true);
+ await expect(decision).resolves.toBe(true);
+ });
+
+ it('cancels every pending decision when its requester window is destroyed', async () => {
+ const bridge = new PluginMarketPackagePermissionReviewBridge();
+ const decision = bridge.request(7, facts, () => true);
+
+ bridge.cancelRequester(7);
+
+ await expect(decision).resolves.toBe(false);
+ });
+
+ it('cancels immediately when the request cannot be delivered', async () => {
+ const bridge = new PluginMarketPackagePermissionReviewBridge();
+
+ await expect(bridge.request(7, facts, () => false)).resolves.toBe(false);
+ });
+});
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.ts
index 4973ac4d56..9a20503cd5 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
@@ -65,9 +65,8 @@ vi.mock('../download.js', () => ({
downloadVerifiedPlugin: vi.fn(async () => undefined),
}));
-import type { VisiblePluginSummary } from '@cindy/plugin-protocol';
+import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-protocol';
-import type { MarketSourceConfig } from '../../../shared/pluginMarket';
import { customMarketPluginId, customMarketReleaseId, marketSourceKey } from '../../../shared/pluginMarket';
import { PluginMarketLedger, ghostManifestDigest } from '../ledger';
import { PluginMarketService } from '../service';
@@ -100,7 +99,7 @@ function ghostManifest(id: string, version = '1.0.0') {
version,
kind: 'chip' as const,
entry: 'main.js',
- slots: ['notify'],
+ slots: ['notify' as const],
};
}
@@ -126,18 +125,6 @@ function serverSummary(overrides: Partial<VisiblePluginSummary> = {}): VisiblePl
};
}
-/** 服务端详情夹具:summary + 该 release 的完整 manifest。 */
-function serverDetail() {
- const summary = serverSummary();
- return {
- ...summary,
- currentRelease: {
- ...summary.currentRelease,
- manifest: ghostManifest(summary.ghostId),
- },
- };
-}
-
/** 在临时目录造一个本地市场夹具(marketplace.json + 插件目录)。 */
function writeLocalMarket(
root: string,
@@ -181,7 +168,17 @@ function harness(items: VisiblePluginSummary[], marketDirs: Array<{ name: string
}
const api = {
listAll: vi.fn(async () => ({ plugins: items, removals: [] })),
- detail: vi.fn(),
+ detail: vi.fn(async (pluginId: string) => {
+ const item = items.find((candidate) => candidate.id === pluginId);
+ if (!item) throw new Error('not found');
+ return {
+ ...item,
+ currentRelease: {
+ ...item.currentRelease,
+ manifest: ghostManifest(item.ghostId, item.currentRelease.version),
+ },
+ } satisfies VisiblePluginDetail;
+ }),
download: vi.fn(),
};
return {
@@ -278,7 +275,7 @@ describe('PluginMarketService 自定义市场聚合', () => {
});
});
- it('marks cross-source ghostId duplicates as conflict on both sides', async () => {
+ it('keeps uninstalled cross-source ghostId duplicates available', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
@@ -286,10 +283,10 @@ describe('PluginMarketService 自定义市场聚合', () => {
const snapshot = await h.service.snapshot();
expect(snapshot.items.find((item) => item.sourceType === 'server')?.installState).toBe(
- 'conflict',
+ 'not-installed',
);
expect(snapshot.items.find((item) => item.sourceType === 'local-market')?.installState).toBe(
- 'conflict',
+ 'not-installed',
);
});
@@ -384,7 +381,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const h = harness([], [{ name: 'team-lib', dir }]);
const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
- expect(detail.manifest.id).toBe('alpha');
+ expect(detail.manifest?.id).toBe('alpha');
expect(detail.sourceType).toBe('local-market');
await expect(h.service.detail(customMarketPluginId('team-lib', 'missing'))).rejects.toMatchObject({
code: 'NOT_FOUND',
@@ -609,7 +606,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expect(runtime.install).not.toHaveBeenCalled();
});
- it('rejects install when another custom source declares the same ghostId', async () => {
+ it('lets the user choose between uninstalled custom sources with the same ghostId', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
@@ -619,10 +616,19 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
{ name: 'rival-lib', dir: rival },
]);
- // 两个来源声明同一 ghostId、本地尚无安装:列表把双方都标成 conflict 并禁用,
- // 安装入口必须用同一口径重算并拒绝,不能因为"本地还没装"就放行。
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('alpha'),
+ dir: '/ghosts/alpha',
+ enabled: true,
+ });
+
+ // 市场目录只负责发现。没有真实安装时,两个条目都可选;用户选择哪个来源,
+ // 安装完成后才由运行时插件和账本建立所有权。
const snapshot = await h.service.snapshot();
- expect(snapshot.items.map((item) => item.installState)).toEqual(['conflict', 'conflict']);
+ expect(snapshot.items.map((item) => item.installState)).toEqual([
+ 'not-installed',
+ 'not-installed',
+ ]);
const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
await expect(
@@ -630,15 +636,20 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
expectedManifest: reviewed.manifest,
}),
- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
- expect(runtime.install).not.toHaveBeenCalled();
+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
+ expect(runtime.install).toHaveBeenCalledTimes(1);
});
- it('rejects install when the server catalog declares the same ghostId', async () => {
+ it('lets a selected custom source install when the server catalog declares the same ghostId', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('server-plugin'),
+ dir: '/ghosts/server-plugin',
+ enabled: true,
+ });
const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'server-plugin'));
await expect(
@@ -646,66 +657,78 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedReleaseId: customMarketReleaseId('team-lib', 'server-plugin', '1.0.0'),
expectedManifest: reviewed.manifest,
}),
- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
- expect(runtime.install).not.toHaveBeenCalled();
+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
+ expect(runtime.install).toHaveBeenCalledTimes(1);
});
- it('rejects installing a server plugin that a custom source also declares', async () => {
+ it('lets a selected server plugin install when a custom source declares the same ghostId', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
const item = serverSummary();
- h.api.detail.mockResolvedValue(serverDetail());
+ h.api.download.mockResolvedValue({
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ });
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('server-plugin'),
+ dir: '/ghosts/server-plugin',
+ enabled: true,
+ });
- // 列表把两边都标成 conflict 并禁用;服务端安装入口只查服务端目录内部重名,
- // 必须用同一口径重算,否则普通 UI 流程或直接 IPC 都能装进来并抢占 ghostId。
const snapshot = await h.service.snapshot();
expect(
snapshot.items.find((entry) => entry.sourceType === 'server')?.installState,
- ).toBe('conflict');
+ ).toBe('not-installed');
await expect(
- h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
- expect(h.api.download).not.toHaveBeenCalled();
+ h.service.install(item.id, {
+ expectedReleaseId: item.currentRelease.id,
+ expectedManifest: ghostManifest(item.ghostId, item.currentRelease.version),
+ }),
+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
+ expect(h.api.download).toHaveBeenCalledTimes(1);
});
- it('keeps the conflict state on the server detail view', async () => {
+ it('keeps an uninstalled duplicate available on the server detail view', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
- h.api.detail.mockResolvedValue(serverDetail());
- // 详情传空重复集合会把 conflict 项恢复成可安装,给出绕过冲突闸的入口。
const detail = await h.service.detail(serverSummary().id);
- expect(detail.installState).toBe('conflict');
+ expect(detail.installState).toBe('not-installed');
});
- it('skips defaultInstall when a custom source declares the same ghostId', async () => {
+ it('does not let an uninstalled custom catalog entry block an official default install', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
const h = harness([serverSummary({ defaultInstall: true })], [{ name: 'team-lib', dir }]);
- h.api.detail.mockResolvedValue(serverDetail());
+ h.api.download.mockResolvedValue({
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ });
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('server-plugin'),
+ dir: '/ghosts/server-plugin',
+ enabled: true,
+ });
- // 默认安装会真的下载并启用插件。若只按服务端目录判重,与自定义来源同 ghostId
- // 的默认项会被静默抢占所有权,而列表随后又把它标成 conflict —— 既定事实已经
- // 发生。冲突集合必须先于默认安装算出来。
- const snapshot = await h.service.snapshot();
- expect(h.api.download).not.toHaveBeenCalled();
- expect(runtime.install).not.toHaveBeenCalled();
- expect(
- snapshot.items.find((entry) => entry.sourceType === 'server')?.installState,
- ).toBe('conflict');
+ await h.service.snapshot();
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(runtime.install).toHaveBeenCalledTimes(1);
});
- it('rechecks cross-source ownership right before committing the install', async () => {
+ it('does not rescan unrelated catalogs while committing a selected install', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
- const rivalDir = writeLocalMarket(root, 'rival-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
runtime.install.mockResolvedValue({
manifest: ghostManifest('alpha'),
@@ -715,25 +738,13 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const pluginId = customMarketPluginId('team-lib', 'alpha');
const reviewed = await h.service.detail(pluginId);
- // 竞争来源必须在**入口检查之后**才出现,否则被入口那次判定拦住,根本触不到
- // 提交点复核。打包是异步的、可以持续很久,期间另一窗口经独立的 market-sources
- // 互斥键添加了声明同一 ghostId 的来源 —— 用"第一次读取来源表之后才加进去"
- // 精确模拟这个时序。
- const rival: MarketSourceConfig = {
- name: 'rival-lib',
- addedAt: '2026-08-01T00:00:00.000Z',
- lastSyncedAt: '2026-08-01T00:00:00.000Z',
- lastRevision: null,
- source: { type: 'local', path: rivalDir },
- };
const realList = MarketSourceStore.prototype.list;
let reads = 0;
const listSpy = vi
.spyOn(MarketSourceStore.prototype, 'list')
.mockImplementation(function (this: MarketSourceStore) {
- const configs = realList.call(this);
reads += 1;
- return reads <= 1 ? configs : [...configs, rival];
+ return realList.call(this);
});
try {
@@ -742,10 +753,9 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
expectedManifest: reviewed.manifest,
}),
- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
- // 关键:不能只是报错,而是必须在**改动 Ghost 运行时之前**就拒绝。
- expect(runtime.install).not.toHaveBeenCalled();
- expect(reads).toBeGreaterThan(1);
+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(reads).toBe(0);
} finally {
listSpy.mockRestore();
}
@@ -761,8 +771,8 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const reviewed = await h.service.detail(pluginId);
// 落位期间(installOrUpdateMarketGhostPackage 还在 await 包检查)另一窗口尝试
- // 添加声明同一 ghostId 的来源。提交段持有来源锁,这次 addSource 必须排在落位
- // 之后 —— 否则复核结论在真正落位前就过期了。
+ // 变更来源配置。自定义安装提交段持有来源锁,这次 addSource 必须排在落位后,
+ // 保证所选来源从提交前复核到落位完成之间保持稳定。
const order: string[] = [];
let markInstallEntered!: () => void;
const installEntered = new Promise<void>((resolve) => {
@@ -964,22 +974,31 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
}
});
- it('skips default installs while any custom source is unreadable', async () => {
+ it('keeps official default installs available while a custom source is unreadable', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'other-plugin' }]);
const h = harness([serverSummary({ defaultInstall: true })], [{ name: 'team-lib', dir }]);
- h.api.detail.mockResolvedValue(serverDetail());
- // 来源暂时不可读:合并冲突集合缺了它声明的 ghostId,此刻自动安装会在它恢复
- // 前抢占所有权——目录不完整时必须整体跳过默认安装。
+ h.api.download.mockResolvedValue({
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ });
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('server-plugin'),
+ dir: '/ghosts/server-plugin',
+ enabled: true,
+ });
+ // 来源暂时不可读只影响该来源,未安装的目录条目不能阻塞官方默认安装。
fs.rmSync(dir, { recursive: true, force: true });
await h.service.snapshot();
- expect(h.api.download).not.toHaveBeenCalled();
- expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.api.download).toHaveBeenCalled();
+ expect(runtime.install).toHaveBeenCalled();
});
- it('skips default installs while a single plugin entry is temporarily unreadable', async () => {
+ it('keeps official default installs available while one custom entry is unreadable', async () => {
// 粒度到条目:来源本身可读、清单也在,只是**某个插件的 ghost.json** 因文件锁/
// 权限/网络盘抖动暂时读不到。此前这类失败与"内容非法"共用静默跳过分支,目录
// 仍被判 complete,同 ghostId 的默认安装会在这个窗口里抢占所有权,恢复后该
@@ -992,7 +1011,17 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
{ rel: 'plugins/srv', id: 'unrelated-plugin' },
]);
const h = harness([serverSummary({ defaultInstall: true })], [{ name: 'team-lib', dir }]);
- h.api.detail.mockResolvedValue(serverDetail());
+ h.api.download.mockResolvedValue({
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ });
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('server-plugin'),
+ dir: '/ghosts/server-plugin',
+ enabled: true,
+ });
// EACCES 是可重试类错误(事实不明);注意不能用 ENOENT —— 那是"清单指向不存在
// 的目录"这种永久错误,按内容非法跳过才对(否则这类市场永久阻塞默认安装)。
// 路径必须按 realpath 拼:发现层用的是 realpath(macOS 上 /var → /private/var),
@@ -1009,8 +1038,8 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
}) as typeof fs.promises.open);
try {
await h.service.snapshot();
- expect(h.api.download).not.toHaveBeenCalled();
- expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.api.download).toHaveBeenCalled();
+ expect(runtime.install).toHaveBeenCalled();
} finally {
spy.mockRestore();
}
@@ -1025,26 +1054,75 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/gone', id: 'stale-entry' }]);
fs.rmSync(path.join(dir, 'plugins', 'gone'), { recursive: true, force: true });
const h = harness([serverSummary({ defaultInstall: true })], [{ name: 'team-lib', dir }]);
- h.api.detail.mockResolvedValue(serverDetail());
await h.service.snapshot();
// 与"不可读"组对称的信号:目录判为完整 → 默认安装照常进入下载阶段。
expect(h.api.download).toHaveBeenCalled();
});
- it('fails closed on manual installs while any custom source is unreadable', async () => {
+ it('keeps manual official installs available while a custom source is unreadable', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'other-plugin' }]);
const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
- h.api.detail.mockResolvedValue(serverDetail());
+ h.api.download.mockResolvedValue({
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ });
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('server-plugin'),
+ dir: '/ghosts/server-plugin',
+ enabled: true,
+ });
fs.rmSync(dir, { recursive: true, force: true });
const item = serverSummary();
await expect(
- h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
- ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ h.service.install(item.id, {
+ expectedReleaseId: item.currentRelease.id,
+ expectedManifest: ghostManifest(item.ghostId, item.currentRelease.version),
+ }),
+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
+ expect(h.api.download).toHaveBeenCalled();
+ });
+
+ it('does not let official market take over an installed custom plugin when its source is unreadable', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/x', id: 'server-plugin' },
+ ]);
+ const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
+ runtime.ghosts = [
+ { manifest: ghostManifest('server-plugin'), dir: '/ghosts/server-plugin', enabled: true },
+ ];
+ h.ledger.upsertInstallation({
+ pluginId: customMarketPluginId('team-lib', 'server-plugin'),
+ ghostId: 'server-plugin',
+ releaseId: customMarketReleaseId('team-lib', 'server-plugin', '1.0.0'),
+ version: '1.0.0',
+ sha256: 'custom-unverified',
+ scope: 'public',
+ organizationId: null,
+ source: 'local-market',
+ installed: true,
+ updatedAt: '2026-08-06T00:00:00.000Z',
+ sourceKey: marketSourceKey({ type: 'local', path: dir }),
+ manifestDigest: ghostManifestDigest(ghostManifest('server-plugin')),
+ });
+ fs.rmSync(dir, { recursive: true, force: true });
+
+ const item = serverSummary();
+ await expect(
+ h.service.install(item.id, {
+ expectedReleaseId: item.currentRelease.id,
+ expectedManifest: ghostManifest(item.ghostId, item.currentRelease.version),
+ }),
+ ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
expect(h.api.download).not.toHaveBeenCalled();
+ expect(runtime.install).not.toHaveBeenCalled();
});
it('adopts a matching install after a lost ledger write instead of dead-ending in conflict', async () => {
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 1aa3191e28..8c4c3378c0 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -4,7 +4,10 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { ghostPermissionBaselineKey } from '../../../shared/ghost.js';
+import {
+ diffGhostPermissionItems,
+ ghostPermissionBaselineKey,
+} from '../../../shared/ghost.js';
const runtime = vi.hoisted(() => ({
ghosts: [] as Array<{
@@ -143,13 +146,10 @@ function summary(
};
}
-function detail(item = summary(), slots: ['notify'] | ['notify', 'fs'] = ['notify']): VisiblePluginDetail {
+function reviewedInstallOptions(item: VisiblePluginSummary) {
return {
- ...item,
- currentRelease: {
- ...item.currentRelease,
- manifest: manifest(item.ghostId, item.currentRelease.version, slots),
- },
+ expectedReleaseId: item.currentRelease.id,
+ expectedManifest: manifest(item.ghostId, item.currentRelease.version),
};
}
@@ -179,7 +179,13 @@ function harness(
detail: vi.fn(async (pluginId: string) => {
const item = items.find((candidate) => candidate.id === pluginId);
if (!item) throw new Error('not found');
- return detail(item);
+ return {
+ ...item,
+ currentRelease: {
+ ...item.currentRelease,
+ manifest: manifest(item.ghostId, item.currentRelease.version),
+ },
+ } satisfies VisiblePluginDetail;
}),
download: vi.fn(async () => ({
url: 'https://downloads.test.invalid/plugin.cindy',
@@ -444,7 +450,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
{
ghostId: 'cindy-test',
version: '1.0.0',
- reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),
+ reviewedManifest: manifest(),
},
);
expect(snapshot.items[0]).toMatchObject({
@@ -458,41 +464,34 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
});
- it('backfills a missing digest only for an unchanged current market release', async () => {
- const item = summary({ scope: 'organization', organizationId: 'org-1' });
- const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-installed-'));
- roots.push(installDir);
- fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(manifest()));
- runtime.ghosts = [{ manifest: manifest(), dir: installDir, enabled: true }];
+ it('does not auto-install a default package with permissions absent from its catalog manifest', async () => {
+ const item = summary({ defaultInstall: true });
+ runtime.install.mockRejectedValueOnce(
+ new GhostPackagePermissionReviewRequiredError({
+ manifest: manifest(item.ghostId, item.currentRelease.version, ['notify', 'fs']),
+ permissionDiff: null,
+ packageSha256: item.currentRelease.sha256,
+ installedBaseline: null,
+ }),
+ );
const h = harness([item]);
- h.ledger.upsertInstallation({
- pluginId: item.id,
- ghostId: item.ghostId,
- releaseId: item.currentRelease.id,
- version: item.currentRelease.version,
- sha256: item.currentRelease.sha256,
- scope: item.scope,
- organizationId: item.organizationId,
- source: 'market',
- installed: true,
- updatedAt: '2026-07-27T00:00:00.000Z',
- });
- await h.service.snapshot();
+ const snapshot = await h.service.snapshot();
- expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
- source: 'market',
- manifestDigest: ghostManifestDigest(manifest()),
- });
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.stringMatching(/\.cindy$/),
+ expect.objectContaining({ reviewedManifest: manifest() }),
+ );
+ expect(snapshot.items[0]?.installState).toBe('not-installed');
+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
- it('does not backfill provenance when the installed manifest differs', async () => {
+ it('does not infer historical provenance from the server manifest', async () => {
const item = summary({ scope: 'organization', organizationId: 'org-1' });
- const changedManifest = manifest('cindy-test', '1.0.0', ['notify', 'fs']);
const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-installed-'));
roots.push(installDir);
- fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(changedManifest));
- runtime.ghosts = [{ manifest: changedManifest, dir: installDir, enabled: true }];
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(manifest()));
+ runtime.ghosts = [{ manifest: manifest(), dir: installDir, enabled: true }];
const h = harness([item]);
h.ledger.upsertInstallation({
pluginId: item.id,
@@ -523,25 +522,21 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- const { ghost } = await h.service.install(item.id, { expectedReleaseId: item.currentRelease.id });
+ const { ghost } = await h.service.install(item.id, reviewedInstallOptions(item));
expect(runtime.install).toHaveBeenCalledWith(
expect.stringMatching(/\.cindy$/),
{
ghostId: 'cindy-test',
version: '1.0.0',
- reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),
+ reviewedManifest: manifest(),
},
);
// 锁定装完即开的最终结果:装入入口返回的 ghost 必须是启用态。
expect(ghost?.enabled).toBe(true);
});
- // 装入确认框渲染的是**服务端给的** manifest,真正落地的是 .cindy 包里的
- // ghost.json。服务端投影层与客户端清单契约漂移时(cindy-protocol 那份平行
- // 校验器已经缺了 confirm 槽,新字段按「忽略未知字段」被静默丢掉),包会带着
- // 用户没审过的权限装进来。出口处需要这份 reviewedManifest 才能逐项比对拦下。
- it('passes the reviewed server manifest to the install entry so package permissions can be re-reviewed', async () => {
+ it('passes the reviewed server manifest to the package verification boundary', async () => {
const item = summary();
runtime.install.mockResolvedValue({
manifest: manifest(),
@@ -550,48 +545,42 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await h.service.install(item.id, { expectedReleaseId: item.currentRelease.id });
+ await h.service.install(item.id, reviewedInstallOptions(item));
- const passed = runtime.install.mock.calls[0]?.[1] as { reviewedManifest?: unknown };
- expect(passed.reviewedManifest).toBeDefined();
- // 必须是服务端那一份原文(确认框渲染的就是它),不是包里的或已装的。
- expect(passed.reviewedManifest).toMatchObject({
- id: item.ghostId,
- version: item.currentRelease.version,
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ reviewedManifest: manifest(),
});
});
- it('returns a recoverable package review result and forwards the bound approval on retry', async () => {
+ it('pauses one install transaction for package review and reuses the download', async () => {
const item = summary();
const review = {
manifest: manifest('cindy-test', '1.0.0', ['notify', 'fs']),
+ permissionDiff: null,
packageSha256: 'a'.repeat(64),
installedBaseline: null,
};
- runtime.install.mockRejectedValueOnce(
- new GhostPackagePermissionReviewRequiredError(review),
- );
+ runtime.install
+ .mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review))
+ .mockResolvedValueOnce({
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
const h = harness([item]);
+ const confirmReview = vi.fn(async () => true);
await expect(
- h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
- ).resolves.toEqual({ reviewRequired: review });
- expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
-
- runtime.install.mockResolvedValueOnce({
- manifest: manifest(),
- dir: '/userData/cindy-brain/cindy-test',
- enabled: true,
- });
- await expect(
- h.service.install(item.id, {
- expectedReleaseId: item.currentRelease.id,
- approvedPackageSha256: review.packageSha256,
- }),
+ h.service.install(item.id, reviewedInstallOptions(item), confirmReview),
).resolves.toMatchObject({ ghost: { manifest: { id: item.ghostId } } });
+ expect(confirmReview).toHaveBeenCalledWith(review);
+ expect(h.api.download).toHaveBeenCalledTimes(1);
expect(runtime.install).toHaveBeenLastCalledWith(
expect.stringMatching(/\.cindy$/),
- expect.objectContaining({ approvedPackageSha256: review.packageSha256 }),
+ expect.objectContaining({
+ reviewedManifest: manifest(),
+ approvedPackageSha256: review.packageSha256,
+ }),
);
});
@@ -599,6 +588,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
const item = summary();
const review = {
manifest: manifest('cindy-test', '1.0.0', ['notify', 'fs']),
+ permissionDiff: null,
packageSha256: 'a'.repeat(64),
installedBaseline: null,
};
@@ -613,12 +603,12 @@ describe('PluginMarketService migration and defaultInstall', () => {
const h = harness([item]);
await expect(
- h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ h.service.install(item.id, reviewedInstallOptions(item)),
).rejects.toThrow('[PRECONDITION_FAILED]');
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
- it('uses a digest-matched installed manifest as the legacy approval baseline', async () => {
+ it('uses the installed raw manifest as the package permission baseline', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
@@ -646,14 +636,14 @@ describe('PluginMarketService migration and defaultInstall', () => {
manifestDigest: ghostManifestDigest(installed),
});
- await h.service.install(item.id, { expectedReleaseId: item.currentRelease.id });
+ await h.service.install(item.id, reviewedInstallOptions(item));
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
- previouslyInstalledManifest: installed,
+ permissionBaselineManifest: installed,
});
});
- it('does not use a changed installed manifest as an approval baseline', async () => {
+ it('does not let a stale official record claim a locally changed package', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
@@ -662,11 +652,6 @@ describe('PluginMarketService migration and defaultInstall', () => {
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),
@@ -675,12 +660,14 @@ describe('PluginMarketService migration and defaultInstall', () => {
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');
+ expect((await h.service.snapshot()).items[0]?.installState).toBe('conflict');
+ await expect(
+ h.service.install(item.id, reviewedInstallOptions(item)),
+ ).rejects.toThrow('[ALREADY_EXISTS]');
+ expect(runtime.install).not.toHaveBeenCalled();
});
- it('does not use a legacy ledger record without an authenticated manifest digest', async () => {
+ it('does not trust an installed manifest as the permission baseline without a digest', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
@@ -702,9 +689,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
version: '1.0.0',
});
- await h.service.install(item.id, { expectedReleaseId: item.currentRelease.id });
+ await h.service.install(item.id, reviewedInstallOptions(item));
- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('previouslyInstalledManifest');
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');
});
it('installs and enables a public defaultInstall package in local mode', async () => {
@@ -732,7 +719,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
{
ghostId: item.ghostId,
version: item.currentRelease.version,
- reviewedManifest: expect.objectContaining({ id: item.ghostId }),
+ reviewedManifest: manifest(),
},
);
expect(snapshot.items[0]).toMatchObject({
@@ -755,7 +742,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).resolves.toMatchObject({
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({
ghost: { manifest: { id: 'cindy-test' }, enabled: false },
});
expect(h.api.download).toHaveBeenCalledWith(item.id, item.currentRelease.id);
@@ -780,9 +767,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const order: string[] = [];
- const installing = h.service.install(item.id, {
- expectedReleaseId: item.currentRelease.id,
- });
+ const installing = h.service.install(item.id, reviewedInstallOptions(item));
// 等安装推进到持锁并阻塞在 runtime.install 上。
await vi.waitFor(() => expect(runtime.install).toHaveBeenCalled());
const outsider = withGhostInstallLock(item.ghostId, async () => {
@@ -814,8 +799,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[NOT_FOUND]');
- expect(h.api.detail).not.toHaveBeenCalled();
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[NOT_FOUND]');
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1234,11 +1218,37 @@ describe('PluginMarketService migration and defaultInstall', () => {
installed: false,
});
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[ALREADY_EXISTS]');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[ALREADY_EXISTS]');
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('does not overwrite a local plugin that appears while an official package downloads', async () => {
+ const item = summary();
+ const h = harness([item]);
+ h.api.download.mockImplementationOnce(async () => {
+ runtime.ghosts = [
+ {
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ },
+ ];
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ });
+
+ await expect(
+ h.service.install(item.id, reviewedInstallOptions(item)),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
- it('requires an explicit reviewed flag before an update can add permissions', async () => {
+ it('continues the same update transaction after real-package approval', async () => {
const item = summary({
currentRelease: {
...summary().currentRelease,
@@ -1253,41 +1263,42 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: true,
},
];
- runtime.install.mockResolvedValue({
- manifest: manifest('cindy-test', '2.0.0', ['notify', 'fs']),
- dir: '/userData/cindy-brain/cindy-test',
- enabled: true,
- });
+ const targetManifest = manifest('cindy-test', '2.0.0', ['notify', 'fs']);
+ const review = {
+ manifest: targetManifest,
+ permissionDiff: diffGhostPermissionItems(manifest(), targetManifest),
+ packageSha256: 'a'.repeat(64),
+ installedBaseline: ghostPermissionBaselineKey(manifest()),
+ };
+ runtime.install
+ .mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review))
+ .mockResolvedValueOnce({
+ manifest: review.manifest,
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
const h = harness([item]);
h.ledger.upsertInstallation({
...recordForTest(item),
releaseId: 'release-1',
version: '1.0.0',
});
- h.api.detail.mockResolvedValue(detail(item, ['notify', 'fs']));
-
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[PRECONDITION_FAILED]');
- expect(runtime.install).not.toHaveBeenCalled();
+ const confirmReview = vi.fn(async () => true);
await expect(
- h.service.install(item.id, {
- expectedReleaseId: item.currentRelease.id,
- allowPermissionExpansion: true,
- }),
+ h.service.install(item.id, reviewedInstallOptions(item), confirmReview),
).resolves.toMatchObject({
ghost: { manifest: { version: '2.0.0' } },
});
- expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(confirmReview).toHaveBeenCalledWith(review);
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(runtime.install).toHaveBeenCalledTimes(2);
});
- it('re-checks the reviewed baseline inside the install lock before honouring an expansion', async () => {
+ it('cancels the current transaction when real-package approval is declined', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
- // 用户审阅时的已装 manifest 是 notify+fs(相对目标包没有新增权限);
- // IPC 往返期间「从文件更新」把它换成了只有 notify 的包——此刻目标包相对
- // **当前**已装多出 fs,而这条权限用户从没审过。旧批准不得放行它。
- const reviewedInstalled = manifest('cindy-test', '1.0.0', ['notify', 'fs']);
runtime.ghosts = [
{
manifest: manifest(),
@@ -1295,41 +1306,37 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: true,
},
];
- runtime.install.mockResolvedValue({
+ const review = {
manifest: manifest('cindy-test', '2.0.0', ['notify', 'fs']),
- dir: '/userData/cindy-brain/cindy-test',
- enabled: true,
- });
+ permissionDiff: diffGhostPermissionItems(
+ manifest(),
+ manifest('cindy-test', '2.0.0', ['notify', 'fs']),
+ ),
+ packageSha256: 'a'.repeat(64),
+ installedBaseline: ghostPermissionBaselineKey(manifest()),
+ };
+ runtime.install.mockRejectedValueOnce(
+ new GhostPackagePermissionReviewRequiredError(review),
+ );
const h = harness([item]);
h.ledger.upsertInstallation({ ...recordForTest(item), releaseId: 'release-1', version: '1.0.0' });
- h.api.detail.mockResolvedValue(detail(item, ['notify', 'fs']));
-
- await expect(
- h.service.install(item.id, {
- expectedReleaseId: item.currentRelease.id,
- allowPermissionExpansion: true,
- reviewedBaseline: ghostPermissionBaselineKey(reviewedInstalled),
- }),
- ).rejects.toThrow('[PRECONDITION_FAILED]');
- expect(runtime.install).not.toHaveBeenCalled();
- // 基线与当前已装一致时照常放行(正常批准路径不被这道复核破坏)。
await expect(
- h.service.install(item.id, {
- expectedReleaseId: item.currentRelease.id,
- allowPermissionExpansion: true,
- reviewedBaseline: ghostPermissionBaselineKey(manifest()),
- }),
- ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
+ h.service.install(item.id, reviewedInstallOptions(item), async () => false),
+ ).resolves.toEqual({ cancelled: true });
+ expect(h.api.download).toHaveBeenCalledTimes(1);
expect(runtime.install).toHaveBeenCalledTimes(1);
});
- it('re-checks the baseline inside the install lock when the download window is raced', async () => {
+ it('does not trust the current installed package without a digest after download', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
- // 审阅时已装 notify+fs:相对目标包没有新增权限,批准是"空头"批准。
const reviewedInstalled = manifest('cindy-test', '1.0.0', ['notify', 'fs']);
+ const currentInstalled = manifest('cindy-test', '1.0.0', ['notify']);
+ const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-ghost-'));
+ roots.push(installedDir);
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(currentInstalled));
runtime.ghosts = [
{ manifest: reviewedInstalled, dir: '/userData/cindy-brain/cindy-test', enabled: true },
];
@@ -1338,29 +1345,20 @@ describe('PluginMarketService migration and defaultInstall', () => {
dir: '/userData/cindy-brain/cindy-test',
enabled: true,
});
- // 下载窗口期(锁外复核已通过之后)本地 ghosts:update 把已装换成只有 notify
- // 的包——此刻目标包相对当前已装多出 fs,而这条从没被审阅过。
const downloadMock = vi.mocked(
(await import('../download.js')).downloadVerifiedPlugin,
);
downloadMock.mockImplementationOnce(async () => {
runtime.ghosts = [
- { manifest: manifest(), dir: '/userData/cindy-brain/cindy-test', enabled: true },
+ { manifest: currentInstalled, dir: installedDir, enabled: true },
];
});
const h = harness([item]);
h.ledger.upsertInstallation({ ...recordForTest(item), releaseId: 'release-1', version: '1.0.0' });
- h.api.detail.mockResolvedValue(detail(item, ['notify', 'fs']));
-
await expect(
- h.service.install(item.id, {
- expectedReleaseId: item.currentRelease.id,
- allowPermissionExpansion: true,
- reviewedBaseline: ghostPermissionBaselineKey(reviewedInstalled),
- }),
- ).rejects.toThrow('[PRECONDITION_FAILED]');
- // 锁内复核发生在落位之前:并发替换绕不过旧批准。
- expect(runtime.install).not.toHaveBeenCalled();
+ h.service.install(item.id, reviewedInstallOptions(item)),
+ ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');
});
it('rejects an update when the installed target disappears during download', async () => {
@@ -1390,7 +1388,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
await expect(
- h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ h.service.install(item.id, reviewedInstallOptions(item)),
).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1406,14 +1404,10 @@ describe('PluginMarketService migration and defaultInstall', () => {
},
});
const h = harness([reviewed]);
- // listAll 仍让该 plugin 对当前用户可见;detail 在确认后已切到新 release。
- h.api.detail.mockResolvedValue(detail(replacement, ['notify', 'fs']));
+ h.api.listAll.mockResolvedValueOnce({ plugins: [replacement], removals: [] });
await expect(
- h.service.install(reviewed.id, {
- expectedReleaseId: reviewed.currentRelease.id,
- allowPermissionExpansion: true,
- }),
+ h.service.install(reviewed.id, reviewedInstallOptions(reviewed)),
).rejects.toThrow('[PRECONDITION_FAILED]');
expect(h.api.download).not.toHaveBeenCalled();
expect(runtime.install).not.toHaveBeenCalled();
@@ -1429,7 +1423,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
sizeBytes: item.currentRelease.sizeBytes,
});
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1445,7 +1439,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
return { plugins: [item], removals: [] };
});
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
@@ -1468,7 +1462,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
return installedGhost;
});
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).resolves.toEqual({
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toEqual({
ghost: installedGhost,
});
expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-manager.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-manager.test.ts
index 1265f36cb7..e37941d99b 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/sources-manager.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-manager.test.ts
@@ -87,6 +87,8 @@ describe('MarketSourceManager local sources', () => {
expect(added).toMatchObject({
name: 'local-lib',
pluginCount: 1,
+ skippedCount: 0,
+ unreadableCount: 0,
status: 'ok',
});
expect(added.source).toEqual({ type: 'local', path: market });
@@ -96,6 +98,26 @@ describe('MarketSourceManager local sources', () => {
expect(list[0]?.name).toBe('local-lib');
});
+ it('reports skipped entries separately from an empty marketplace', async () => {
+ const root = makeRoot();
+ const market = path.join(root, 'my-market');
+ writeMarketplace(market, 'local-lib', [{ rel: 'plugins/a', id: 'alpha' }]);
+ const manifestPath = path.join(market, '.agents', 'plugins', 'marketplace.json');
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as {
+ plugins: Array<{ name: string; source: string }>;
+ };
+ manifest.plugins.push({ name: 'missing', source: 'plugins/missing' });
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));
+
+ const summary = await makeManager(root).addSource({ source: market });
+ expect(summary).toMatchObject({
+ pluginCount: 1,
+ skippedCount: 1,
+ unreadableCount: 0,
+ status: 'ok',
+ });
+ });
+
it('rejects a local source that is not a directory', async () => {
const manager = makeManager(makeRoot());
await expect(
@@ -145,6 +167,8 @@ describe('MarketSourceManager local sources', () => {
const list = await manager.listSources();
expect(list[0]?.status).toBe('error');
expect(list[0]?.errorCode).toBe('MARKET_SOURCE_INVALID');
+ expect(list[0]?.skippedCount).toBe(0);
+ expect(list[0]?.unreadableCount).toBe(0);
});
it('refreshes local sources by rescanning the manifest', async () => {
diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.ts
index 99122d8353..d450f0a9a9 100644
--- a/apps/desktop/src/main/plugin-market/install.ts
+++ b/apps/desktop/src/main/plugin-market/install.ts
@@ -59,17 +59,16 @@ export async function installCustomMarketPlugin(input: {
* 打包完成后、实际改动 Ghost 运行时之前调用的校验钩(可异步)。
* 自定义市场按调用方捕获的账户审阅 manifest;打包是异步的,装出前必须
* 重新确认会话未漂移,避免把 A 审阅的插件装进当前账户 B 的运行时。
- * 跨来源 ghostId 所有权也在这里复核——打包耗时,期间另一窗口可能添加了
- * 声明同一 ghostId 的来源。
+ * 这里同时复核当前账号、所选来源和运行时已安装插件事实。
*/
beforeCommit?: () => void | Promise<void>;
/**
* 提交段(复核 + 落位)的互斥包装,与来源增删共享同一把锁。
*
* 只在 `beforeCommit` 里复核不够:它返回后 `installOrUpdateMarketGhostPackage`
- * 还要先 await 包检查才开始真正改动运行时,那段时间另一窗口仍能添加声明同一
- * ghostId 的来源,复核结论在落位前就过期了。把"复核 + 落位"整段放进锁里,
- * 来源变更插不进来。
+ * 还要先 await 包检查才开始真正改动运行时,那段时间另一窗口仍能移除或替换
+ * 所选来源,复核结论在落位前就过期了。把“复核 + 落位”整段放进锁里,来源
+ * 变更插不进来。
*/
withCommitLock?: <T>(fn: () => Promise<T>) => Promise<T>;
/**
@@ -159,13 +158,12 @@ export async function installCustomMarketPlugin(input: {
'Plugin changed after permission review',
);
}
- // 装出前最后防线:打包期间账号可能已切换、也可能有别的来源声明了同一 ghostId。
+ // 装出前最后防线:打包期间账号、所选来源或运行时插件状态都可能已变化。
// 复核与落位必须在同一把锁内完成,否则复核结论会在落位前过期。
const commit = async (): Promise<InstalledGhost> => {
await input.beforeCommit?.();
- // 这里不传 reviewedManifest:上面那道逐字节比对(packed.manifest ===
- // input.expected)比出口处的逐项权限比对**更强**,自定义来源不存在服务端
- // 那种「投影层丢字段」的漂移面。传了是死代码,不传不是漏改。
+ // 自定义来源已经把 Renderer 审阅的本地清单与实际打包清单逐字节绑定,
+ // 不再进入官方市场“下载真实包后复核”的分支。
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: validated.manifest.id,
version: validated.manifest.version,
diff --git a/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.ts b/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.ts
new file mode 100644
index 0000000000..750d967d53
--- /dev/null
+++ b/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.ts
@@ -0,0 +1,64 @@
+/**
+ * 官方市场真实包权限确认的 Main ↔ Renderer 往返桥。
+ *
+ * 它只保存“当前窗口对当前弹框的回答”,不保存包路径、安装状态或批准记录。
+ * 安装事务本身仍停在 service.install() 的调用栈里;确认、取消或窗口销毁后,
+ * promise 立即结算,service 的 finally 负责删除临时包。
+ */
+
+import { randomUUID } from 'node:crypto';
+
+import type {
+ PluginMarketPackageReviewFacts,
+ PluginMarketPackageReviewRequest,
+} from '../../shared/pluginMarket.js';
+
+interface PendingReview {
+ requesterId: number;
+ resolve: (confirmed: boolean) => void;
+}
+
+export class PluginMarketPackagePermissionReviewBridge {
+ private readonly pending = new Map<string, PendingReview>();
+
+ request(
+ requesterId: number,
+ facts: PluginMarketPackageReviewFacts,
+ send: (request: PluginMarketPackageReviewRequest) => boolean,
+ ): Promise<boolean> {
+ const requestId = randomUUID();
+ return new Promise<boolean>((resolve) => {
+ this.pending.set(requestId, { requesterId, resolve });
+ let delivered = false;
+ try {
+ delivered = send({
+ requestId,
+ manifest: facts.manifest,
+ permissionDiff: facts.permissionDiff,
+ });
+ } finally {
+ if (!delivered) this.settle(requestId, false);
+ }
+ });
+ }
+
+ resolve(requesterId: number, requestId: string, confirmed: unknown): boolean {
+ const pending = this.pending.get(requestId);
+ if (!pending || pending.requesterId !== requesterId) return false;
+ this.settle(requestId, confirmed === true);
+ return true;
+ }
+
+ cancelRequester(requesterId: number): void {
+ for (const [requestId, pending] of this.pending) {
+ if (pending.requesterId === requesterId) this.settle(requestId, false);
+ }
+ }
+
+ private settle(requestId: string, confirmed: boolean): void {
+ const pending = this.pending.get(requestId);
+ if (!pending) return;
+ this.pending.delete(requestId);
+ pending.resolve(confirmed);
+ }
+}
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 8462cad98f..8a580fcbf9 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -1,6 +1,6 @@
import os from 'node:os';
-import { ipcMain } from 'electron';
+import { ipcMain, type WebContents } from 'electron';
import { isIpcError } from '../../shared/ipc-errors.js';
import type { GhostManifest } from '../../shared/ghost.js';
@@ -12,12 +12,16 @@ import { createLogger } from '../logger.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { requireObject, requireString, throwIpcError } from '../utils/ipcValidate.js';
import { parseMarketSource } from './sources/parse.js';
+import { PluginMarketPackagePermissionReviewBridge } from './packagePermissionReviewBridge.js';
import { PluginMarketService } from './service.js';
const log = createLogger('plugin-market-ipc');
let registered = false;
let serviceSingleton: PluginMarketService | null = null;
const REMOVAL_NOTICE_AVAILABLE_CHANNEL = 'plugin-market:removal-notice-available';
+const PACKAGE_PERMISSION_REVIEW_CHANNEL = 'plugin-market:package-permission-review';
+const trackedReviewRequesters = new WeakSet<WebContents>();
+const packagePermissionReviewBridge = new PluginMarketPackagePermissionReviewBridge();
function service(): PluginMarketService {
serviceSingleton ??= new PluginMarketService();
@@ -71,6 +75,21 @@ async function invokePluginMarket<T>(operation: () => Promise<T>): Promise<T> {
}
}
+function trackPackageReviewRequester(contents: WebContents): void {
+ if (trackedReviewRequesters.has(contents)) return;
+ trackedReviewRequesters.add(contents);
+ const requesterId = contents.id;
+ const cancelPending = () => packagePermissionReviewBridge.cancelRequester(requesterId);
+ contents.once('destroyed', cancelPending);
+ contents.on('render-process-gone', cancelPending);
+ contents.on(
+ 'did-start-navigation',
+ (_event, _url, isSameDocument, isMainFrame) => {
+ if (isMainFrame && !isSameDocument) cancelPending();
+ },
+ );
+}
+
/** 注册 renderer 可用的只读市场与显式安装/卸载写路径。 */
export function registerPluginMarketIpc(): void {
if (registered) return;
@@ -96,6 +115,7 @@ export function registerPluginMarketIpc(): void {
'plugin-market:install',
(event, pluginId: unknown, options: unknown) => {
assertTrustedAppRendererEvent(event);
+ trackPackageReviewRequester(event.sender);
const obj =
typeof options === 'object' && options !== null
? (options as {
@@ -103,39 +123,52 @@ export function registerPluginMarketIpc(): void {
expectedManifest?: unknown;
allowPermissionExpansion?: unknown;
reviewedBaseline?: unknown;
- approvedPackageSha256?: unknown;
})
: null;
const expectedReleaseId = requireString(obj?.expectedReleaseId, 'expectedReleaseId');
- const expectedManifest =
- obj?.expectedManifest === undefined || obj?.expectedManifest === null
- ? undefined
- : requireObject(obj.expectedManifest);
+ const expectedManifest = requireObject(obj?.expectedManifest);
const allowPermissionExpansion = obj?.allowPermissionExpansion === true;
// 扩权批准的审阅基线:只收字符串,野值按缺席处理(缺席 = 保持旧行为)。
const reviewedBaseline =
typeof obj?.reviewedBaseline === 'string' ? obj.reviewedBaseline : undefined;
- const approvedPackageSha256 =
- typeof obj?.approvedPackageSha256 === 'string'
- ? obj.approvedPackageSha256
- : undefined;
- if (
- approvedPackageSha256 !== undefined &&
- !/^[a-f0-9]{64}$/.test(approvedPackageSha256)
- ) {
- throwIpcError('INVALID_PARAMS', 'approvedPackageSha256 is invalid');
- }
return invokePluginMarket(() =>
- service().install(requireString(pluginId, 'pluginId'), {
- expectedReleaseId,
- ...(expectedManifest ? { expectedManifest: expectedManifest as unknown as GhostManifest } : {}),
- allowPermissionExpansion,
- ...(reviewedBaseline !== undefined ? { reviewedBaseline } : {}),
- ...(approvedPackageSha256 !== undefined ? { approvedPackageSha256 } : {}),
- }),
+ service().install(
+ requireString(pluginId, 'pluginId'),
+ {
+ expectedReleaseId,
+ expectedManifest: expectedManifest as unknown as GhostManifest,
+ allowPermissionExpansion,
+ ...(reviewedBaseline !== undefined ? { reviewedBaseline } : {}),
+ },
+ (facts) =>
+ packagePermissionReviewBridge.request(
+ event.sender.id,
+ facts,
+ (request) => {
+ if (event.sender.isDestroyed()) return false;
+ event.sender.send(PACKAGE_PERMISSION_REVIEW_CHANNEL, request);
+ return true;
+ },
+ ),
+ ),
);
},
);
+ ipcMain.handle('plugin-market:resolve-package-permission-review', (event, raw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const payload = requireObject(raw);
+ const requestId = requireString(payload.requestId, 'requestId');
+ if (requestId.length > 128) {
+ throwIpcError('INVALID_PARAMS', 'requestId is too long');
+ }
+ return {
+ handled: packagePermissionReviewBridge.resolve(
+ event.sender.id,
+ requestId,
+ payload.confirmed,
+ ),
+ };
+ });
ipcMain.handle('plugin-market:uninstall', (event, pluginId: unknown) => {
assertTrustedAppRendererEvent(event);
return invokePluginMarket(() =>
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 8411396351..a7c5dcfe3b 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -25,6 +25,7 @@ import type {
PluginMarketInstallOptions,
PluginMarketInstallResult,
PluginMarketItem,
+ PluginMarketPackageReviewFacts,
PluginMarketSnapshot,
PluginRemovalUserNotice,
} from '../../shared/pluginMarket.js';
@@ -71,20 +72,23 @@ import { MarketSourceManager } from './sources/index.js';
import { MarketSourceStore } from './sources/store.js';
const log = createLogger('plugin-market');
-const NO_DUPLICATE_GHOST_IDS: ReadonlySet<string> = new Set();
+
+type PackagePermissionReviewer = (
+ facts: PluginMarketPackageReviewFacts,
+) => Promise<boolean>;
/**
- * 来源增删改的互斥键。**安装的提交段(所有权复核 + 包落位)也要拿这把锁**:
- * 否则复核通过后、真正改动 Ghost 运行时之前,另一窗口能添加声明同一 ghostId 的
- * 来源,让已冲突的插件照样装上。
+ * 来源增删改的互斥键。自定义市场安装的提交段也要拿这把锁,保证所选来源从
+ * 复核到包落位之间不会被移除或替换。官方市场安装不依赖自定义市场目录,不能
+ * 拿这把锁,否则一次慢刷新就会无关地拖住官方插件安装。
*
* **锁次序(不变量,违反即死锁)**:允许 `withMutation(pluginId)` 内再取本键
* (安装路径就是这么做的),**禁止**持本键时再取任何 pluginId 键。来源操作
* (add/remove/refresh)只拿本键,永不反向,因此锁图无环。
*
- * **已知权衡**:refreshSource 全程持本键,大仓库 clone 期间(可达分钟级)安装的
- * 提交段与其它来源操作会排队。这是有意选择——只读路径(快照/列表/详情)不受
- * 影响,而把刷新的网络段移出锁会重新打开"提交点复核过期"的窗口;吞吐不构成
+ * **已知权衡**:refreshSource 全程持本键,大仓库 clone 期间(可达分钟级)自定义
+ * 市场安装的提交段与其它来源操作会排队。只读路径和官方市场安装不受影响;
+ * 把刷新的网络段移出锁会重新打开“所选来源在提交前被替换”的窗口;吞吐不构成
* 放宽正确性的理由。
*/
const SOURCE_MUTATION_KEY = 'market-sources';
@@ -178,6 +182,25 @@ function recordFrom(
};
}
+/** 列表与详情是两次请求;安装前必须确认两次看到的是同一份发布。 */
+function assertDetailMatchesSummary(
+ summary: VisiblePluginSummary,
+ detail: VisiblePluginDetail,
+): void {
+ if (
+ detail.id !== summary.id ||
+ detail.ghostId !== summary.ghostId ||
+ detail.scope !== summary.scope ||
+ detail.organizationId !== summary.organizationId ||
+ detail.currentRelease.id !== summary.currentRelease.id ||
+ detail.currentRelease.version !== summary.currentRelease.version ||
+ detail.currentRelease.sha256 !== summary.currentRelease.sha256 ||
+ detail.currentRelease.sizeBytes !== summary.currentRelease.sizeBytes
+ ) {
+ throwIpcError('PRECONDITION_FAILED', 'Plugin release changed while loading details');
+ }
+}
+
/**
* Claims a trusted legacy install without pretending its bytes came from the
* current market release. A synthetic release id keeps the local version
@@ -220,20 +243,6 @@ interface CustomMarketEntry {
plugin: DiscoveredMarketPlugin;
}
-/** 服务端目录 + 自定义市场合并后的重复 ghostId 集合。 */
-function combinedDuplicateGhostIds(
- plugins: readonly VisiblePluginSummary[],
- customEntries: readonly CustomMarketEntry[],
-): ReadonlySet<string> {
- const counts = ghostIdCounts(plugins);
- for (const entry of customEntries) {
- counts.set(entry.plugin.ghostId, (counts.get(entry.plugin.ghostId) ?? 0) + 1);
- }
- return new Set(
- [...counts.entries()].filter(([, count]) => count > 1).map(([ghostId]) => ghostId),
- );
-}
-
/**
* 已安装插件的 locale 无关 manifest 摘要。运行时 `InstalledGhost.manifest` 是
* **按当前界面语言本地化后的**(GhostManager.readInstalledLocalizedManifest),
@@ -273,6 +282,25 @@ function installedGhostRawManifestDigest(dir: string): string | null {
return manifest ? ghostManifestDigest(manifest) : null;
}
+/** 官方市场是否仍拥有当前落地包;带摘要的新记录必须与磁盘事实一致。 */
+function serverMarketOwnsInstalledGhost(
+ pluginId: string,
+ ghost: InstalledGhost,
+ record: PluginMarketInstallationRecord | null,
+): boolean {
+ if (
+ !record?.installed ||
+ (record.source !== 'market' && record.source !== 'legacy-adopted') ||
+ record.pluginId !== pluginId
+ ) {
+ return false;
+ }
+ return (
+ record.manifestDigest === undefined ||
+ record.manifestDigest === installedGhostRawManifestDigest(ghost.dir)
+ );
+}
+
/** Stable local facts reused while projecting one market catalog response. */
interface LocalInstallSnapshot {
/** Installed Ghost runtime facts indexed once for one market operation. */
@@ -334,8 +362,7 @@ export class PluginMarketService {
customSourceNames: [],
};
}
- const { entries: customEntries, complete: customComplete } =
- await this.discoverCustomEntriesSafe(owner);
+ const customEntries = await this.discoverCustomEntriesSafe(owner);
const customSourceNames = this.customSourceNamesSafe(owner);
requireSameMarketOwner(owner);
if (!getClientEndpoint('pluginApiBaseUrl')) {
@@ -367,28 +394,16 @@ export class PluginMarketService {
requireSameMarketOwner(owner);
const ledger = this.ledgerForOwner(owner);
- // ghostId 冲突判定跨服务端与自定义市场合并计算(全局唯一、先装先得)。
- // 必须**先于** applyDefaultInstalls 算出来:默认安装会真的下载并启用插件,
- // 若只按服务端目录判重,与自定义来源同 ghostId 的默认项会被静默抢占所有权,
- // 而列表随后又把它标成 conflict —— 既定事实已经发生。
- const duplicateGhostIds = combinedDuplicateGhostIds(plugins, customEntries);
await this.adoptLegacyInstallations(plugins, ledger, owner);
- await this.migrateMarketManifestDigests(plugins, ledger, owner);
await this.reconcileRemovedInstallations(ledger, owner);
await this.applyServerRemovals(removals, owner, ledger);
- // 自定义目录不完整(某来源暂时不可读)时跳过全部默认安装:此刻的合并冲突
- // 集合缺了坏来源声明的 ghostId,自动安装会在它恢复前抢占所有权。
- if (customComplete) {
- await this.applyDefaultInstalls(plugins, owner, ledger, duplicateGhostIds);
- } else {
- log.warn('skipping default installs: custom marketplace catalog is incomplete');
- }
+ // 自定义来源只影响自己的目录发现;暂时不可读的来源不能阻塞官方默认安装。
+ // 已经落地的同 id 插件仍由 applyDefaultInstalls → installDetail 的本地事实检查保护。
+ await this.applyDefaultInstalls(plugins, owner, ledger);
requireSameMarketOwner(owner);
const local = this.localInstallSnapshot(ledger);
- const serverItems = plugins.map((plugin) =>
- this.toItem(plugin, duplicateGhostIds, local),
- );
- const items = [...serverItems, ...this.projectCustomItems(customEntries, duplicateGhostIds, local)];
+ const serverItems = plugins.map((plugin) => this.toItem(plugin, local));
+ const items = [...serverItems, ...this.projectCustomItems(customEntries, local)];
// 聚合完成、返回 Renderer 前最后校验:账号在任一 await 间隙漂移则拒绝,
// 不把按旧账号解析的自定义项/账本状态发给当前会话。
requireSameMarketOwner(owner);
@@ -425,8 +440,15 @@ export class PluginMarketService {
}
this.requireConfigured();
return this.runForOwner(async (owner) => {
+ const catalog = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);
+ requireSameMarketOwner(owner);
+ const summary = catalog.find((candidate) => candidate.id === pluginId);
+ if (!summary) {
+ throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');
+ }
const plugin = await this.api.detail(pluginId);
requireSameMarketOwner(owner);
+ assertDetailMatchesSummary(summary, plugin);
if (owner.mode === 'local' && plugin.scope !== 'public') {
throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');
}
@@ -434,16 +456,8 @@ export class PluginMarketService {
if (!compatible.ok) {
throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
}
- // 详情必须与列表同口径:传空重复集合会把列表标为 conflict 并禁用的项
- // 在详情页恢复成可安装,给出一条绕过冲突闸的入口。
- const { duplicates } = await this.crossSourceDuplicateGhostIds(owner);
- requireSameMarketOwner(owner);
return {
- ...this.toItem(
- plugin,
- duplicates,
- this.localInstallSnapshot(this.ledgerForOwner(owner)),
- ),
+ ...this.toItem(plugin, this.localInstallSnapshot(this.ledgerForOwner(owner))),
manifest: compatible.manifest,
};
});
@@ -452,13 +466,11 @@ export class PluginMarketService {
async install(
pluginId: string,
options: PluginMarketInstallOptions,
+ reviewPackagePermissions?: PackagePermissionReviewer,
): Promise<PluginMarketInstallResult> {
const customRef = parseCustomMarketPluginId(pluginId);
if (customRef) {
- if (!options.expectedManifest) {
- throwIpcError('INVALID_PARAMS', 'The reviewed Plugin manifest is required');
- }
- return this.customInstall(customRef, options as typeof options & { expectedManifest: GhostManifest });
+ return this.customInstall(customRef, options);
}
if (!isValidPluginResourceId(pluginId)) {
throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');
@@ -481,56 +493,43 @@ export class PluginMarketService {
}
const plugin = await this.api.detail(pluginId);
requireSameMarketOwner(owner);
+ assertDetailMatchesSummary(selected, plugin);
if (plugin.currentRelease.id !== options.expectedReleaseId) {
throwIpcError(
'PRECONDITION_FAILED',
'Plugin release changed after permission review',
);
}
+ const compatible = validateGhostManifest(plugin.currentRelease.manifest);
+ const reviewed = validateGhostManifest(options.expectedManifest);
+ if (
+ !compatible.ok ||
+ !reviewed.ok ||
+ ghostManifestDigest(compatible.manifest) !== ghostManifestDigest(reviewed.manifest)
+ ) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin manifest changed after permission review',
+ );
+ }
const existing = getGhostManager()
.list()
- .some((ghost) => ghost.manifest.id === plugin.ghostId);
- // 上面只查了服务端目录内部重名。列表的 conflict 判定是"服务端 + 全部自定义
- // 来源"合并计数,这里必须用同一口径重算,否则被标为 conflict 并禁用的服务端
- // 项仍能经普通 UI 流程或直接 IPC 装进来并抢占 ghostId。
- const record = ledger.installationForGhost(plugin.ghostId);
- const ownsInstall = Boolean(
- existing && record?.installed && record.pluginId === plugin.id,
+ .find((ghost) => ghost.manifest.id === plugin.ghostId);
+ const ghost = await this.installDetail(
+ plugin,
+ {
+ expectedInstalled: Boolean(existing),
+ reviewedManifest: compatible.manifest,
+ allowPermissionExpansion: options.allowPermissionExpansion === true,
+ reviewPackagePermissions,
+ ...(options.reviewedBaseline !== undefined
+ ? { reviewedBaseline: options.reviewedBaseline }
+ : {}),
+ },
+ owner,
+ ledger,
);
- const assertOwnership = () =>
- this.assertSourceOwnsGhostId({
- owner,
- ghostId: plugin.ghostId,
- ownsInstall,
- // 复用已拉到的目录,复核不再多打一次网络请求。
- knownServerPlugins: catalog,
- });
- await assertOwnership();
- return {
- ghost: await this.installDetail(
- plugin,
- {
- expectedInstalled: existing,
- allowPermissionExpansion: options.allowPermissionExpansion === true,
- ...(options.reviewedBaseline !== undefined
- ? { reviewedBaseline: options.reviewedBaseline }
- : {}),
- ...(options.approvedPackageSha256 !== undefined
- ? { approvedPackageSha256: options.approvedPackageSha256 }
- : {}),
- // 下载可能持续数分钟,提交副作用前按当前事实再算一次。
- recheckOwnership: assertOwnership,
- },
- owner,
- ledger,
- ),
- };
- }).catch((error: unknown) => {
- if (error instanceof GhostPackagePermissionReviewRequiredError) {
- requireSameMarketOwner(owner);
- return { reviewRequired: error.review };
- }
- throw error;
+ return ghost ? { ghost } : { cancelled: true };
});
}
@@ -683,13 +682,9 @@ export class PluginMarketService {
if (!plugin) {
throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');
}
- // 与服务端详情同理:详情必须沿用列表的 conflict 口径,不能传空重复集合。
- const { duplicates } = await this.crossSourceDuplicateGhostIds(owner);
- requireSameMarketOwner(owner);
return {
...this.customToItem(
{ config: discovered.config, plugin },
- duplicates,
this.localInstallSnapshot(this.ledgerForOwner(owner)),
),
manifest: plugin.manifest,
@@ -697,71 +692,6 @@ export class PluginMarketService {
});
}
- /**
- * 按 snapshot 的同一口径重算跨来源重复 ghostId(服务端目录 + 全部自定义来源)。
- * 详情与安装都用它,保证"列表标成 conflict 并禁用"的判定不会在别处被放宽。
- *
- * 服务端目录可选:未配置或拉取失败时降级为仅自定义来源,并把 `serverKnown`
- * 置为 false 供调用方判断。自定义安装本就不要求服务端可用;未安装的服务端插件
- * 不构成本地运行期抢占,已安装的那种情况由安装侧的 `existing` 检查拦住。
- */
- private async crossSourceDuplicateGhostIds(
- owner: ActiveAppSession,
- knownServerPlugins?: readonly VisiblePluginSummary[],
- ): Promise<{ duplicates: ReadonlySet<string>; serverKnown: boolean; customComplete: boolean }> {
- const { entries: customEntries, complete: customComplete } =
- await this.discoverCustomEntriesSafe(owner);
- let serverPlugins: readonly VisiblePluginSummary[] = knownServerPlugins ?? [];
- let serverKnown = knownServerPlugins !== undefined;
- if (!serverKnown && getClientEndpoint('pluginApiBaseUrl')) {
- try {
- serverPlugins = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);
- serverKnown = true;
- } catch (error) {
- log.warn('market catalog unavailable while recomputing cross-source duplicates', {
- error: error instanceof Error ? error.message : String(error),
- });
- }
- }
- requireSameMarketOwner(owner);
- return {
- duplicates: combinedDuplicateGhostIds(serverPlugins, customEntries),
- serverKnown,
- customComplete,
- };
- }
-
- /**
- * 安装入口重算 ghostId 所有权:列表把跨来源重名标成 `conflict` 并禁用,但那份
- * 判定是快照期算的。安装 IPC 可以被不可信 Renderer 直接调用,也可能在详情打开
- * 后由另一个窗口添加了声明同一 ghostId 的来源 —— 所以真正产生副作用之前必须
- * 用同一口径重新确认。服务端与自定义两条安装路径共用这道闸。
- */
- private async assertSourceOwnsGhostId(input: {
- owner: ActiveAppSession;
- ghostId: string;
- ownsInstall: boolean;
- knownServerPlugins?: readonly VisiblePluginSummary[];
- }): Promise<void> {
- // 已经拥有当前安装记录的来源保留所有权(先装先得,与列表判定一致)。
- if (input.ownsInstall) return;
- const { duplicates, customComplete } = await this.crossSourceDuplicateGhostIds(
- input.owner,
- input.knownServerPlugins,
- );
- // 任一来源暂时不可读时,冲突集合是不完整的——此刻放行安装会在坏来源恢复前
- // 抢占它声明的 ghostId(先装先得被绕过)。fail closed:提示先修复或移除。
- if (!customComplete) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'A marketplace source is unavailable; refresh or remove it before installing',
- );
- }
- if (duplicates.has(input.ghostId)) {
- throwIpcError('ALREADY_EXISTS', 'Another marketplace already provides this Plugin ID');
- }
- }
-
/**
* 自定义市场插件安装/更新。与服务端 installDetail 同一组防线:
* release 一致性(重发现后比对 expectedReleaseId)、冲突先装先得、
@@ -839,7 +769,6 @@ export class PluginMarketService {
if (existing && !ownsInstall && !adoptable) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
- await this.assertSourceOwnsGhostId({ owner, ghostId: plugin.ghostId, ownsInstall });
if (
existing &&
// 与服务端安装同口径:对比已装 manifest 与候选包,只有新增权限才要求
@@ -855,9 +784,6 @@ export class PluginMarketService {
const ghost = await installCustomMarketPlugin({
pluginDir: plugin.dir,
expected: options.expectedManifest,
- // 打包耗时,期间另一窗口可以经独立的 market-sources 互斥键添加声明同一
- // ghostId 的来源(来源变更与插件安装不共享互斥边界)。所以在真正改动
- // Ghost 运行时之前把所有权再算一遍,而不是只依赖打包前那一次。
beforeCommit: async () => {
requireSameMarketOwner(owner);
// 所选来源必须**仍然存在且仍是同一个来源**:移除来源会先拿
@@ -871,8 +797,7 @@ export class PluginMarketService {
'The marketplace source changed during the install',
);
}
- await this.assertSourceOwnsGhostId({ owner, ghostId: plugin.ghostId, ownsInstall });
- // runtime 所有权也要复核,不只来源所有权:打包窗口(秒到分钟级)内,
+ // runtime 所有权也要复核:打包窗口(秒到分钟级)内,
// 本地插件页可以卸载同 id 插件(那条路径不持本服务的互斥锁)——不查
// 会把"更新"降级成"首装+带电启用";反向地,窗口内新装入的同 id
// 本地 .cindy 会被更新分支静默覆盖,还绕过了审阅时跳过的权限 diff。
@@ -953,7 +878,7 @@ export class PluginMarketService {
/** 快照聚合用:发现全部自定义市场条目。任何失败都降级为空,不拖垮快照。 */
private async discoverCustomEntriesSafe(
owner?: ActiveAppSession,
- ): Promise<{ entries: CustomMarketEntry[]; complete: boolean }> {
+ ): Promise<CustomMarketEntry[]> {
try {
const manager = owner
? this.sourceManagerForOwner(owner)
@@ -963,26 +888,15 @@ export class PluginMarketService {
});
const discovered = await manager.discoverAll();
const entries: CustomMarketEntry[] = [];
- // "目录不完整"与"来源确实为空"必须分开:任一来源发现失败时,合并冲突集合
- // 缺了它声明的 ghostId,自动安装/所有权提交会在它暂时不可读的窗口里抢占
- // 先装先得。展示照旧容错(单源失败不拖垮列表),但 complete=false 要让
- // 写路径 fail closed。
- let complete = true;
for (const { config, result } of discovered) {
if (!result.ok) {
- complete = false;
log.warn('custom marketplace discovery failed', {
market: config.name,
code: result.code,
});
continue;
}
- // 粒度到条目的同一口径:某个插件的 ghost.json 暂时读不到(文件锁/网络盘
- // 抖动/权限)时,这个市场声明了哪些 ghostId 就给不出完整答案——展示照旧
- // 容错,但写路径必须 fail closed,否则同 ghostId 的默认安装会在这个窗口
- // 里抢占所有权,恢复后该插件永久 conflict。内容非法(skippedCount)不算。
if (result.marketplace.unreadableCount > 0) {
- complete = false;
log.warn('custom marketplace has unreadable plugin entries', {
market: config.name,
unreadableCount: result.marketplace.unreadableCount,
@@ -992,30 +906,26 @@ export class PluginMarketService {
entries.push({ config, plugin });
}
}
- return { entries, complete };
+ return entries;
} catch (error) {
log.warn('custom marketplace enumeration failed', {
error: error instanceof Error ? error.message : String(error),
});
- return { entries: [], complete: false };
+ return [];
}
}
private projectCustomItems(
entries: readonly CustomMarketEntry[],
- duplicateGhostIds?: ReadonlySet<string>,
local?: LocalInstallSnapshot,
): PluginMarketItem[] {
- const duplicates =
- duplicateGhostIds ?? combinedDuplicateGhostIds([], entries);
const snapshot = local ?? this.localInstallSnapshot();
- return entries.map((entry) => this.customToItem(entry, duplicates, snapshot));
+ return entries.map((entry) => this.customToItem(entry, snapshot));
}
/** 自定义市场项的状态机与服务端 toItem 完全一致(冲突 / 首装 / 更新 / 已装)。 */
private customToItem(
entry: CustomMarketEntry,
- duplicateGhostIds: ReadonlySet<string>,
local: LocalInstallSnapshot,
): PluginMarketItem {
const { config, plugin } = entry;
@@ -1042,12 +952,9 @@ export class PluginMarketService {
!ownsInstall &&
local.rawDigestByGhostId.get(plugin.ghostId) === ghostManifestDigest(plugin.manifest),
);
- // 已拥有当前安装记录的来源保留所有权(installed / update-available);
- // duplicate 只把未拥有安装的竞争来源标为冲突,避免“先装先得”被降格。
- const conflict = Boolean(
- (duplicateGhostIds.has(plugin.ghostId) && !ownsInstall) ||
- (ghost && !ownsInstall && !adoptable),
- );
+ // 市场目录只用于发现,不声明未安装 ghostId 的所有权。只有运行时已经存在
+ // 同 id 且不属于当前来源时才冲突,避免官方或其它市场接管用户已装插件。
+ const conflict = Boolean(ghost && !ownsInstall && !adoptable);
const installState: PluginMarketItem['installState'] = conflict
? 'conflict'
: !ownsInstall
@@ -1119,24 +1026,21 @@ export class PluginMarketService {
}
private async installDetail(
- plugin: VisiblePluginDetail,
+ plugin: VisiblePluginSummary | VisiblePluginDetail,
options: {
+ /** 手动安装时已向用户展示;默认安装时作为自动授权的目录权限上限。 */
+ reviewedManifest?: GhostManifest;
allowPermissionExpansion?: boolean;
- /** 扩权批准所依据的已装权限指纹;安装锁内复核,详见 install() 的说明。 */
+ /** 安装前权限确认所依据的已装权限指纹。 */
reviewedBaseline?: string;
- /** 用户确认过的真实下载包 SHA。 */
- approvedPackageSha256?: string;
+ /** 真实包比展示清单多权限时,在当前安装事务内立即询问发起窗口。 */
+ reviewPackagePermissions?: PackagePermissionReviewer;
/** 确认操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */
expectedInstalled: boolean;
- /**
- * 提交副作用前的所有权复核。下载可能持续数分钟,期间另一窗口可经独立的
- * market-sources 互斥键添加声明同一 ghostId 的来源,入口处那次判定已过期。
- */
- recheckOwnership?: () => Promise<void>;
} = { expectedInstalled: false },
owner = captureMarketOwner(),
ledger = this.ledgerForOwner(owner),
- ): Promise<InstalledGhost> {
+ ): Promise<InstalledGhost | null> {
requireSameMarketOwner(owner);
if (owner.mode === 'local' && plugin.scope !== 'public') {
throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');
@@ -1145,31 +1049,23 @@ export class PluginMarketService {
.list()
.find((ghost) => ghost.manifest.id === plugin.ghostId);
const currentRecord = ledger.installationForGhost(plugin.ghostId);
- if (existing && (!currentRecord?.installed || currentRecord.pluginId !== plugin.id)) {
+ if (existing && !serverMarketOwnsInstalledGhost(plugin.id, existing, currentRecord)) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
- const compatible = validateGhostManifest(plugin.currentRelease.manifest);
- if (!compatible.ok) {
+ const reviewedManifest = options.reviewedManifest
+ ? validateGhostManifest(options.reviewedManifest)
+ : null;
+ if (reviewedManifest && !reviewedManifest.ok) {
throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
}
- /**
- * 扩权闸门:按**传入时刻的**已装 manifest 判定。下面调用两次——
- * 1. 锁外一次:快速失败,不为注定被拒的更新白下载几十 MB;
- * 2. 落位前在 withGhostInstallLock 内再一次(权威):下载可能持续数分钟,
- * 期间本地 `ghosts:update` 能整体替换已装 manifest。只在锁外判定的话,
- * 旧的 reviewedBaseline 会放行相对**新** manifest 多出来的权限——
- * 那些权限用户从没审过。锁内这次才是不可绕过的那道。
- */
- const assertExpansionApproved = (installedNow: GhostManifest | null): void => {
- if (!installedNow) return;
- if (diffGhostPermissionItems(installedNow, compatible.manifest).added.length === 0) return;
- if (options.allowPermissionExpansion !== true) {
- throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');
- }
- assertReviewedBaselineFresh(installedNow, options.reviewedBaseline);
- };
- assertExpansionApproved(existing?.manifest ?? null);
+ this.assertServerPreviewExpansionApproved(
+ existing?.manifest ?? null,
+ reviewedManifest?.manifest,
+ options.allowPermissionExpansion,
+ options.reviewedBaseline,
+ );
+
const download = await this.api.download(plugin.id, plugin.currentRelease.id);
requireSameMarketOwner(owner);
if (
@@ -1190,84 +1086,147 @@ export class PluginMarketService {
try {
await downloadVerifiedPlugin(download.url, download, tempPath);
requireSameMarketOwner(owner);
- if (options.expectedInstalled) {
- const stillInstalled = getGhostManager()
- .list()
- .some((ghost) => ghost.manifest.id === plugin.ghostId);
- if (!stillInstalled) {
- // 用户确认的是更新;下载期间若另一窗口已卸载目标,不能把操作
- // 降级成首装并自动启用。按状态变化拒绝,由 renderer 刷新重试。
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Plugin was uninstalled while the update was downloading',
- );
- }
- }
- // 复核 + 落位 + 溯源写入在同一对锁内完成:
- // - SOURCE_MUTATION_KEY:`installOrUpdateMarketGhostPackage` 会先 await 包
- // 检查才开始改动运行时,复核若在锁外做,结论会在这段等待里过期。
- // - withGhostInstallLock(ghostId):与本地 .cindy 装入/更新/卸载共用同一按 id
- // 互斥。少了它,本地装入能在包检查窗口里落入同 id 的包,随后被本次安装当作
- // 更新目标覆盖,而权限差异确认因审阅时目标不存在而没跑过。账本写入也必须在
- // 锁内:否则本地装入可以插在"落位"与"写溯源"之间,让账本认领一个其实已被
- // 替换掉的包(账本摘要若未对上当前安装内容,投影时不会认领)。
- // 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation,不可反向。
- const ghost = await this.withMutation(SOURCE_MUTATION_KEY, () =>
- withGhostInstallLock(plugin.ghostId, async () => {
- // 改动 Ghost 运行时之前的最后一道:跨来源 ghostId 所有权按当前事实重算。
- await options.recheckOwnership?.();
- requireSameMarketOwner(owner);
- // 权限扩权的**权威**判定点:锁内按当前已装 manifest 重算。锁外那次
- // 只是快速失败;下载窗口期本地装入/更新若换掉了已装包,旧批准在这里
- // 被基线比对拦下,并发替换绕不过去(落位就在下面几行)。
- 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, {
- ghostId: plugin.ghostId,
- version: plugin.currentRelease.version,
- // 确认框渲染的就是这份服务端 manifest;包里若多出权限项,出口处先
- // 暂停落位并返回真实包权限——服务端投影层与客户端清单契约漂移时,
- // 必须让用户按实际要安装的能力面重新确认。
- reviewedManifest: compatible.manifest,
- ...(previouslyInstalledManifest ? { previouslyInstalledManifest } : {}),
- ...(options.approvedPackageSha256 !== undefined
- ? {
- approvedPackageSha256: options.approvedPackageSha256,
- reviewedBaseline: options.reviewedBaseline,
- }
+ try {
+ return await this.commitDownloadedPackage(
+ tempPath,
+ plugin,
+ {
+ expectedInstalled: options.expectedInstalled,
+ ...(reviewedManifest?.ok
+ ? { reviewedManifest: reviewedManifest.manifest }
: {}),
- });
- // Once the package directory is committed, finish provenance against
- // the owner captured at operation start even if the active session
- // changes. The bound ledger prevents this write from leaking into the
- // new owner.
- await this.withCapturedLedgerMutation(ledger, () => {
- ledger.upsertInstallation(recordFrom(plugin, 'market', installed));
- });
- return installed;
- }),
- );
- return ghost;
+ allowPermissionExpansion: options.allowPermissionExpansion,
+ reviewedBaseline: options.reviewedBaseline,
+ },
+ owner,
+ ledger,
+ );
+ } catch (error) {
+ if (!(error instanceof GhostPackagePermissionReviewRequiredError)) throw error;
+ requireSameMarketOwner(owner);
+ const approved = await options.reviewPackagePermissions?.(error.review);
+ requireSameMarketOwner(owner);
+ if (approved !== true) return null;
+ return this.commitDownloadedPackage(
+ tempPath,
+ plugin,
+ {
+ expectedInstalled: options.expectedInstalled,
+ ...(reviewedManifest?.ok
+ ? { reviewedManifest: reviewedManifest.manifest }
+ : {}),
+ allowPermissionExpansion: options.allowPermissionExpansion,
+ reviewedBaseline: options.reviewedBaseline,
+ approvedPackageSha256: error.review.packageSha256,
+ approvedPackageBaseline: error.review.installedBaseline,
+ },
+ owner,
+ ledger,
+ );
+ }
} finally {
await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);
}
}
+ /** 把已验证临时包提交到运行时;确认前后复用同一文件。 */
+ private async commitDownloadedPackage(
+ tempPath: string,
+ plugin: VisiblePluginSummary | VisiblePluginDetail,
+ options: {
+ reviewedManifest?: GhostManifest;
+ allowPermissionExpansion?: boolean;
+ reviewedBaseline?: string;
+ approvedPackageSha256?: string;
+ approvedPackageBaseline?: string | null;
+ expectedInstalled: boolean;
+ },
+ owner: ActiveAppSession,
+ ledger: PluginMarketLedger,
+ ): Promise<InstalledGhost> {
+ return withGhostInstallLock(plugin.ghostId, async () => {
+ const installedNow = getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === plugin.ghostId);
+ const currentRecordNow = ledger.installationForGhost(plugin.ghostId);
+ if (Boolean(installedNow) !== options.expectedInstalled) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ installedNow
+ ? 'A local Plugin appeared with this Plugin ID during the install'
+ : 'Plugin was uninstalled while the update was downloading',
+ );
+ }
+ if (
+ installedNow &&
+ !serverMarketOwnsInstalledGhost(plugin.id, installedNow, currentRecordNow)
+ ) {
+ throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
+ }
+ requireSameMarketOwner(owner);
+ this.assertServerPreviewExpansionApproved(
+ installedNow?.manifest ?? null,
+ options.reviewedManifest,
+ options.allowPermissionExpansion,
+ options.reviewedBaseline,
+ );
+ const installedRawManifest = installedNow
+ ? installedGhostRawManifest(installedNow.dir)
+ : null;
+ const permissionBaselineManifest =
+ installedRawManifest &&
+ currentRecordNow?.installed &&
+ (currentRecordNow.source === 'market' ||
+ currentRecordNow.source === 'legacy-adopted') &&
+ currentRecordNow.manifestDigest === ghostManifestDigest(installedRawManifest)
+ ? installedRawManifest
+ : null;
+ const installed = await installOrUpdateMarketGhostPackage(tempPath, {
+ ghostId: plugin.ghostId,
+ version: plugin.currentRelease.version,
+ ...(options.reviewedManifest
+ ? {
+ reviewedManifest: options.reviewedManifest,
+ ...(permissionBaselineManifest
+ ? { permissionBaselineManifest }
+ : {}),
+ }
+ : {}),
+ ...(options.approvedPackageSha256 !== undefined
+ ? {
+ approvedPackageSha256: options.approvedPackageSha256,
+ ...(options.approvedPackageBaseline !== null
+ ? { reviewedBaseline: options.approvedPackageBaseline }
+ : {}),
+ }
+ : {}),
+ });
+ await this.withCapturedLedgerMutation(ledger, () => {
+ ledger.upsertInstallation(recordFrom(plugin, 'market', installed));
+ });
+ return installed;
+ });
+ }
+
+ private assertServerPreviewExpansionApproved(
+ installed: GhostManifest | null,
+ reviewedManifest: GhostManifest | undefined,
+ allowPermissionExpansion: boolean | undefined,
+ reviewedBaseline: string | undefined,
+ ): void {
+ if (
+ !installed ||
+ !reviewedManifest ||
+ diffGhostPermissionItems(installed, reviewedManifest).added.length === 0
+ ) {
+ return;
+ }
+ if (allowPermissionExpansion !== true) {
+ throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');
+ }
+ assertReviewedBaselineFresh(installed, reviewedBaseline);
+ }
+
private requireConfigured(): void {
if (!getClientEndpoint('pluginApiBaseUrl')) {
throwIpcError('UNSUPPORTED_CAPABILITY', 'Plugin market is not configured');
@@ -1275,22 +1234,16 @@ export class PluginMarketService {
}
private toItem(
- plugin: VisiblePluginSummary | VisiblePluginDetail,
- duplicateGhostIds: ReadonlySet<string> = NO_DUPLICATE_GHOST_IDS,
+ plugin: VisiblePluginSummary,
local = this.localInstallSnapshot(),
): PluginMarketItem {
const ghost = local.ghostsById.get(plugin.ghostId);
const record = local.installations[plugin.ghostId];
const ownsInstall = Boolean(
- ghost && record?.installed && record.pluginId === plugin.id,
- );
- // 与自定义侧 customToItem 对齐:已拥有当前安装记录的来源保留所有权
- // (installed / update-available),duplicate 只标未拥有安装的竞争来源,
- // 避免先安装者被重复 ghostId 降格、失去更新入口。
- const conflict = Boolean(
- (duplicateGhostIds.has(plugin.ghostId) && !ownsInstall) ||
- (ghost && (!record?.installed || record.pluginId !== plugin.id)),
+ ghost && serverMarketOwnsInstalledGhost(plugin.id, ghost, record ?? null),
);
+ // 未安装的其它市场条目不拥有 ghostId;真实已安装插件才建立所有权边界。
+ const conflict = Boolean(ghost && !ownsInstall);
const installState: PluginMarketItem['installState'] = conflict
? 'conflict'
: !ownsInstall
@@ -1348,95 +1301,6 @@ export class PluginMarketService {
}
}
- /**
- * Backfill the digest added by the trusted-install provenance check without
- * trusting a mutable installed manifest on its own. Only an old market
- * record whose exact release is still current can be migrated, and the
- * installed manifest's canonical digest must match the server manifest.
- * Older or replaced packages stay fail-closed until the user installs a
- * current release.
- */
- private async migrateMarketManifestDigests(
- summaries: readonly VisiblePluginSummary[],
- ledger: PluginMarketLedger,
- owner: ActiveAppSession,
- ): Promise<void> {
- const candidates = Object.values(ledger.read().installations).filter(
- (record) =>
- record.source === 'market' &&
- record.installed &&
- record.manifestDigest === undefined,
- );
- for (const record of candidates) {
- const summary = summaries.find(
- (plugin) =>
- plugin.id === record.pluginId &&
- plugin.ghostId === record.ghostId &&
- plugin.currentRelease.id === record.releaseId &&
- plugin.currentRelease.version === record.version &&
- plugin.currentRelease.sha256 === record.sha256,
- );
- if (!summary) continue;
-
- let plugin: VisiblePluginDetail;
- try {
- plugin = await this.api.detail(record.pluginId);
- } catch (error) {
- log.warn('market manifest digest migration detail unavailable', {
- ghostId: record.ghostId,
- pluginId: record.pluginId,
- error: error instanceof Error ? error.message : String(error),
- });
- continue;
- }
- requireSameMarketOwner(owner);
- if (
- plugin.ghostId !== record.ghostId ||
- plugin.currentRelease.id !== record.releaseId ||
- plugin.currentRelease.version !== record.version ||
- plugin.currentRelease.sha256 !== record.sha256 ||
- plugin.scope !== record.scope ||
- plugin.organizationId !== record.organizationId
- ) {
- continue;
- }
- const releaseDigest = ghostManifestDigest(plugin.currentRelease.manifest);
- let migrated = false;
- await withGhostInstallLock(record.ghostId, async () => {
- const installed = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === record.ghostId);
- const installedDigest = installed
- ? installedGhostRawManifestDigest(installed.dir)
- : null;
- if (!installedDigest || installedDigest !== releaseDigest) return;
- await this.withLedgerMutation(owner, () => {
- const current = ledger.installationForGhost(record.ghostId);
- if (
- !current ||
- !current.installed ||
- current.source !== 'market' ||
- current.manifestDigest !== undefined ||
- current.pluginId !== record.pluginId ||
- current.releaseId !== record.releaseId ||
- current.sha256 !== record.sha256
- ) {
- return;
- }
- ledger.upsertInstallation({ ...current, manifestDigest: installedDigest });
- migrated = true;
- });
- });
- if (migrated) {
- log.info('migrated market installation manifest digest', {
- ghostId: record.ghostId,
- pluginId: record.pluginId,
- releaseId: record.releaseId,
- });
- }
- }
- }
-
private async reconcileRemovedInstallations(
ledger: PluginMarketLedger,
owner: ActiveAppSession,
@@ -1564,8 +1428,6 @@ export class PluginMarketService {
plugins: readonly VisiblePluginSummary[],
owner: ActiveAppSession,
ledger: PluginMarketLedger,
- /** 服务端 + 全部自定义来源合并算出的重复 ghostId;命中的默认项一律跳过。 */
- duplicateGhostIds: ReadonlySet<string>,
): Promise<void> {
const installSubject = defaultInstallSubject(owner);
const counts = ghostIdCounts(plugins);
@@ -1578,31 +1440,29 @@ export class PluginMarketService {
const local = this.localInstallSnapshot(ledger, ledgerData.installations);
for (const summary of plugins) {
if (!summary.defaultInstall || !uniqueGhostIds.has(summary.ghostId)) continue;
- // 跨来源重名:自动安装会替用户做出"服务端胜出"的抢占决定,必须交回用户手动
- // 处置(列表把两边都标成 conflict)。
- if (duplicateGhostIds.has(summary.ghostId)) continue;
if (ledgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id)) continue;
if (isBuiltinGhostRemovedByUser(summary.ghostId)) continue;
- const state = this.toItem(summary, duplicateGhostIds, local).installState;
+ const state = this.toItem(summary, local).installState;
if (state !== 'not-installed') continue;
try {
await this.withMutation(summary.id, async () => {
requireSameMarketOwner(owner);
const detail = await this.api.detail(summary.id);
+ requireSameMarketOwner(owner);
+ assertDetailMatchesSummary(summary, detail);
+ const reviewedManifest = validateGhostManifest(detail.currentRelease.manifest);
+ if (!reviewedManifest.ok) {
+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
+ }
// 装完即开语义已收敛进市场安装入口本身,这里无需再显式声明。
await this.installDetail(
detail,
{
expectedInstalled: false,
- // 默认安装同样有下载窗口:提交前按当前事实重算跨来源所有权,
- // 复用已有的服务端目录,不额外打网络请求。
- recheckOwnership: () =>
- this.assertSourceOwnsGhostId({
- owner,
- ghostId: summary.ghostId,
- ownsInstall: false,
- knownServerPlugins: plugins,
- }),
+ // 默认安装没有用户发起窗口:目录 manifest 是自动安装可接受的权限
+ // 上限;真实包若额外扩权,installDetail 会安全取消并等待用户之后
+ // 从详情页手动安装、在原请求窗口完成确认。
+ reviewedManifest: reviewedManifest.manifest,
},
owner,
ledger,
diff --git a/apps/desktop/src/main/plugin-market/sources/discover.ts b/apps/desktop/src/main/plugin-market/sources/discover.ts
index e2c6994caa..20443a4f74 100644
--- a/apps/desktop/src/main/plugin-market/sources/discover.ts
+++ b/apps/desktop/src/main/plugin-market/sources/discover.ts
@@ -123,10 +123,8 @@ export interface DiscoveredMarketplace {
/**
* 因**读取事实不明**未能判定的条目数(文件锁、权限、网络盘抖动、瞬时 I/O)。
*
- * 与 skippedCount 必须分开:>0 表示"这个市场声明了哪些 ghostId"当前给不出完整
- * 答案。展示可以照旧容错,但**新的所有权提交必须 fail closed**——否则同 ghostId
- * 的服务端默认安装/手动安装会在它暂时不可读的窗口里抢占先装先得,恢复后该插件
- * 永久 conflict。与来源级失败(result.ok === false)同一口径,只是粒度到条目。
+ * 与 skippedCount 必须分开:>0 表示部分条目当前读取失败,管理界面应明确提示
+ * 用户刷新或检查来源,但不能因此阻断其它市场的发现和安装。
*/
unreadableCount: number;
}
@@ -499,8 +497,7 @@ export async function discoverMarketplace(marketRoot: string): Promise<DiscoverR
}
const resolved = await resolvePluginDir(marketRoot, relPath);
if (resolved.kind === 'unreadable') {
- // 事实不明:不能与"内容非法"共用静默跳过分支,否则调用方会把目录当完整,
- // 允许同 ghostId 的默认安装/手动安装在这个窗口里抢占所有权。
+ // 事实不明不能与“内容非法”共用计数,否则 UI 无法告诉用户这是可重试问题。
unreadableCount += 1;
noteSkip(index, relPath, resolved);
continue;
diff --git a/apps/desktop/src/main/plugin-market/sources/index.ts b/apps/desktop/src/main/plugin-market/sources/index.ts
index 0b43480878..014d123113 100644
--- a/apps/desktop/src/main/plugin-market/sources/index.ts
+++ b/apps/desktop/src/main/plugin-market/sources/index.ts
@@ -744,6 +744,8 @@ export class MarketSourceManager {
: {
...entry.config,
pluginCount: 0,
+ skippedCount: 0,
+ unreadableCount: 0,
status: 'error' as const,
errorCode: entry.result.code,
},
@@ -799,6 +801,8 @@ export class MarketSourceManager {
return {
...config,
pluginCount: marketplace.plugins.length,
+ skippedCount: marketplace.skippedCount,
+ unreadableCount: marketplace.unreadableCount,
status: 'ok',
errorCode: null,
};
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 1d90a9f27f..1a75ae2eb5 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -376,6 +376,9 @@ const fanOutCorruptionRestored = createIpcFanOut('local-db:corruption-restored')
const fanOutPluginRemovalNoticeAvailable = createIpcFanOut(
'plugin-market:removal-notice-available',
);
+const fanOutPluginMarketPackagePermissionReview = createIpcFanOut(
+ 'plugin-market:package-permission-review',
+);
// #37: release 端检测到 schema drift 时一次性 toast 提示开发者切回 dev 自动修复
const fanOutSchemaDriftWarning = createIpcFanOut('local-db:schema-drift-warning');
const fanOutProjectAliasesChanged = createIpcFanOut('local-db:project-aliases:changed');
@@ -1163,6 +1166,15 @@ contextBridge.exposeInMainWorld('electronAPI', {
options: import('../shared/pluginMarket').PluginMarketInstallOptions,
): Promise<import('../shared/pluginMarket').PluginMarketInstallResult> =>
ipcRenderer.invoke('plugin-market:install', pluginId, options),
+ onPackagePermissionReview: fanOutPluginMarketPackagePermissionReview,
+ resolvePackagePermissionReview: (
+ requestId: string,
+ confirmed: boolean,
+ ): Promise<{ handled: boolean }> =>
+ ipcRenderer.invoke('plugin-market:resolve-package-permission-review', {
+ requestId,
+ confirmed,
+ }),
uninstall: (pluginId: string): Promise<{ ok: true }> =>
ipcRenderer.invoke('plugin-market:uninstall', pluginId),
consumeRemovalNotice: (): Promise<
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index 99bf94ffc6..7403b98cea 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -26,6 +26,7 @@ import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
import { FindInPageBar } from '@/components/find-in-page/FindInPageBar';
import { ProjectAutomationNotifyBridge } from '@/features/scheduler/components/ProjectAutomationNotifyBridge';
import { GhostConfirmDialogHost } from '@/cindy-brain/GhostConfirmDialogHost';
+import { PluginMarketPermissionReviewHost } from '@/features/plugin/PluginMarketPermissionReviewHost';
import { makerChatStore } from '@/lib/makerChatStore';
import { installSystemNetworkErrorToastListener } from '@/lib/systemNetworkErrorToast';
import { installSilentInstallToastListener } from '@/lib/silentInstallToast';
@@ -311,6 +312,7 @@ export function App() {
内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口
都挂、谁收到谁弹,不按窗口类型 gate。 */}
<GhostConfirmDialogHost />
+ <PluginMarketPermissionReviewHost />
<OwnerScopedRouter />
</EnvCheckGuard>
</LoginHandoffHost>
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 62338ca7a7..21a222c207 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -769,56 +769,23 @@ export function GhostPluginPage() {
[t],
);
- /**
- * 市场详情与真实下载包权限不一致时,展示 Main 验证后的真实权限并绑定重试。
- * Renderer 只负责确认;包 SHA 和已装权限基线均由 Main 重新核对。
- */
+ /** 真实包的追加确认由窗口级 Host 在这一次 install IPC 事务内完成。 */
const installReviewedMarketPackage = useCallback(
async (input: {
detail: PluginMarketDetail;
lease: { pluginId: string };
options: PluginMarketInstallOptions;
}): Promise<InstalledGhost | null> => {
- const initial = await window.electronAPI.pluginMarket.install(
+ const result = await window.electronAPI.pluginMarket.install(
input.detail.pluginId,
input.options,
);
- if (initial.ghost !== undefined) return initial.ghost;
- if (!isMarketBusyLeaseActive(input.lease)) return null;
-
- const review = initial.reviewRequired;
- if (!review) return null;
- const approved = await confirm({
- title: t('settings.ghosts.market.installConfirmTitle', {
- name: input.detail.name,
- }),
- description: t('settings.ghosts.market.installConfirmDescription'),
- content: <GhostPermissionList items={ghostPermissionItems(review.manifest)} />,
- maxWidth: 520,
- confirmText: t('settings.ghosts.market.install'),
- cancelText: t('settings.ghosts.installConfirm.cancel'),
- autoFocusConfirm: true,
- });
- if (!approved || !isMarketBusyLeaseActive(input.lease)) return null;
-
- const retried = await window.electronAPI.pluginMarket.install(input.detail.pluginId, {
- ...input.options,
- allowPermissionExpansion: review.installedBaseline !== null,
- reviewedBaseline: review.installedBaseline ?? undefined,
- approvedPackageSha256: review.packageSha256,
- });
- if (retried.ghost !== undefined) return retried.ghost;
-
- // 同一 release 的真实包不应漂移;再次要求复核说明已装基线在往返窗口内变化。
- toast.error(t('settings.ghosts.market.errors.stateChanged'));
- await refreshMarket();
- return null;
+ return result.ghost ?? null;
},
- [confirm, isMarketBusyLeaseActive, refreshMarket, t],
+ [],
);
- // 市场更新流程由列表卡片和详情页共用:先取目标 release 的完整 manifest 做
- // 权限 diff,经用户确认后才安装,不做静默升级。
+ // 所有来源先展示详情清单;官方包下载后仍以真实包清单兜底发现额外权限。
const handleMarketUpdate = useCallback(
async (ghostId: string) => {
const marketItem = marketByGhostId.get(ghostId);
@@ -846,19 +813,18 @@ export function GhostPluginPage() {
cancelText: t('settings.ghosts.updateConfirm.cancel'),
});
if (!approved || !isMarketBusyLeaseActive(marketBusyLease)) return;
+ const options: PluginMarketInstallOptions = {
+ expectedReleaseId: next.releaseId,
+ expectedManifest: next.manifest,
+ allowPermissionExpansion: diff.added.length > 0,
+ ...(installedGhost
+ ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }
+ : {}),
+ };
const ghost = await installReviewedMarketPackage({
detail: next,
lease: marketBusyLease,
- options: {
- expectedReleaseId: next.releaseId,
- ...(next.sourceType !== 'server' ? { expectedManifest: next.manifest } : {}),
- allowPermissionExpansion: diff.added.length > 0,
- // 用户看确认框这段时间里已装 manifest 可能被换掉(如从文件更新);
- // 把审阅基线交给 Main,在安装锁内复核后才放行扩权。
- ...(installedGhost
- ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }
- : {}),
- },
+ options,
});
if (!ghost) return;
if (!isMarketBusyLeaseActive(marketBusyLease)) return;
@@ -1164,40 +1130,23 @@ export function GhostPluginPage() {
// 详情页按钮在 update-available 态复用本入口,后端走原位更新并保留
// 生效状态 —— 文案必须分支,不能对更新路径承诺"装完即开"(review P1)。
const isUpdate = marketDetail.installState === 'update-available';
- // 装完即开意味着"确认安装"就是运行授权,确认框里必须如实展示权限清单
- // (与本地装入确认框同一信息量,review P1):首装展示完整清单,更新展示
- // 与已装版本的权限 diff,并据此决定 allowPermissionExpansion(否则扩权
- // 更新从本入口必被 main 的 PRECONDITION_FAILED 拦下)。更新详情来自 Main
- // 的现查事实,renderer 的 ghosts 推送缓存可能短暂滞后;仅在 update 态且缓存
- // 缺目标时,用既有 listSync 向 Main 现查一次。仍缺失说明状态已经变化,
- // 让后端按原有校验拒绝,绝不能拿新清单和自己做 diff 吞掉新增权限。
- let installedGhost =
- ghosts.find((ghost) => ghost.manifest.id === marketDetail.ghostId) ?? null;
- if (isUpdate && !installedGhost) {
- try {
+ try {
+ let installedGhost =
+ ghosts.find((ghost) => ghost.manifest.id === marketDetail.ghostId) ?? null;
+ if (isUpdate && !installedGhost) {
installedGhost =
window.electronAPI.ghosts
.listSync()
.ghosts.find((ghost) => ghost.manifest.id === marketDetail.ghostId) ?? null;
- } catch {
- // bridge 不可用/状态切换时保持 null;下面不展示伪造的空 diff,
- // 安装调用也不放开 permission expansion,Main 会按真实状态 fail closed。
}
- }
- if (isUpdate && !installedGhost) {
- // detail 仍说可更新、Main 的实时已装清单却没有目标:这是明确的状态
- // 变化,不要展示伪造的空 diff 后让用户确认一次必失败的更新。
- if (isMarketBusyLeaseActive(marketBusyLease)) {
+ if (isUpdate && !installedGhost) {
toast.error(t('settings.ghosts.market.errors.stateChanged'));
+ await refreshMarket();
+ return;
}
- releaseMarketBusy(marketBusyLease);
- await refreshMarket();
- return;
- }
- const diff = isUpdate
- ? diffGhostPermissionItems(installedGhost!.manifest, marketDetail.manifest)
- : null;
- try {
+ const diff = isUpdate
+ ? diffGhostPermissionItems(installedGhost!.manifest, marketDetail.manifest)
+ : null;
const confirmed = await confirm({
title: isUpdate
? t('settings.ghosts.updateConfirm.title', { name: marketDetail.name })
@@ -1206,13 +1155,11 @@ export function GhostPluginPage() {
}),
description: isUpdate
? t('settings.ghosts.market.updateConfirmDescription')
- : // 自定义市场未经服务端完整性校验,确认文案必须如实区分。
- marketDetail.sourceType !== 'server'
- ? t('settings.ghosts.market.customInstallConfirmDescription')
- : t('settings.ghosts.market.installConfirmDescription'),
- // 限高与滚动交给共享 ConfirmDialog(max-h-[85vh] + 内部滚动区 + 打开时
- // 闪一下滚动条),这里不再自套一层 min(56vh,520px) —— 两层限高会让
- // "到底了没有"取决于内外层谁先触底(2026-07-27 收口)。
+ : t(
+ marketDetail.sourceType === 'server'
+ ? 'settings.ghosts.market.installConfirmDescription'
+ : 'settings.ghosts.market.customInstallConfirmDescription',
+ ),
content: isUpdate ? (
<GhostUpdateReview diff={diff!} />
) : (
@@ -1228,25 +1175,22 @@ export function GhostPluginPage() {
autoFocusConfirm: true,
});
if (!confirmed || !isMarketBusyLeaseActive(marketBusyLease)) return;
+ const options: PluginMarketInstallOptions = {
+ expectedReleaseId: marketDetail.releaseId,
+ expectedManifest: marketDetail.manifest,
+ ...(isUpdate && diff!.added.length > 0
+ ? {
+ allowPermissionExpansion: true,
+ ...(installedGhost
+ ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }
+ : {}),
+ }
+ : {}),
+ };
const ghost = await installReviewedMarketPackage({
detail: marketDetail,
lease: marketBusyLease,
- options: {
- expectedReleaseId: marketDetail.releaseId,
- ...(marketDetail.sourceType !== 'server'
- ? { expectedManifest: marketDetail.manifest }
- : {}),
- ...(isUpdate && diff!.added.length > 0
- ? {
- allowPermissionExpansion: true,
- // 确认框展示期间已装 manifest 可能被换掉;基线交由 Main 在
- // 安装锁内复核,不一致就拒绝这次批准而不是沿用旧同意。
- ...(installedGhost
- ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }
- : {}),
- }
- : {}),
- },
+ options,
});
if (!ghost) return;
if (!isMarketBusyLeaseActive(marketBusyLease)) return;
diff --git a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx
index 2f4c2b0923..22d5c51e7a 100644
--- a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx
@@ -26,10 +26,10 @@ export function MarketPluginDetailView({
}: MarketPluginDetailViewProps) {
const { t } = useTranslation();
const { scrolled, onScroll } = usePluginDetailScrolled();
- const permissions = ghostPermissionItems(detail.manifest);
const presentationOrigin = pluginPresentationOrigin(detail);
// 自定义市场(Git/本地源)的包字节未经服务端校验,安全说明必须如实区分。
const isCustomSource = detail.sourceType !== 'server';
+ const permissions = ghostPermissionItems(detail.manifest);
const actionKey =
detail.installState === 'update-available'
? 'settings.ghosts.market.update'
@@ -133,33 +133,33 @@ export function MarketPluginDetailView({
</section>
<section className="mt-10" aria-labelledby="market-permissions-title">
- <div className="flex items-baseline gap-2">
- <h2
- id="market-permissions-title"
- className="text-18 font-medium leading-[26px] text-[var(--text-primary)]"
- >
- {t('settings.ghosts.perm.grantsTitle')}
- </h2>
- <span className="text-12 text-[var(--text-tertiary)]">
- {t('settings.ghosts.perm.itemCount', { count: permissions.length })}
- </span>
- </div>
- <div className="mt-5 max-w-[760px] divide-y divide-[var(--border-default)] rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-5">
- {permissions.length > 0 ? (
- permissions.map((permission, index) => (
- <div
- key={`${permission.kind}-${permission.labelKey}-${index}`}
- className="py-3.5 text-13 leading-5 text-[var(--text-secondary)]"
- >
- {t(`settings.ghosts.perm.${permission.labelKey}`, permission.labelArgs)}
+ <div className="flex items-baseline gap-2">
+ <h2
+ id="market-permissions-title"
+ className="text-18 font-medium leading-[26px] text-[var(--text-primary)]"
+ >
+ {t('settings.ghosts.perm.grantsTitle')}
+ </h2>
+ <span className="text-12 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.perm.itemCount', { count: permissions.length })}
+ </span>
+ </div>
+ <div className="mt-5 max-w-[760px] divide-y divide-[var(--border-default)] rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-5">
+ {permissions.length > 0 ? (
+ permissions.map((permission, index) => (
+ <div
+ key={`${permission.kind}-${permission.labelKey}-${index}`}
+ className="py-3.5 text-13 leading-5 text-[var(--text-secondary)]"
+ >
+ {t(`settings.ghosts.perm.${permission.labelKey}`, permission.labelArgs)}
+ </div>
+ ))
+ ) : (
+ <div className="py-4 text-13 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.market.noPermissions')}
</div>
- ))
- ) : (
- <div className="py-4 text-13 text-[var(--text-tertiary)]">
- {t('settings.ghosts.market.noPermissions')}
- </div>
- )}
- </div>
+ )}
+ </div>
</section>
</article>
</main>
diff --git a/apps/desktop/src/renderer/features/plugin/MarketplaceSourcesDialog.tsx b/apps/desktop/src/renderer/features/plugin/MarketplaceSourcesDialog.tsx
index a41011af81..0c093cf252 100644
--- a/apps/desktop/src/renderer/features/plugin/MarketplaceSourcesDialog.tsx
+++ b/apps/desktop/src/renderer/features/plugin/MarketplaceSourcesDialog.tsx
@@ -206,6 +206,29 @@ export function MarketplaceSourcesDialog({
<span aria-hidden="true">·</span>
<span className="shrink-0">{formatSyncedAt(source.lastSyncedAt)}</span>
</div>
+ {source.status === 'ok' ? (
+ <div className="mt-1.5 text-11 leading-4 text-[var(--text-tertiary)]">
+ {source.pluginCount === 0 &&
+ source.skippedCount === 0 &&
+ source.unreadableCount === 0 ? (
+ <p>{t('settings.ghosts.market.sources.empty')}</p>
+ ) : null}
+ {source.skippedCount > 0 ? (
+ <p>
+ {t('settings.ghosts.market.sources.skippedEntries', {
+ count: source.skippedCount,
+ })}
+ </p>
+ ) : null}
+ {source.unreadableCount > 0 ? (
+ <p className="text-[var(--warning-fg)]">
+ {t('settings.ghosts.market.sources.unreadableEntries', {
+ count: source.unreadableCount,
+ })}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
<div className="mt-2.5 flex items-center justify-end gap-2">
<button
type="button"
diff --git a/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsx b/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsx
new file mode 100644
index 0000000000..ff95a900e9
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsx
@@ -0,0 +1,64 @@
+import { useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { GhostPermissionList, GhostUpdateReview } from '@/cindy-brain/GhostPermissionList';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { ghostPermissionItems } from '../../../shared/ghost';
+
+/**
+ * 官方市场安装事务的真实包权限确认入口。
+ *
+ * Main 下载并检查真实包后把事务暂停在调用栈内,只向发起窗口投递这一张确认卡。
+ * 无论确认、取消、Esc、遮罩关闭还是渲染异常,finally 都会把答案回给 Main;
+ * Main 随后继续安装或取消事务,并在自己的 finally 中删除临时包。
+ */
+export function PluginMarketPermissionReviewHost() {
+ const { t } = useTranslation();
+ const { confirm } = useConfirmDialog();
+
+ useEffect(() => {
+ return window.electronAPI.pluginMarket.onPackagePermissionReview((review) => {
+ if (!review || typeof review.requestId !== 'string') return;
+ void (async () => {
+ let confirmed = false;
+ try {
+ const isUpdate = review.permissionDiff !== null;
+ confirmed = await confirm({
+ title: isUpdate
+ ? t('settings.ghosts.updateConfirm.title', { name: review.manifest.name })
+ : t('settings.ghosts.market.installConfirmTitle', {
+ name: review.manifest.name,
+ }),
+ description: isUpdate
+ ? t('settings.ghosts.market.updateConfirmDescription')
+ : t('settings.ghosts.market.installConfirmDescription'),
+ content: isUpdate ? (
+ <GhostUpdateReview diff={review.permissionDiff!} />
+ ) : (
+ <GhostPermissionList items={ghostPermissionItems(review.manifest)} />
+ ),
+ maxWidth: 520,
+ confirmText: isUpdate
+ ? t('settings.ghosts.updateConfirm.confirm')
+ : t('settings.ghosts.market.install'),
+ cancelText: isUpdate
+ ? t('settings.ghosts.updateConfirm.cancel')
+ : t('settings.ghosts.installConfirm.cancel'),
+ autoFocusConfirm: true,
+ });
+ } finally {
+ try {
+ await window.electronAPI.pluginMarket.resolvePackagePermissionReview(
+ review.requestId,
+ confirmed,
+ );
+ } catch {
+ // 窗口销毁时 Main 会把等待中的事务按取消结算。
+ }
+ }
+ })();
+ });
+ }, [confirm, t]);
+
+ return null;
+}
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/AddMarketplaceDialog.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/AddMarketplaceDialog.test.tsx
index be8432f672..64f02f465e 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/AddMarketplaceDialog.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/AddMarketplaceDialog.test.tsx
@@ -86,6 +86,8 @@ describe('AddMarketplaceDialog', () => {
lastRevision: null,
source: { type: 'git' as const, url: 'https://git.acme.test/private/repo.git', sparsePaths: [] },
pluginCount: 1,
+ skippedCount: 0,
+ unreadableCount: 0,
status: 'ok' as const,
errorCode: null,
},
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx
index 4f8abeb8da..8445a26c15 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx
@@ -14,8 +14,19 @@ vi.mock('react-i18next', () => ({
}));
import { MarketPluginDetailView } from '../MarketPluginDetailView';
+import type { GhostManifest } from '../../../../shared/ghost';
import type { PluginMarketDetail } from '../../../../shared/pluginMarket';
+const manifest: GhostManifest = {
+ schemaVersion: 2,
+ id: 'google-calendar',
+ name: 'Google Calendar',
+ version: '1.3.11',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['notify'],
+};
+
const detail: PluginMarketDetail = {
pluginId: 'release-google-calendar',
ghostId: 'google-calendar',
@@ -33,15 +44,7 @@ const detail: PluginMarketDetail = {
enabled: null,
sourceType: 'server',
sourceMarketName: null,
- manifest: {
- schemaVersion: 2,
- id: 'google-calendar',
- name: 'Google Calendar',
- version: '1.3.11',
- kind: 'chip',
- entry: 'index.html',
- slots: [],
- },
+ manifest,
};
const renderDetail = (overrides: Partial<PluginMarketDetail> = {}) =>
@@ -67,6 +70,11 @@ describe('MarketPluginDetailView', () => {
).toBeNull();
});
+ it('presents server catalog permissions before the package is downloaded', () => {
+ renderDetail();
+ expect(screen.getByText('settings.ghosts.perm.grantsTitle')).toBeTruthy();
+ });
+
it('explains why a conflicting plugin is unavailable and binds it to the action', () => {
renderDetail({ installState: 'conflict' });
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
index f3bf806e55..733aa6a40e 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
@@ -1,7 +1,7 @@
/**
* Regression coverage for the module-level update-all batch controller:
- * uninstall guards, reviewed-manifest passthrough, package-review baseline
- * drift recovery, and batch state surviving page unmount (review 定稿 2026-08-04).
+ * uninstall guards, reviewed-manifest passthrough, cancellation handling,
+ * baseline drift recovery, and batch state surviving page unmount.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
* @vitest-environment jsdom
*/
@@ -21,7 +21,7 @@ import {
setDataOwnerGeneration,
} from '@/contexts/dataOwnerGeneration';
import { toast } from '@/lib/toast';
-import { ghostPermissionBaselineKey, type GhostManifest } from '../../../../shared/ghost';
+import type { GhostManifest } from '../../../../shared/ghost';
import type { PluginMarketDetail, PluginMarketItem } from '../../../../shared/pluginMarket';
import {
__resetUpdateAllBatchForTest,
@@ -114,60 +114,33 @@ describe('updateAllController', () => {
expect(installMock).not.toHaveBeenCalled();
});
- it('holds actual package permissions for approval', async () => {
- stubDetail({ manifest: manifest({}), sourceType: 'server' });
- const review = {
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- packageSha256: 'a'.repeat(64),
- installedBaseline: ghostPermissionBaselineKey(installedGhosts[0].manifest),
- };
- installMock.mockResolvedValueOnce({ reviewRequired: review } as never);
+ it('holds server preview permission expansion for approval', async () => {
+ const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });
+ stubDetail({ manifest: targetManifest, sourceType: 'server' });
startUpdateAllBatch([marketItem({})]);
await waitForSettledBatch();
expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
status: 'needs-confirm',
releaseId: 'release-2',
- packageReview: review,
+ expectedManifest: targetManifest,
});
await approveUpdateExpansion('plugin-a');
expect(installMock).toHaveBeenLastCalledWith(
'plugin-a',
- expect.objectContaining({
- approvedPackageSha256: review.packageSha256,
- }),
+ expect.objectContaining({ expectedManifest: targetManifest }),
);
});
- it('keeps package review recoverable when the installed baseline drifts in flight', async () => {
+ it('marks a transaction cancelled in Main as skipped', async () => {
stubDetail({ manifest: manifest({}), sourceType: 'server' });
- const review = {
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- packageSha256: 'a'.repeat(64),
- installedBaseline: ghostPermissionBaselineKey(installedGhosts[0].manifest),
- };
- installMock.mockImplementationOnce(async () => {
- installedGhosts = [{ manifest: manifest({ version: '1.0.5', slots: ['fs'] }) }];
- return { reviewRequired: review } as never;
- });
+ installMock.mockResolvedValueOnce({ cancelled: true } as never);
startUpdateAllBatch([marketItem({})]);
await waitForSettledBatch();
- expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
- status: 'needs-confirm',
- staleReview: true,
- releaseId: 'release-2',
- fromVersion: '1.0.5',
- toVersion: '1.1.0',
- });
-
- await approveUpdateExpansion('plugin-a');
- expect(installMock).toHaveBeenLastCalledWith('plugin-a', {
- expectedReleaseId: 'release-2',
- });
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');
});
it('passes the reviewed manifest back when approving a non-server expansion', async () => {
@@ -191,7 +164,7 @@ describe('updateAllController', () => {
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
});
- it('omits expectedManifest when approving a server-source expansion', async () => {
+ it('passes expectedManifest when approving a server-source expansion', async () => {
stubDetail({
manifest: manifest({ network: { hosts: ['api.example.com'] } }),
sourceType: 'server',
@@ -201,11 +174,14 @@ describe('updateAllController', () => {
await waitForSettledBatch();
await approveUpdateExpansion('plugin-a');
- expect(installMock).toHaveBeenCalledWith('plugin-a', {
- expectedReleaseId: 'release-2',
- allowPermissionExpansion: true,
- reviewedBaseline: expect.any(String),
- });
+ expect(installMock).toHaveBeenLastCalledWith(
+ 'plugin-a',
+ expect.objectContaining({
+ expectedReleaseId: 'release-2',
+ expectedManifest: expect.any(Object),
+ reviewedBaseline: expect.any(String),
+ }),
+ );
});
it('turns approval into a skip when the plugin was uninstalled while waiting', async () => {
@@ -245,7 +221,10 @@ describe('updateAllController', () => {
await approveUpdateExpansion('plugin-a');
// 相对当前已装 manifest 已无扩权 → 按普通更新安装,不带 allowPermissionExpansion。
- expect(installMock).toHaveBeenCalledWith('plugin-a', { expectedReleaseId: 'release-2' });
+ expect(installMock).toHaveBeenCalledWith('plugin-a', {
+ expectedReleaseId: 'release-2',
+ expectedManifest: expect.any(Object),
+ });
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
});
@@ -266,7 +245,7 @@ describe('updateAllController', () => {
const row = getUpdateAllBatchState().rows?.[0];
expect(row).toMatchObject({ status: 'needs-confirm', staleReview: false, fromVersion: '1.0.5' });
expect(row?.permissionDiff?.added.length).toBeGreaterThan(0);
- // 重算后仍是扩权:必须回到用户逐项审阅,绝不静默放行。
+ // 重算后仍是扩权:停在当前批次等待用户重新确认,不提前调用安装。
expect(installMock).not.toHaveBeenCalled();
});
@@ -285,7 +264,10 @@ describe('updateAllController', () => {
];
await approveUpdateExpansion('plugin-a');
- expect(installMock).toHaveBeenCalledWith('plugin-a', { expectedReleaseId: 'release-2' });
+ expect(installMock).toHaveBeenCalledWith('plugin-a', {
+ expectedReleaseId: 'release-2',
+ expectedManifest: expect.any(Object),
+ });
});
it('invalidates the review when a same-version manifest swap widened permissions', async () => {
@@ -306,7 +288,7 @@ describe('updateAllController', () => {
expect(held?.permissionDiff).toBeUndefined();
await approveUpdateExpansion('plugin-a');
- // 相对新基线重算后仍是扩权 → 回到逐项审阅,绝不带 allowPermissionExpansion 放行。
+ // 相对新基线仍是扩权 → 回到预览权限确认,绝不沿用旧批准或提前安装。
expect(installMock).not.toHaveBeenCalled();
expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
status: 'needs-confirm',
@@ -331,11 +313,13 @@ describe('updateAllController', () => {
expect(kept?.permissionDiff?.added.length).toBeGreaterThan(0);
await approveUpdateExpansion('plugin-a');
- expect(installMock).toHaveBeenCalledWith('plugin-a', {
- expectedReleaseId: 'release-2',
- allowPermissionExpansion: true,
- reviewedBaseline: expect.any(String),
- });
+ expect(installMock).toHaveBeenLastCalledWith(
+ 'plugin-a',
+ expect.objectContaining({
+ expectedReleaseId: 'release-2',
+ reviewedBaseline: expect.any(String),
+ }),
+ );
});
it('voids the batch when the data owner changes during the detail round-trip', async () => {
@@ -402,11 +386,13 @@ describe('updateAllController', () => {
await approveUpdateExpansion('plugin-a');
// 目标 release 仍未落账 → 必须真正安装,不得凭版本号收成完成。
- expect(installMock).toHaveBeenCalledWith('plugin-a', {
- expectedReleaseId: 'release-2',
- allowPermissionExpansion: true,
- reviewedBaseline: expect.any(String),
- });
+ expect(installMock).toHaveBeenLastCalledWith(
+ 'plugin-a',
+ expect.objectContaining({
+ expectedReleaseId: 'release-2',
+ reviewedBaseline: expect.any(String),
+ }),
+ );
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
});
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
index ca60567571..7cceab1454 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
@@ -27,10 +27,7 @@ import {
ghostPermissionBaselineKey,
type GhostManifest,
} from '../../../../shared/ghost';
-import type {
- PluginMarketItem,
- PluginMarketPackageReview,
-} from '../../../../shared/pluginMarket';
+import type { PluginMarketItem } from '../../../../shared/pluginMarket';
import { pluginMarketErrorKey } from './pluginMarketErrorKey';
import {
batchSummary,
@@ -156,7 +153,6 @@ function holdRowForReReview(
status: 'needs-confirm',
staleReview: true,
permissionDiff: undefined,
- packageReview: undefined,
...patch,
releaseId,
});
@@ -195,43 +191,6 @@ function installedManifestOf(ghostId: string): GhostManifest | null {
);
}
-function holdPackageReview(
- generation: number,
- row: Pick<UpdateAllRow, 'pluginId' | 'ghostId'> & {
- releaseId: string;
- toVersion: string;
- expectedManifest?: GhostManifest;
- },
- review: PluginMarketPackageReview,
-): void {
- const installed = installedManifestOf(row.ghostId);
- if (!installed) {
- patchRow(generation, row.pluginId, { status: 'skipped' });
- return;
- }
- const reviewedBaseline = ghostPermissionBaselineKey(installed);
- if (reviewedBaseline !== review.installedBaseline) {
- holdRowForReReview(generation, row.pluginId, {
- releaseId: row.releaseId,
- fromVersion: installed.version,
- toVersion: row.toVersion,
- expectedManifest: undefined,
- });
- return;
- }
- patchRow(generation, row.pluginId, {
- status: 'needs-confirm',
- fromVersion: installed.version,
- toVersion: row.toVersion,
- releaseId: row.releaseId,
- permissionDiff: diffGhostPermissionItems(installed, review.manifest),
- staleReview: false,
- reviewedBaseline,
- packageReview: review,
- expectedManifest: row.expectedManifest,
- });
-}
-
async function refreshMarketIfMounted(): Promise<void> {
try {
await hooks.refreshMarket?.();
@@ -323,26 +282,16 @@ async function runQueue(generation: number): Promise<void> {
permissionDiff: diff,
// 审阅基线绑定权限指纹而非版本号:同版本换 manifest 也能识别。
reviewedBaseline: ghostPermissionBaselineKey(installedManifest),
- ...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),
+ expectedManifest: detail.manifest,
});
continue;
}
const result = await window.electronAPI.pluginMarket.install(next.pluginId, {
expectedReleaseId: detail.releaseId,
- ...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),
+ expectedManifest: detail.manifest,
});
- if (result.reviewRequired) {
- holdPackageReview(
- generation,
- {
- pluginId: next.pluginId,
- ghostId: next.ghostId,
- releaseId: detail.releaseId,
- toVersion: detail.version,
- ...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),
- },
- result.reviewRequired,
- );
+ if (result.cancelled) {
+ patchRow(generation, next.pluginId, { status: 'skipped' });
continue;
}
patchRow(generation, next.pluginId, { status: 'done' });
@@ -496,8 +445,7 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo
permissionDiff: diffGhostPermissionItems(installed, detail.manifest),
staleReview: false,
reviewedBaseline: ghostPermissionBaselineKey(installed),
- packageReview: undefined,
- expectedManifest: detail.sourceType !== 'server' ? detail.manifest : undefined,
+ expectedManifest: detail.manifest,
});
};
// 用户审阅的是「审阅当时的已装权限面 → 那一刻的目标 release」。三个前提
@@ -508,16 +456,13 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo
// - 目标 release 变化:市场在等待期间发了新版,审的不是这一版。
// - 目标 manifest 变化:自定义市场源可以在**同一 releaseId 下**改 manifest,
// 只比 releaseId 看不出来。
- // 非 server 源**必须**留有 expectedManifest 且与当前详情逐份一致才算有效:
+ // 所有来源都必须留有 expectedManifest 且与当前详情逐份一致才算有效:
// 缺失不能短路成「有效」——那样下一次批准会不带 expectedManifest 去装,
// 主进程对这类来源直接 INVALID_PARAMS,行落成 failed(前一轮把被拒的行
- // 清成 expectedManifest: undefined,正好会踩中)。server 源无此字段,
- // 由 releaseId 兜住。
+ // 清成 expectedManifest: undefined,正好会踩中)。
const manifestStillMatches =
- detail.sourceType === 'server'
- ? true
- : row.expectedManifest !== undefined &&
- JSON.stringify(row.expectedManifest) === JSON.stringify(detail.manifest);
+ row.expectedManifest !== undefined &&
+ JSON.stringify(row.expectedManifest) === JSON.stringify(detail.manifest);
const reviewStillValid =
row.staleReview !== true &&
ghostPermissionBaselineKey(installed) === row.reviewedBaseline &&
@@ -536,18 +481,8 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo
): Promise<boolean> => {
try {
const result = await window.electronAPI.pluginMarket.install(pluginId, options);
- if (result.reviewRequired) {
- holdPackageReview(
- generation,
- {
- pluginId,
- ghostId: row.ghostId,
- releaseId: detail.releaseId,
- toVersion: detail.version,
- ...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),
- },
- result.reviewRequired,
- );
+ if (result.cancelled) {
+ patchRow(generation, pluginId, { status: 'skipped' });
return false;
}
return true;
@@ -570,19 +505,16 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo
throw error;
}
};
- if (reviewStillValid) {
+ if (reviewStillValid && row.expectedManifest !== undefined) {
const didInstall = await installOrHoldForReReview({
expectedReleaseId: row.releaseId,
- ...(row.expectedManifest ? { expectedManifest: row.expectedManifest } : {}),
+ expectedManifest: row.expectedManifest,
allowPermissionExpansion: true,
// 审阅基线随批准回传:Main 在安装锁内用当时的已装 manifest 复核,
// renderer 这边的检查挡不住 IPC 往返窗口内的替换。
...(row.reviewedBaseline !== undefined
? { reviewedBaseline: row.reviewedBaseline }
: {}),
- ...(row.packageReview
- ? { approvedPackageSha256: row.packageReview.packageSha256 }
- : {}),
});
if (!didInstall) return;
patchRow(generation, pluginId, { status: 'done' });
@@ -596,7 +528,7 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo
// 不匹配拒绝,不能把它落成终态失败。
const ok = await installOrHoldForReReview({
expectedReleaseId: detail.releaseId,
- ...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),
+ expectedManifest: detail.manifest,
});
if (!ok) return;
patchRow(generation, pluginId, { status: 'done', fromVersion: installed.version });
@@ -660,7 +592,6 @@ export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[]
fromVersion: installed.version,
permissionDiff: undefined,
staleReview: true,
- packageReview: undefined,
});
changed = true;
} else if (installed.version !== row.fromVersion) {
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
index 02b137c640..b3223e4737 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
@@ -8,10 +8,7 @@
*/
import type { GhostManifest, GhostPermissionDiff } from '../../../../shared/ghost';
-import type {
- PluginMarketItem,
- PluginMarketPackageReview,
-} from '../../../../shared/pluginMarket';
+import type { PluginMarketItem } from '../../../../shared/pluginMarket';
/**
* 批量更新策略(设计定稿):权限无变化的自动串行完成;权限有扩张的
@@ -44,18 +41,14 @@ export interface UpdateAllRow {
/**
* 审阅所依据的**已装 manifest 权限指纹**(不是版本号)。
* `ghosts.update()` 允许同版本整体替换 manifest,所以版本号不是可靠的
- * 审阅基线——同版本换入不同权限声明时,旧 diff 与它换来的
- * allowPermissionExpansion 会把未审阅的新权限一并放行。批准前必须拿
- * 当前已装 manifest 重算指纹比对,不一致即作废重审。
+ * 审阅基线。Renderer 先检查、Main 在安装锁内复核。
*/
reviewedBaseline?: string;
/**
- * 非 server 源在审阅时取得的 manifest:主进程对这类来源强制要求安装时
- * 传回同一份 reviewed manifest,approve 必须原样带上,否则 INVALID_PARAMS。
+ * 审阅时取得的 manifest:主进程强制要求安装时传回同一份清单,
+ * approve 必须原样带上,否则 INVALID_PARAMS。
*/
expectedManifest?: GhostManifest;
- /** 实际下载包等待用户确认的权限事实。 */
- packageReview?: PluginMarketPackageReview;
/** status 为 failed 时的用户可读错误(已经过 i18n 映射)。 */
errorText?: string;
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 016c7c4d37..5428131b48 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3274,6 +3274,9 @@
"listTitle": "Added Marketplaces",
"pluginCount": "{{count}} plugins",
"sourceError": "Unavailable",
+ "empty": "No plugin entries in this marketplace",
+ "skippedEntries": "Skipped {{count}} invalid plugin entries",
+ "unreadableEntries": "{{count}} plugin entries are temporarily unreadable; refresh to retry",
"localBadge": "Local",
"defaultRef": "Default branch",
"neverSynced": "Never synced",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index bc985008c6..d8fa6da7f9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3273,6 +3273,9 @@
"listTitle": "追加済みのマーケット",
"pluginCount": "{{count}} 個のプラグイン",
"sourceError": "読み込み失敗",
+ "empty": "このマーケットにはプラグイン項目がありません",
+ "skippedEntries": "無効なプラグイン項目 {{count}} 件をスキップしました",
+ "unreadableEntries": "プラグイン項目 {{count}} 件を一時的に読み込めません。更新して再試行してください",
"localBadge": "ローカル",
"defaultRef": "デフォルトブランチ",
"neverSynced": "未同期",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 594a59b126..c5ebf2554a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3273,6 +3273,9 @@
"listTitle": "추가된 마켓",
"pluginCount": "플러그인 {{count}}개",
"sourceError": "읽기 실패",
+ "empty": "이 마켓에는 플러그인 항목이 없습니다",
+ "skippedEntries": "잘못된 플러그인 항목 {{count}}개를 건너뛰었습니다",
+ "unreadableEntries": "플러그인 항목 {{count}}개를 일시적으로 읽을 수 없습니다. 새로고침하여 다시 시도하세요",
"localBadge": "로컬",
"defaultRef": "기본 브랜치",
"neverSynced": "동기화되지 않음",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index e107bb45a3..8825309653 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3273,6 +3273,9 @@
"listTitle": "已添加的市场",
"pluginCount": "{{count}} 个插件",
"sourceError": "读取失败",
+ "empty": "市场清单中没有插件条目",
+ "skippedEntries": "已跳过 {{count}} 个无效插件条目",
+ "unreadableEntries": "{{count}} 个插件条目暂时无法读取,请刷新重试",
"localBadge": "本地",
"defaultRef": "默认分支",
"neverSynced": "尚未同步",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 7ba079dbd4..7b82ce8655 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1473,6 +1473,15 @@ interface ElectronAPI {
pluginId: string,
options: import('../shared/pluginMarket').PluginMarketInstallOptions,
) => Promise<import('../shared/pluginMarket').PluginMarketInstallResult>;
+ onPackagePermissionReview: (
+ callback: (
+ request: import('../shared/pluginMarket').PluginMarketPackageReviewRequest,
+ ) => void,
+ ) => () => void;
+ resolvePackagePermissionReview: (
+ requestId: string,
+ confirmed: boolean,
+ ) => Promise<{ handled: boolean }>;
uninstall: (pluginId: string) => Promise<{ ok: true }>;
consumeRemovalNotice: () => Promise<
import('../shared/pluginMarket').PluginRemovalUserNotice | null
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index b17bb53c9d..2340ecf496 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -17,7 +17,6 @@ import {
parseGhostNodeChildToHostMessage,
ghostPartition,
ghostPermissionItems,
- unreviewedGhostPermissionItems,
ghostWebviewEntryPaths,
isGhostCallToolName,
isValidGhostId,
@@ -124,38 +123,6 @@ 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 721c0918c5..aa0360dd90 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -2003,12 +2003,7 @@ export function diffGhostPermissionItems(
return { added, removed, unchanged };
}
-/**
- * 返回未被发布清单或已批准旧版本覆盖的包权限。
- *
- * 第二个来源用于兼容旧市场元数据:旧详情投影可能漏掉已存在的权限,
- * 但这些权限此前已经被用户批准,更新时应继续保留。
- */
+/** 返回真实包中既未在安装前展示、也未被当前已装版本覆盖的权限。 */
export function unreviewedGhostPermissionItems(
reviewed: GhostManifest,
previouslyInstalled: GhostManifest | undefined,
diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.ts
index 44f44e480f..34bfafd8fe 100644
--- a/apps/desktop/src/shared/pluginMarket.ts
+++ b/apps/desktop/src/shared/pluginMarket.ts
@@ -1,4 +1,4 @@
-import type { GhostManifest, InstalledGhost } from './ghost';
+import type { GhostManifest, GhostPermissionDiff, InstalledGhost } from './ghost';
import type { PluginIconMetadata } from '@cindy/plugin-protocol';
export type PluginMarketScope = 'public' | 'organization' | 'personal';
@@ -47,36 +47,44 @@ export interface PluginRemovalUserNotice {
name: string | null;
}
-/** 详情额外携带经 Desktop 当前 runtime validator 验证过的完整清单。 */
+/** 详情携带安装前展示给用户的 manifest;官方来自 release,自定义来自本地发现。 */
export interface PluginMarketDetail extends PluginMarketItem {
manifest: GhostManifest;
}
-/** Main 验证真实下载包后,交给 Renderer 展示的权限复核事实。 */
-export interface PluginMarketPackageReview {
+/** Main 从已验证真实包中提取的权限复核事实。 */
+export interface PluginMarketPackageReviewFacts {
/** 已按当前界面语言本地化,仅用于展示;安全指纹由 Main 基于原始清单计算。 */
manifest: GhostManifest;
+ /** Main 基于当前已装原始清单与真实包原始清单算出的权限差异;首装为 null。 */
+ permissionDiff: GhostPermissionDiff | null;
packageSha256: string;
/** 产生复核结果时的已装权限基线;null 表示当时尚未安装。 */
installedBaseline: string | null;
}
+/** Main 在安装事务内请求当前窗口立即确认真实包权限;不暴露内部批准绑定。 */
+export interface PluginMarketPackageReviewRequest {
+ requestId: string;
+ manifest: GhostManifest;
+ permissionDiff: GhostPermissionDiff | null;
+}
+
export interface PluginMarketInstallOptions {
/** 用户审阅时看到的目标 release;Main 会在下载前重新核对。 */
expectedReleaseId: string;
- /** 自定义市场审阅过的完整清单;服务端市场由 Main 读取 release 清单。 */
- expectedManifest?: GhostManifest;
+ /** 安装前展示给用户的完整清单;Main 会与当前来源事实重新核对。 */
+ expectedManifest: GhostManifest;
+ /** 仅用于自定义市场确认其本地真实 manifest 的扩权。 */
allowPermissionExpansion?: boolean;
- /** 用户审阅扩权时的已装权限基线。 */
+ /** 用户审阅目标权限时的已装权限基线。 */
reviewedBaseline?: string;
- /** 用户确认过的真实下载包;Main 会重新下载并核对 SHA。 */
- approvedPackageSha256?: string;
}
-/** 安装成功,或真实包权限与市场展示不一致而需要用户复核。 */
+/** 安装成功,或用户在事务内取消真实包权限确认。 */
export type PluginMarketInstallResult =
- | { ghost: InstalledGhost; reviewRequired?: never }
- | { ghost?: never; reviewRequired: PluginMarketPackageReview };
+ | { ghost: InstalledGhost; cancelled?: never }
+ | { ghost?: never; cancelled: true };
/* ------------------------------------------------------------------------ */
/* 自定义市场源(Git / 本地文件夹) */
@@ -102,6 +110,10 @@ export interface MarketSourceConfig {
export interface MarketSourceSummary extends MarketSourceConfig {
/** 最近一次发现到的插件数;发现失败时为 0 并携带 status。 */
pluginCount: number;
+ /** 清单中因内容非法被跳过的插件条目数。 */
+ skippedCount: number;
+ /** 清单中因权限、文件锁或瞬时 I/O 暂时无法读取的插件条目数。 */
+ unreadableCount: number;
status: 'ok' | 'error';
/** status === 'error' 时的 IPC 错误码(Renderer 按码本地化)。 */
errorCode: string | null;