Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): 企业插件静默升级(org + defaultInstall,含目录级扩权自动放行) (#2129)

fmfsaisaicb90e5c23cec
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
index f9749252dc..fe195b8994 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
@@ -1938,6 +1938,8 @@ describe('anyInflightWork(更新重启阻断探针)', () => {
generateImage: vi.fn(async () => {
// 请求已计入 inflight、但还没结算的那一刻。
expect(slot.anyInflightWork()).toBe(true);
+ expect(slot.hasInflightWorkFor('art')).toBe(true);
+ expect(slot.hasInflightWorkFor('other')).toBe(false);
await gate;
return { buffer: new Uint8Array([1]), mimeType: 'image/png' };
}),
@@ -1959,6 +1961,8 @@ describe('anyInflightWork(更新重启阻断探针)', () => {
const { slot } = makeSlot({
depositMedia: vi.fn(async () => {
seenDuring = slot.anyInflightWork();
+ expect(slot.hasInflightWorkFor('art')).toBe(true);
+ expect(slot.hasInflightWorkFor('other')).toBe(false);
await gate;
return { hash: 'a'.repeat(64), bytes: PNG_BYTES.length, usedBytes: 10, quotaBytes: 100 };
}),
@@ -2015,6 +2019,8 @@ describe('anyInflightWork(更新重启阻断探针)', () => {
expect(res).toMatchObject({ ok: true, status: 'running' });
// 受理即返回,job 仍在途 —— 此时没有任何 turn 级信号还亮着。
expect(slot.anyInflightWork()).toBe(true);
+ expect(slot.hasInflightWorkFor('art')).toBe(true);
+ expect(slot.hasInflightWorkFor('other')).toBe(false);
release();
});
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
index 19459825c6..dcda32382c 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
@@ -349,6 +349,29 @@ describe('结果截断', () => {
});
describe('clearGhost', () => {
+ it('clearGhost 后仍把在途 errand 视为忙,直到 execute finally 收口', async () => {
+ let release: (() => void) | null = null;
+ const runner = vi.fn(
+ () =>
+ new Promise((resolve) => {
+ release = () => resolve({ ok: true, sessionId: 'sess-1', text: 'done' });
+ }),
+ );
+ const { slot } = makeSlot({ runner: runner as unknown as GhostErrandRunner });
+
+ await expect(slot.handleRequest('helper', RUN)).resolves.toMatchObject({
+ ok: true,
+ status: 'running',
+ });
+ expect(slot.hasActiveErrandFor('helper')).toBe(true);
+ slot.clearGhost('helper');
+ expect(slot.hasActiveErrandFor('helper')).toBe(true);
+
+ release!();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(slot.hasActiveErrandFor('helper')).toBe(false);
+ });
+
it('清除任务记录与节流状态', async () => {
const { slot, clock } = makeSlot();
const a = await slot.handleRequest('helper', RUN);
diff --git a/apps/desktop/src/main/cindy-brain/cindySlot.ts b/apps/desktop/src/main/cindy-brain/cindySlot.ts
index 506b58ec00..8bdf5e43df 100644
--- a/apps/desktop/src/main/cindy-brain/cindySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/cindySlot.ts
@@ -565,7 +565,7 @@ export class GhostCindySlot {
* 代办限流账(getInflightLimit),这个只回答「重启会打断什么」—— 理由见 handleModelRequest
* 里那两个分支的注释。
*/
- private mediaOps = 0;
+ private readonly mediaOps = new Map<string, number>();
/** 异步代办任务表(jobId → 记录;惰性 sweep,过期即清)。 */
private readonly jobs = new Map<string, CindyAsyncJob>();
/**
@@ -621,7 +621,7 @@ export class GhostCindySlot {
// 刻意用独立计数而不并入 inflight:那个是**代办限流账**(getInflightLimit),
// 把面板里删素材 / 粘贴图算进去会让它们撞上「同时进行的代办已达上限」——
// 那是行为变更,不是本改动该做的事。这里只服务于「重启会打断什么」的判定。
- this.mediaOps += 1;
+ this.mediaOps.set(ghostId, (this.mediaOps.get(ghostId) ?? 0) + 1);
try {
return p.kind === 'deposit_media'
? await this.handleDepositMedia(ghostId, p)
@@ -634,7 +634,9 @@ export class GhostCindySlot {
});
return { ok: false, message: `${verb}失败:${message}` };
} finally {
- this.mediaOps -= 1;
+ const left = (this.mediaOps.get(ghostId) ?? 1) - 1;
+ if (left <= 0) this.mediaOps.delete(ghostId);
+ else this.mediaOps.set(ghostId, left);
}
}
// 快问快答(text.oneshot):不经媒体生成链、不选型、秒级同步——单独
@@ -1162,7 +1164,18 @@ export class GhostCindySlot {
for (const count of this.inflight.values()) {
if (count > 0) return true;
}
- return this.mediaOps > 0;
+ for (const count of this.mediaOps.values()) {
+ if (count > 0) return true;
+ }
+ return false;
+ }
+
+ /** 是否有指定 Ghost 的在途 Cindy 工作;jobs、inflight、mediaOps 三类来源按 Ghost 隔离。 */
+ hasInflightWorkFor(ghostId: string): boolean {
+ for (const job of this.jobs.values()) {
+ if (job.ghostId === ghostId && job.status === 'running') return true;
+ }
+ return (this.inflight.get(ghostId) ?? 0) > 0 || (this.mediaOps.get(ghostId) ?? 0) > 0;
}
private evictSettledJobs(ghostId: string): void {
diff --git a/apps/desktop/src/main/cindy-brain/errandSlot.ts b/apps/desktop/src/main/cindy-brain/errandSlot.ts
index cc3ebdb416..8f0336102d 100644
--- a/apps/desktop/src/main/cindy-brain/errandSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/errandSlot.ts
@@ -145,6 +145,13 @@ export class GhostErrandSlot {
this.runner = runner;
}
+ /** clearGhost 只删 jobs,不删 inFlightGhosts;收口前两者可能短暂不一致。 */
+ hasActiveErrandFor(ghostId: string): boolean {
+ return this.inFlightGhosts.has(ghostId) || [...this.jobs.values()].some(
+ (job) => job.ghostId === ghostId && job.status === 'running',
+ );
+ }
+
/** 插件停用/卸载时清除节流状态与任务记录,防止权限/信息残留。 */
clearGhost(ghostId: string): void {
this.lastRunAt.delete(ghostId);
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 032c14c94e..c81365de8c 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1095,6 +1095,10 @@ export function getGhostPipeDispatcher(): GhostPipeDispatcher {
return dispatcherSingleton;
}
+export function hasPendingGhostCalls(ghostId: string): boolean {
+ return getGhostPipeDispatcher().hasPendingCallsFor(ghostId);
+}
+
let agentSlotSingleton: GhostAgentSlot | null = null;
/** Agent 新回合槽单例:一次性点击票、后台权限与模板替换的统一守门点。 */
@@ -1130,6 +1134,14 @@ export function getGhostErrandSlot(): GhostErrandSlot {
return errandSlotSingleton;
}
+export function hasRunningGhostErrand(ghostId: string): boolean {
+ return getGhostErrandSlot().hasActiveErrandFor(ghostId);
+}
+
+export function hasRunningGhostCindyWork(ghostId: string): boolean {
+ return getGhostCindySlot().hasInflightWorkFor(ghostId);
+}
+
/** maker-ipc 完成初始化后注入真实派活 runner;传 null 用于退出清理。 */
export function setGhostErrandRunner(runner: GhostErrandRunner | null): void {
getGhostErrandSlot().setRunner(runner);
@@ -3607,6 +3619,7 @@ export async function installOrUpdateMarketGhostPackage(
/** 用户确认过的真实下载包 SHA 与确认时的已装权限基线。 */
approvedPackageSha256?: string;
reviewedBaseline?: string;
+ beforeCommitInLock?: () => void;
/** 仅 server-market 主机路径可传;custom/local 不传。 */
officialCindyGithub?: boolean;
},
@@ -3628,6 +3641,7 @@ async function installOrUpdateMarketGhostPackageLocked(
permissionBaselineManifest?: GhostManifest;
approvedPackageSha256?: string;
reviewedBaseline?: string;
+ beforeCommitInLock?: () => void;
officialCindyGithub?: boolean;
},
): Promise<InstalledGhost> {
@@ -3718,6 +3732,7 @@ async function installOrUpdateMarketGhostPackageLocked(
});
}
+ expected.beforeCommitInLock?.();
const runtime = getGhostRuntime();
runtime.stop(expected.ghostId);
getGhostNodeRuntimeBroker().stop(expected.ghostId);
diff --git a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
index bb1c7ad30c..8fe1754094 100644
--- a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
+++ b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
@@ -125,6 +125,13 @@ export class GhostPipeDispatcher {
return this.pending.size;
}
+ hasPendingCallsFor(ghostId: string): boolean {
+ for (const entry of this.pending.values()) {
+ if (entry.ghostId === ghostId) return true;
+ }
+ return false;
+ }
+
/**
* 派活主入口(ghost 总机的 callGhostTool 回调)。
* 永不 reject——一切失败都折叠成结构化 GhostToolCallResult。
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
index 7db9e405fb..db48c71c4c 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -29,7 +29,7 @@ describe('Plugin Market IPC error boundary', () => {
expect(body).toContain('if (isIpcError(error)) throw error;');
expect(body).toContain("throwIpcError('INTERNAL', 'Plugin market operation failed');");
- expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(11);
+ expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(12);
});
it('guards removal notice consumption and signals trusted app windows only', () => {
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 d41341ed70..dafa0a38ad 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -19,6 +19,9 @@ const runtime = vi.hoisted(() => ({
uninstall: vi.fn(),
builtinRemoved: new Set<string>(),
accountGhostAvailable: true,
+ pendingCalls: false,
+ runningErrand: false,
+ cindyWork: false,
boundaryPending: false,
pluginApiBaseUrl: 'https://plugin.test.invalid' as string | null,
session: {
@@ -56,6 +59,9 @@ vi.mock('../../cindy-brain/index.js', () => ({
getGhostManager: () => ({ list: () => runtime.ghosts }),
isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),
installOrUpdateMarketGhostPackage: runtime.install,
+ hasPendingGhostCalls: vi.fn(() => runtime.pendingCalls),
+ hasRunningGhostErrand: vi.fn(() => runtime.runningErrand),
+ hasRunningGhostCindyWork: vi.fn(() => runtime.cindyWork),
isBuiltinGhostRemovedByUser: (id: string) => runtime.builtinRemoved.has(id),
uninstallGhostAndCleanup: runtime.uninstall,
}));
@@ -97,6 +103,9 @@ afterEach(() => {
runtime.uninstall.mockReset();
runtime.builtinRemoved.clear();
runtime.accountGhostAvailable = true;
+ runtime.pendingCalls = false;
+ runtime.runningErrand = false;
+ runtime.cindyWork = false;
runtime.boundaryPending = false;
runtime.pluginApiBaseUrl = 'https://plugin.test.invalid';
runtime.session = {
@@ -1038,6 +1047,494 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
});
+ it('silently updates an organization defaultInstall package and preserves disabled state', async () => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: {
+ ...summary().currentRelease,
+ id: 'release-2',
+ version: '2.0.0',
+ },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: false }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ const upgraded = manifest(item.ghostId, '2.0.0');
+ runtime.install.mockImplementation(async () => {
+ runtime.ghosts = [{ manifest: upgraded, dir: installDir, enabled: false }];
+ return runtime.ghosts[0];
+ });
+
+ const snapshot = await h.service.snapshot();
+
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.stringMatching(/\.cindy$/),
+ expect.objectContaining({
+ ghostId: item.ghostId,
+ version: '2.0.0',
+ reviewedManifest: upgraded,
+ }),
+ );
+ expect(snapshot.items[0]).toMatchObject({ installState: 'installed', enabled: false });
+ expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Test Plugin', permissions: null, hasPermissionExpansion: false });
+ });
+
+ it('integration: snapshot upgrades an organization defaultInstall release and consumes its notice', async () => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: {
+ ...summary().currentRelease,
+ id: 'release-2',
+ version: '2.0.0',
+ },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-integration-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ const upgraded = manifest(item.ghostId, '2.0.0');
+ runtime.install.mockImplementationOnce(async () => {
+ const ghost = { manifest: upgraded, dir: installDir, enabled: true };
+ runtime.ghosts = [ghost];
+ return ghost;
+ });
+
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [{ installState: 'installed', version: '2.0.0' }],
+ unavailableReason: null,
+ });
+ expect(h.api.listAll).toHaveBeenCalledTimes(1);
+ expect(h.api.detail).toHaveBeenCalledWith(item.id);
+ expect(h.api.download).toHaveBeenCalledWith(item.id, 'release-2');
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Test Plugin', permissions: null, hasPermissionExpansion: false });
+ expect(h.service.consumeUpgradeNotice()).toBeNull();
+ });
+
+ it('skips a queued duplicate snapshot after the first upgrade reconciles the release', async () => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-concurrent-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ const upgraded = manifest(item.ghostId, '2.0.0');
+ runtime.install.mockImplementationOnce(async () => {
+ const ghost = { manifest: upgraded, dir: installDir, enabled: true };
+ runtime.ghosts = [ghost];
+ return ghost;
+ });
+
+ const first = h.service.snapshot();
+ const second = h.service.snapshot();
+ await Promise.all([first, second]);
+
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Test Plugin', permissions: null, hasPermissionExpansion: false });
+ expect(h.service.consumeUpgradeNotice()).toBeNull();
+ });
+
+ it('silently upgrades organization plugins that expand catalog permissions and reports the new permissions', async () => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ const expanded = manifest(item.ghostId, '2.0.0', ['notify', 'fs']);
+ h.api.detail.mockResolvedValueOnce({
+ ...item,
+ currentRelease: { ...item.currentRelease, manifest: expanded },
+ } as never);
+
+ const upgraded = manifest(item.ghostId, '2.0.0', ['notify', 'fs']);
+ runtime.install.mockImplementationOnce(async () => {
+ runtime.ghosts = [{ manifest: upgraded, dir: installDir, enabled: true }];
+ return runtime.ghosts[0];
+ });
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [{ installState: 'installed', version: '2.0.0' }],
+ });
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.service.consumeUpgradeNotice()).toEqual({
+ count: 1,
+ name: 'Test Plugin',
+ permissions: [{ key: 'fs', labelKey: 'fsWrite' }],
+ hasPermissionExpansion: true,
+ });
+ });
+
+ it('skips organization upgrades when the downloaded package drifts to extra permissions', async () => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ runtime.install.mockRejectedValueOnce(
+ new GhostPackagePermissionReviewRequiredError({
+ manifest: manifest(item.ghostId, '2.0.0', ['notify', 'fs']),
+ permissionDiff: diffGhostPermissionItems(oldManifest, manifest(item.ghostId, '2.0.0', ['notify', 'fs'])),
+ packageSha256: item.currentRelease.sha256,
+ installedBaseline: ghostPermissionBaselineKey(oldManifest),
+ }),
+ );
+
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [{ installState: 'update-available' }],
+ });
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.service.consumeUpgradeNotice()).toBeNull();
+ });
+
+ it('abandons a silent upgrade before download when the installed permission baseline changes', async () => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-stale-baseline-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ const expanded = manifest(item.ghostId, '2.0.0', ['notify', 'fs']);
+ h.api.detail.mockImplementationOnce(async () => {
+ const changed = manifest(item.ghostId, '1.0.0', ['notify', 'workspace'] as never);
+ runtime.ghosts = [{ manifest: changed, dir: installDir, enabled: true }];
+ return {
+ ...item,
+ currentRelease: { ...item.currentRelease, manifest: expanded },
+ } as never;
+ });
+
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [{ installState: 'update-available' }],
+ });
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.service.consumeUpgradeNotice()).toBeNull();
+ });
+
+ it('abandons a silent upgrade when the installed permission baseline changes during download', async () => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-stale-baseline-lock-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ const expanded = manifest(item.ghostId, '2.0.0', ['notify', 'fs']);
+ h.api.detail.mockResolvedValueOnce({
+ ...item,
+ currentRelease: { ...item.currentRelease, manifest: expanded },
+ } as never);
+ const downloadMock = vi.mocked(
+ (await import('../download.js')).downloadVerifiedPlugin,
+ );
+ const downloadStarted = deferred();
+ const downloadGate = deferred();
+ downloadMock.mockImplementationOnce(async () => {
+ downloadStarted.resolve();
+ await downloadGate.promise;
+ });
+
+ const snapshotPromise = h.service.snapshot();
+ await downloadStarted.promise;
+ const changed = manifest(item.ghostId, '1.0.0', ['notify', 'workspace'] as never);
+ runtime.ghosts = [{ manifest: changed, dir: installDir, enabled: true }];
+ downloadGate.resolve();
+
+ await expect(snapshotPromise).resolves.toMatchObject({
+ items: [{ installState: 'update-available' }],
+ });
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.service.consumeUpgradeNotice()).toBeNull();
+ });
+
+ it.each(['pendingCalls', 'runningErrand', 'cindyWork'] as const)(
+ 'skips a busy organization upgrade and retries on the next snapshot (%s)',
+ async (signal) => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ runtime[signal] = true;
+ const upgraded = manifest(item.ghostId, '2.0.0');
+ runtime.install.mockImplementation(async () => {
+ runtime.ghosts = [{ manifest: upgraded, dir: installDir, enabled: true }];
+ return runtime.ghosts[0];
+ });
+
+ await h.service.snapshot();
+ expect(runtime.install).not.toHaveBeenCalled();
+ runtime[signal] = false;
+ await h.service.snapshot();
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Test Plugin', permissions: null, hasPermissionExpansion: false });
+ },
+ );
+
+ it('skips organization upgrades that require a newer Cindy version', async () => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ const incompatible = { ...manifest(item.ghostId, '2.0.0'), minCindyVersion: '99.0.0' };
+ h.api.detail.mockResolvedValueOnce({
+ ...item,
+ currentRelease: { ...item.currentRelease, manifest: incompatible },
+ } as never);
+
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [{ installState: 'update-available' }],
+ });
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('continues upgrading other organization plugins when one upgrade fails', async () => {
+ const first = summary({
+ scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const second = summary({
+ id: `c${'b'.repeat(24)}`, ghostId: 'cindy-second', name: 'Second Plugin',
+ scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2b', version: '2.0.0' },
+ });
+ const firstDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ const secondDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ roots.push(firstDir, secondDir);
+ const firstManifest = manifest(first.ghostId, '1.0.0');
+ const secondManifest = manifest(second.ghostId, '1.0.0');
+ fs.writeFileSync(path.join(firstDir, 'ghost.json'), JSON.stringify(firstManifest));
+ fs.writeFileSync(path.join(secondDir, 'ghost.json'), JSON.stringify(secondManifest));
+ runtime.ghosts = [
+ { manifest: firstManifest, dir: firstDir, enabled: true },
+ { manifest: secondManifest, dir: secondDir, enabled: true },
+ ];
+ const h = harness([first, second]);
+ h.ledger.upsertInstallation({ ...recordForTest(first), releaseId: 'release-1', version: '1.0.0', manifestDigest: ghostManifestDigest(firstManifest) });
+ h.ledger.upsertInstallation({ ...recordForTest(second), releaseId: 'release-1b', version: '1.0.0', manifestDigest: ghostManifestDigest(secondManifest) });
+ runtime.install
+ .mockRejectedValueOnce(new Error('first failed'))
+ .mockImplementationOnce(async (_file, expected) => {
+ const upgraded = {
+ ...manifest(expected.ghostId, '2.0.0'),
+ ...(expected.ghostId === second.ghostId ? { name: 'Second Plugin' } : {}),
+ };
+ const dir = expected.ghostId === first.ghostId ? firstDir : secondDir;
+ const ghost = { manifest: upgraded, dir, enabled: true };
+ runtime.ghosts = runtime.ghosts.map((candidate) => candidate.manifest.id === expected.ghostId ? ghost : candidate);
+ return ghost;
+ });
+
+ await expect(h.service.snapshot()).resolves.toMatchObject({ unavailableReason: null });
+ expect(runtime.install).toHaveBeenCalledTimes(2);
+ expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Second Plugin', permissions: null, hasPermissionExpansion: false });
+ });
+
+ it('does not silently update public or non-defaultInstall plugins', async () => {
+ const publicItem = summary({ defaultInstall: true, currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' } });
+ const nonDefault = summary({
+ id: `c${'b'.repeat(24)}`, ghostId: 'cindy-second', scope: 'organization', organizationId: 'org-1', defaultInstall: false,
+ currentRelease: { ...summary().currentRelease, id: 'release-2b', version: '2.0.0' },
+ });
+ const firstDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ const secondDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ roots.push(firstDir, secondDir);
+ const firstManifest = manifest(publicItem.ghostId, '1.0.0');
+ const secondManifest = manifest(nonDefault.ghostId, '1.0.0');
+ fs.writeFileSync(path.join(firstDir, 'ghost.json'), JSON.stringify(firstManifest));
+ fs.writeFileSync(path.join(secondDir, 'ghost.json'), JSON.stringify(secondManifest));
+ runtime.ghosts = [
+ { manifest: firstManifest, dir: firstDir, enabled: true },
+ { manifest: secondManifest, dir: secondDir, enabled: true },
+ ];
+ const h = harness([publicItem, nonDefault]);
+ h.ledger.upsertInstallation({ ...recordForTest(publicItem), releaseId: 'release-1', version: '1.0.0', manifestDigest: ghostManifestDigest(firstManifest) });
+ h.ledger.upsertInstallation({ ...recordForTest(nonDefault), releaseId: 'release-1b', version: '1.0.0', manifestDigest: ghostManifestDigest(secondManifest) });
+
+ const snapshot = await h.service.snapshot();
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(snapshot.items.map((entry) => entry.installState)).toEqual(['update-available', 'update-available']);
+ });
+
+ it('aggregates upgrade notices and filters directional controls from a single name', async () => {
+ const item = summary({
+ scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({ ...recordForTest(item), releaseId: 'release-1', version: '1.0.0', manifestDigest: ghostManifestDigest(oldManifest) });
+ const upgraded = { ...manifest(item.ghostId, '2.0.0'), name: '\u202eSecret Plugin' };
+ h.api.detail.mockResolvedValueOnce({ ...item, currentRelease: { ...item.currentRelease, manifest: upgraded } } as never);
+ runtime.install.mockResolvedValueOnce({ manifest: upgraded, dir: installDir, enabled: true });
+
+ await h.service.snapshot();
+ expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Secret Plugin', permissions: null, hasPermissionExpansion: false });
+ expect(h.service.consumeUpgradeNotice()).toBeNull();
+ });
+
+ it('aggregates multiple upgrades and flags permission expansion without listing names', async () => {
+ const first = summary({
+ scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const second = summary({
+ id: `c${'b'.repeat(24)}`, ghostId: 'cindy-second', name: 'Second Plugin',
+ scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2b', version: '2.0.0' },
+ });
+ const firstDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ const secondDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
+ roots.push(firstDir, secondDir);
+ const firstManifest = manifest(first.ghostId, '1.0.0');
+ const secondManifest = manifest(second.ghostId, '1.0.0');
+ fs.writeFileSync(path.join(firstDir, 'ghost.json'), JSON.stringify(firstManifest));
+ fs.writeFileSync(path.join(secondDir, 'ghost.json'), JSON.stringify(secondManifest));
+ runtime.ghosts = [
+ { manifest: firstManifest, dir: firstDir, enabled: true },
+ { manifest: secondManifest, dir: secondDir, enabled: true },
+ ];
+ const h = harness([first, second]);
+ h.ledger.upsertInstallation({ ...recordForTest(first), releaseId: 'release-1', version: '1.0.0', manifestDigest: ghostManifestDigest(firstManifest) });
+ h.ledger.upsertInstallation({ ...recordForTest(second), releaseId: 'release-1b', version: '1.0.0', manifestDigest: ghostManifestDigest(secondManifest) });
+ h.api.detail.mockImplementation(async (id) => {
+ const plugin = id === first.id ? first : second;
+ const nextManifest = id === first.id
+ ? manifest(plugin.ghostId, '2.0.0', ['notify', 'fs'])
+ : manifest(plugin.ghostId, '2.0.0');
+ return { ...plugin, currentRelease: { ...plugin.currentRelease, manifest: nextManifest } } as never;
+ });
+ runtime.install.mockImplementation(async (_file, expected) => {
+ const dir = expected.ghostId === first.ghostId ? firstDir : secondDir;
+ const upgraded = { ...manifest(expected.ghostId, '2.0.0', expected.ghostId === first.ghostId ? ['notify', 'fs'] : ['notify']), name: expected.ghostId === second.ghostId ? 'Second Plugin' : 'Test Plugin' };
+ const ghost = { manifest: upgraded, dir, enabled: true };
+ runtime.ghosts = runtime.ghosts.map((candidate) => candidate.manifest.id === expected.ghostId ? ghost : candidate);
+ return ghost;
+ });
+
+ await h.service.snapshot();
+ expect(h.service.consumeUpgradeNotice()).toEqual({
+ count: 2,
+ name: null,
+ permissions: null,
+ hasPermissionExpansion: true,
+ });
+ });
+
it('installs a public market plugin in account-free local mode', async () => {
runtime.session = {
mode: 'local',
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 8a580fcbf9..7b293c8563 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -19,6 +19,7 @@ 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 UPGRADE_NOTICE_AVAILABLE_CHANNEL = 'plugin-market:upgrade-notice-available';
const PACKAGE_PERMISSION_REVIEW_CHANNEL = 'plugin-market:package-permission-review';
const trackedReviewRequesters = new WeakSet<WebContents>();
const packagePermissionReviewBridge = new PluginMarketPackagePermissionReviewBridge();
@@ -33,6 +34,11 @@ function signalRemovalNoticeAvailable(): void {
sendToTrustedAppWindows(REMOVAL_NOTICE_AVAILABLE_CHANNEL, undefined);
}
+function signalUpgradeNoticeAvailable(): void {
+ if (!service().hasPendingUpgradeNotice()) return;
+ sendToTrustedAppWindows(UPGRADE_NOTICE_AVAILABLE_CHANNEL, undefined);
+}
+
async function snapshotAndSignalRemovalNotice() {
try {
return await service().snapshot();
@@ -40,6 +46,7 @@ async function snapshotAndSignalRemovalNotice() {
// 清理已成功但后续默认安装等步骤失败时,pending 仍必须通知 Renderer;
// snapshot 的原始异常继续向上抛,不把通知信号伪装成整轮成功。
signalRemovalNoticeAvailable();
+ signalUpgradeNoticeAvailable();
}
}
@@ -105,6 +112,10 @@ export function registerPluginMarketIpc(): void {
assertTrustedAppRendererEvent(event);
return invokePluginMarket(async () => service().consumeRemovalNotice());
});
+ ipcMain.handle('plugin-market:consume-upgrade-notice', (event) => {
+ assertTrustedAppRendererEvent(event);
+ return invokePluginMarket(async () => service().consumeUpgradeNotice());
+ });
ipcMain.handle('plugin-market:detail', (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 4bb2fc6f50..26caf2c7b3 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -29,6 +29,8 @@ import type {
PluginMarketPackageReviewFacts,
PluginMarketSnapshot,
PluginRemovalUserNotice,
+ PluginUpgradePermissionNotice,
+ PluginUpgradeUserNotice,
} from '../../shared/pluginMarket.js';
import {
customMarketPluginId,
@@ -39,6 +41,9 @@ import {
import { getCurrentUserId } from '../authManager.js';
import {
getGhostManager,
+ hasPendingGhostCalls,
+ hasRunningGhostCindyWork,
+ hasRunningGhostErrand,
installOrUpdateMarketGhostPackage,
isGhostAvailableForActiveSession,
isBuiltinGhostRemovedByUser,
@@ -79,6 +84,9 @@ type PackagePermissionReviewer = (
facts: PluginMarketPackageReviewFacts,
) => Promise<boolean>;
+class SilentUpgradeBusyError extends Error {}
+class SilentUpgradeStaleBaselineError extends Error {}
+
/**
* 来源增删改的互斥键。自定义市场安装的提交段也要拿这把锁,保证所选来源从
* 复核到包落位之间不会被移除或替换。官方市场安装不依赖自定义市场目录,不能
@@ -351,6 +359,10 @@ function removalNoticeKey(owner: ActiveAppSession): string {
return `${owner.mode}:${owner.dataOwnerId}`;
}
+function upgradeNoticeKey(owner: ActiveAppSession): string {
+ return `${owner.mode}:${owner.dataOwnerId}`;
+}
+
/**
* Plugin 市场的 main 端协调器。远程不可用时不碰本地目录;安装写路径必须依次
* 通过 protocol parser、下载大小/SHA 校验、Ghost runtime validator 和原子换目录。
@@ -359,6 +371,7 @@ export class PluginMarketService {
private readonly mutations = new Map<string, Promise<unknown>>();
private ledgerMutation: Promise<void> = Promise.resolve();
private readonly pendingRemovalNotices = new Map<string, PluginRemovalUserNotice>();
+ private readonly pendingUpgradeNotices = new Map<string, PluginUpgradeUserNotice>();
constructor(
private readonly api = new PluginMarketApi(undefined, () => app.getVersion()),
@@ -433,6 +446,7 @@ export class PluginMarketService {
// 自定义来源只影响自己的目录发现;暂时不可读的来源不能阻塞官方默认安装。
// 已经落地的同 id 插件仍由 applyDefaultInstalls → installDetail 的本地事实检查保护。
await this.applyDefaultInstalls(plugins, owner, ledger);
+ await this.applyDefaultUpgrades(plugins, owner, ledger);
requireSameMarketOwner(owner);
const local = this.localInstallSnapshot(ledger);
const serverItems = plugins.map((plugin) => this.toItem(plugin, local));
@@ -464,6 +478,22 @@ export class PluginMarketService {
}
}
+ consumeUpgradeNotice(): PluginUpgradeUserNotice | null {
+ const key = upgradeNoticeKey(captureMarketOwner());
+ const notice = this.pendingUpgradeNotices.get(key) ?? null;
+ if (notice) this.pendingUpgradeNotices.delete(key);
+ return notice;
+ }
+
+ hasPendingUpgradeNotice(): boolean {
+ if (this.pendingUpgradeNotices.size === 0) return false;
+ try {
+ return this.pendingUpgradeNotices.has(upgradeNoticeKey(captureMarketOwner()));
+ } catch {
+ return false;
+ }
+ }
+
async detail(pluginId: string): Promise<PluginMarketDetail> {
// 自定义市场插件走本地发现,不要求服务端可用,也不受 CUID 形状约束。
const customRef = parseCustomMarketPluginId(pluginId);
@@ -1081,6 +1111,8 @@ export class PluginMarketService {
reviewedBaseline?: string;
/** 真实包比展示清单多权限时,在当前安装事务内立即询问发起窗口。 */
reviewPackagePermissions?: PackagePermissionReviewer;
+ beforeCommitInLock?: () => void;
+ silentBaselineMismatch?: boolean;
/** 确认操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */
expectedInstalled: boolean;
} = { expectedInstalled: false },
@@ -1110,6 +1142,7 @@ export class PluginMarketService {
reviewedManifest?.manifest,
options.allowPermissionExpansion,
options.reviewedBaseline,
+ options.silentBaselineMismatch,
);
const download = await this.api.download(plugin.id, plugin.currentRelease.id);
@@ -1143,6 +1176,8 @@ export class PluginMarketService {
: {}),
allowPermissionExpansion: options.allowPermissionExpansion,
reviewedBaseline: options.reviewedBaseline,
+ beforeCommitInLock: options.beforeCommitInLock,
+ silentBaselineMismatch: options.silentBaselineMismatch,
},
owner,
ledger,
@@ -1165,6 +1200,8 @@ export class PluginMarketService {
reviewedBaseline: options.reviewedBaseline,
approvedPackageSha256: error.review.packageSha256,
approvedPackageBaseline: error.review.installedBaseline,
+ beforeCommitInLock: options.beforeCommitInLock,
+ silentBaselineMismatch: options.silentBaselineMismatch,
},
owner,
ledger,
@@ -1185,6 +1222,8 @@ export class PluginMarketService {
reviewedBaseline?: string;
approvedPackageSha256?: string;
approvedPackageBaseline?: string | null;
+ beforeCommitInLock?: () => void;
+ silentBaselineMismatch?: boolean;
expectedInstalled: boolean;
},
owner: ActiveAppSession,
@@ -1215,6 +1254,7 @@ export class PluginMarketService {
options.reviewedManifest,
options.allowPermissionExpansion,
options.reviewedBaseline,
+ options.silentBaselineMismatch,
);
const installedRawManifest = installedNow
? installedGhostRawManifest(installedNow.dir)
@@ -1247,6 +1287,7 @@ export class PluginMarketService {
: {}),
}
: {}),
+ ...(options.beforeCommitInLock ? { beforeCommitInLock: options.beforeCommitInLock } : {}),
});
await this.withCapturedLedgerMutation(ledger, () => {
ledger.upsertInstallation(recordFrom(plugin, 'market', installed));
@@ -1260,6 +1301,7 @@ export class PluginMarketService {
reviewedManifest: GhostManifest | undefined,
allowPermissionExpansion: boolean | undefined,
reviewedBaseline: string | undefined,
+ silentBaselineMismatch = false,
): void {
if (
!installed ||
@@ -1271,6 +1313,13 @@ export class PluginMarketService {
if (allowPermissionExpansion !== true) {
throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');
}
+ if (
+ silentBaselineMismatch &&
+ reviewedBaseline !== undefined &&
+ ghostPermissionBaselineKey(installed) !== reviewedBaseline
+ ) {
+ throw new SilentUpgradeStaleBaselineError('Installed Plugin permissions changed');
+ }
assertReviewedBaselineFresh(installed, reviewedBaseline);
}
@@ -1589,6 +1638,115 @@ export class PluginMarketService {
}
}
+ private async applyDefaultUpgrades(
+ plugins: readonly VisiblePluginSummary[],
+ owner: ActiveAppSession,
+ ledger: PluginMarketLedger,
+ ): Promise<void> {
+ const local = this.localInstallSnapshot(ledger);
+ const completed: Array<{
+ name: string | null;
+ permissions: PluginUpgradePermissionNotice[];
+ }> = [];
+ for (const summary of plugins) {
+ if (!summary.defaultInstall || summary.scope !== 'organization') continue;
+ if (this.toItem(summary, local).installState !== 'update-available') continue;
+ if (
+ hasPendingGhostCalls(summary.ghostId) ||
+ hasRunningGhostErrand(summary.ghostId) ||
+ hasRunningGhostCindyWork(summary.ghostId)
+ ) continue;
+ try {
+ await this.withMutation(summary.id, async () => {
+ requireSameMarketOwner(owner);
+ if (
+ hasPendingGhostCalls(summary.ghostId) ||
+ hasRunningGhostErrand(summary.ghostId) ||
+ hasRunningGhostCindyWork(summary.ghostId)
+ ) {
+ throw new SilentUpgradeBusyError('Plugin is busy');
+ }
+ const freshLocal = this.localInstallSnapshot(ledger);
+ if (this.toItem(summary, freshLocal).installState !== 'update-available') {
+ log.debug?.('default plugin upgrade already reconciled', {
+ pluginId: summary.id,
+ });
+ return;
+ }
+ const freshInstalled = freshLocal.ghostsById.get(summary.ghostId);
+ const reviewedBaseline = freshInstalled
+ ? ghostPermissionBaselineKey(freshInstalled.manifest)
+ : undefined;
+ 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');
+ if (!manifestSupportsCurrentCindy(reviewedManifest.manifest)) {
+ log.warn('default plugin upgrade skipped for Cindy version', {
+ pluginId: summary.id,
+ minCindyVersion: reviewedManifest.manifest.minCindyVersion,
+ });
+ return;
+ }
+ const installed = await this.installDetail(detail, {
+ expectedInstalled: true,
+ reviewedManifest: reviewedManifest.manifest,
+ allowPermissionExpansion: true,
+ reviewedBaseline,
+ silentBaselineMismatch: true,
+ beforeCommitInLock: () => {
+ if (
+ hasPendingGhostCalls(summary.ghostId) ||
+ hasRunningGhostErrand(summary.ghostId) ||
+ hasRunningGhostCindyWork(summary.ghostId)
+ ) {
+ throw new SilentUpgradeBusyError('Plugin is busy');
+ }
+ },
+ }, owner, ledger);
+ if (installed) {
+ const addedPermissions = freshInstalled
+ ? diffGhostPermissionItems(freshInstalled.manifest, reviewedManifest.manifest).added
+ .map(({ key, labelKey, labelArgs }) => ({
+ key,
+ labelKey,
+ ...(labelArgs ? { labelArgs } : {}),
+ }))
+ : [];
+ completed.push({
+ name: stripDirectionalControls(installed.manifest.name) || null,
+ permissions: addedPermissions,
+ });
+ }
+ });
+ } catch (error) {
+ if (!(error instanceof SilentUpgradeBusyError || error instanceof SilentUpgradeStaleBaselineError)) {
+ log.warn('default plugin upgrade failed', {
+ pluginId: summary.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }
+ if (completed.length > 0) {
+ const key = upgradeNoticeKey(owner);
+ const count = (this.pendingUpgradeNotices.get(key)?.count ?? 0) + completed.length;
+ const hasPermissionExpansion =
+ (this.pendingUpgradeNotices.get(key)?.hasPermissionExpansion ?? false) ||
+ completed.some((entry) => entry.permissions.length > 0);
+ this.pendingUpgradeNotices.set(key, {
+ count,
+ name: count === 1 ? (completed[0]?.name ?? null) : null,
+ permissions:
+ count === 1 && completed[0]?.permissions.length
+ ? completed[0].permissions
+ : null,
+ hasPermissionExpansion,
+ });
+ }
+ }
+
private localInstallSnapshot(
ledger = this.ledger,
installations = ledger.read().installations,
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 894073f60b..10c20d855b 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -386,6 +386,9 @@ const fanOutCorruptionRestored = createIpcFanOut('local-db:corruption-restored')
const fanOutPluginRemovalNoticeAvailable = createIpcFanOut(
'plugin-market:removal-notice-available',
);
+const fanOutPluginUpgradeNoticeAvailable = createIpcFanOut(
+ 'plugin-market:upgrade-notice-available',
+);
const fanOutPluginMarketPackagePermissionReview = createIpcFanOut(
'plugin-market:package-permission-review',
);
@@ -1215,6 +1218,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
import('../shared/pluginMarket').PluginRemovalUserNotice | null
> => ipcRenderer.invoke('plugin-market:consume-removal-notice'),
onRemovalNoticeAvailable: fanOutPluginRemovalNoticeAvailable,
+ consumeUpgradeNotice: (): Promise<
+ import('../shared/pluginMarket').PluginUpgradeUserNotice | null
+ > => ipcRenderer.invoke('plugin-market:consume-upgrade-notice'),
+ onUpgradeNoticeAvailable: fanOutPluginUpgradeNoticeAvailable,
listSources: (): Promise<import('../shared/pluginMarket').MarketSourceSummary[]> =>
ipcRenderer.invoke('plugin-market:list-sources'),
pickLocalSource: (
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index f64f415808..0524616a44 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -77,6 +77,7 @@ import { useCorruptionRestoredToast } from '@/hooks/useCorruptionRestoredToast';
import { useSchemaDriftWarningToast } from '@/hooks/useSchemaDriftWarningToast';
import { useVoiceInputShortcutRecoveryToast } from '@/hooks/useVoiceInputShortcutRecoveryToast';
import { usePluginRemovalNoticeToast } from '@/hooks/usePluginRemovalNoticeToast';
+import { usePluginUpgradeNoticeToast } from '@/hooks/usePluginUpgradeNoticeToast';
import { requestProjectFocus } from '@/state/pendingProjectFocus';
import { patchDraft } from '@/state/newMakerDraft';
import { cn } from '@/lib/utils';
@@ -489,6 +490,7 @@ export function MainLayout() {
useVoiceInputShortcutRecoveryToast();
// 冷启动市场对账可能早于 Renderer 挂载;Main pending + 常驻 consume 保证清理不静默。
usePluginRemovalNoticeToast();
+ usePluginUpgradeNoticeToast();
// device-link 跨设备远程控制:同账号在线 + 开了被控的设备,其项目自动并入侧边栏
useDeviceLinkRemoteProjects();
diff --git a/apps/desktop/src/renderer/hooks/__tests__/usePluginUpgradeNoticeToast.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/usePluginUpgradeNoticeToast.test.tsx
new file mode 100644
index 0000000000..5d5df5206c
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/usePluginUpgradeNoticeToast.test.tsx
@@ -0,0 +1,115 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ listener: undefined as (() => void) | undefined,
+ secondary: false,
+ consume: vi.fn(),
+ subscribe: vi.fn(),
+ unsubscribe: vi.fn(),
+ toastInfo: vi.fn(),
+ translate: vi.fn((key: string) => key),
+ language: 'en',
+ warn: vi.fn(),
+}));
+
+vi.mock('@/i18n', () => ({ i18n: { t: mocks.translate, language: mocks.language } }));
+vi.mock('@/lib/secondaryWindow', () => ({ isSecondaryWindow: () => mocks.secondary }));
+vi.mock('@/lib/toast', () => ({ toast: { info: mocks.toastInfo } }));
+vi.mock('@/lib/logger', () => ({ createLogger: () => ({ warn: mocks.warn }) }));
+
+import { usePluginUpgradeNoticeToast } from '../usePluginUpgradeNoticeToast';
+
+describe('usePluginUpgradeNoticeToast', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.listener = undefined;
+ mocks.secondary = false;
+ mocks.consume.mockResolvedValue(null);
+ mocks.subscribe.mockImplementation((listener: () => void) => {
+ mocks.listener = listener;
+ return mocks.unsubscribe;
+ });
+ (window as unknown as { electronAPI: { pluginMarket: unknown } }).electronAPI = {
+ pluginMarket: {
+ consumeUpgradeNotice: mocks.consume,
+ onUpgradeNoticeAvailable: mocks.subscribe,
+ },
+ };
+ });
+ afterEach(() => cleanup());
+
+ it('single notice includes plugin name', async () => {
+ mocks.consume.mockResolvedValueOnce({
+ count: 1,
+ name: 'Team Plugin',
+ permissions: null,
+ hasPermissionExpansion: false,
+ });
+ renderHook(() => usePluginUpgradeNoticeToast());
+ await waitFor(() => expect(mocks.toastInfo).toHaveBeenCalledTimes(1));
+ expect(mocks.translate).toHaveBeenCalledWith('settings.ghosts.market.upgradeNotice.single', {
+ name: 'Team Plugin',
+ });
+ });
+
+ it('multiple notice reports count and consumes push signals', async () => {
+ renderHook(() => usePluginUpgradeNoticeToast());
+ await waitFor(() => expect(mocks.consume).toHaveBeenCalledTimes(1));
+ mocks.consume.mockResolvedValueOnce({
+ count: 2,
+ name: null,
+ permissions: null,
+ hasPermissionExpansion: false,
+ });
+ act(() => mocks.listener?.());
+ await waitFor(() => expect(mocks.translate).toHaveBeenCalledWith(
+ 'settings.ghosts.market.upgradeNotice.multiple',
+ { count: 2 },
+ ));
+ });
+
+ it('single expansion notice translates and names new permissions', async () => {
+ mocks.translate.mockImplementation((key: string, args?: Record<string, string>) =>
+ args ? `${key}:${JSON.stringify(args)}` : key,
+ );
+ mocks.consume.mockResolvedValueOnce({
+ count: 1,
+ name: 'Team Plugin',
+ permissions: [
+ { key: 'networkHost:api.example.com', labelKey: 'networkHost', labelArgs: { host: 'api.example.com' } },
+ { key: 'fs', labelKey: 'fsWrite' },
+ ],
+ hasPermissionExpansion: true,
+ });
+ renderHook(() => usePluginUpgradeNoticeToast());
+ await waitFor(() => expect(mocks.toastInfo).toHaveBeenCalledTimes(1));
+ expect(mocks.translate).toHaveBeenCalledWith('settings.ghosts.perm.networkHost', {
+ host: 'api.example.com',
+ });
+ expect(mocks.translate).toHaveBeenCalledWith(
+ 'settings.ghosts.market.upgradeNotice.singleWithPermissions',
+ expect.objectContaining({
+ name: 'Team Plugin',
+ permissions: expect.stringContaining(', '),
+ }),
+ );
+ });
+
+ it('multiple expansion notice uses aggregated copy', async () => {
+ mocks.consume.mockResolvedValueOnce({
+ count: 2,
+ name: null,
+ permissions: null,
+ hasPermissionExpansion: true,
+ });
+ renderHook(() => usePluginUpgradeNoticeToast());
+ await waitFor(() => expect(mocks.toastInfo).toHaveBeenCalledTimes(1));
+ expect(mocks.translate).toHaveBeenCalledWith(
+ 'settings.ghosts.market.upgradeNotice.multipleWithPermissions',
+ { count: 2 },
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/usePluginUpgradeNoticeToast.ts b/apps/desktop/src/renderer/hooks/usePluginUpgradeNoticeToast.ts
new file mode 100644
index 0000000000..b8fb8e5d28
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/usePluginUpgradeNoticeToast.ts
@@ -0,0 +1,53 @@
+import { useEffect } from 'react';
+
+import { i18n } from '@/i18n';
+import { createLogger } from '@/lib/logger';
+import { isSecondaryWindow } from '@/lib/secondaryWindow';
+import { toast } from '@/lib/toast';
+
+const log = createLogger('usePluginUpgradeNoticeToast');
+
+export function usePluginUpgradeNoticeToast(): void {
+ useEffect(() => {
+ if (isSecondaryWindow()) return undefined;
+ let cancelled = false;
+ const showIfPending = async (): Promise<void> => {
+ try {
+ const notice = await window.electronAPI.pluginMarket.consumeUpgradeNotice();
+ if (cancelled || !notice) return;
+ const permissions = notice.permissions
+ ? new Intl.ListFormat(i18n.language, {
+ type: 'conjunction',
+ style: 'narrow',
+ }).format(notice.permissions.map((permission) =>
+ i18n.t(`settings.ghosts.perm.${permission.labelKey}`, permission.labelArgs),
+ ))
+ : undefined;
+ const message =
+ notice.count === 1 && notice.name
+ ? notice.hasPermissionExpansion && permissions
+ ? i18n.t('settings.ghosts.market.upgradeNotice.singleWithPermissions', {
+ name: notice.name,
+ permissions,
+ })
+ : i18n.t('settings.ghosts.market.upgradeNotice.single', { name: notice.name })
+ : notice.hasPermissionExpansion
+ ? i18n.t('settings.ghosts.market.upgradeNotice.multipleWithPermissions', {
+ count: notice.count,
+ })
+ : i18n.t('settings.ghosts.market.upgradeNotice.multiple', { count: notice.count });
+ toast.info(message, { duration: 8000 });
+ } catch (error) {
+ log.warn('failed to consume plugin upgrade notice:', error);
+ }
+ };
+ const unsubscribe = window.electronAPI.pluginMarket.onUpgradeNoticeAvailable(() => {
+ void showIfPending();
+ });
+ void showIfPending();
+ return () => {
+ cancelled = true;
+ unsubscribe();
+ };
+ }, []);
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 24e915dfeb..6177927fbb 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3241,6 +3241,14 @@
"unavailable": "The plugin market is temporarily unavailable. Installed plugins remain available.",
"authenticationRequired": "Sign in to Cindy to view the plugin market.",
"notConfigured": "The plugin market is not configured for this environment. Installed plugins remain available.",
+ "upgradeNotice": {
+ "single": "Automatically updated organization plugin “{{name}}”.",
+ "multiple_one": "Automatically updated {{count}} organization plugin.",
+ "multiple_other": "Automatically updated {{count}} organization plugins.",
+ "singleWithPermissions": "Automatically updated organization plugin “{{name}}”; new permissions: {{permissions}}.",
+ "multipleWithPermissions_one": "Automatically updated {{count}} organization plugin; it includes new permissions.",
+ "multipleWithPermissions_other": "Automatically updated {{count}} organization plugins; some plugins include new permissions."
+ },
"removalNotice": {
"single": "The organization removed the plugin “{{name}}”. Its local copy and data on this device have been cleaned up.",
"multiple_one": "The organization removed {{count}} plugin. Its local copy and data on this device have been cleaned up.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 5f9e15693c..5ddc402983 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3240,6 +3240,14 @@
"unavailable": "プラグインマーケットを一時的に利用できません。インストール済みプラグインは引き続き利用できます。",
"authenticationRequired": "プラグインマーケットを表示するには Cindy にログインしてください。",
"notConfigured": "この環境ではプラグインマーケットが設定されていません。インストール済みプラグインは引き続き利用できます。",
+ "upgradeNotice": {
+ "single": "組織のプラグイン「{{name}}」を自動更新しました。",
+ "multiple_one": "組織の {{count}} 個のプラグインを自動更新しました。",
+ "multiple_other": "組織の {{count}} 個のプラグインを自動更新しました。",
+ "singleWithPermissions": "組織のプラグイン「{{name}}」を自動更新しました。新しい権限:{{permissions}}",
+ "multipleWithPermissions_one": "組織の {{count}} 個のプラグインを自動更新しました。新しい権限が追加されました。",
+ "multipleWithPermissions_other": "組織の {{count}} 個のプラグインを自動更新しました。新しい権限が追加されたプラグインがあります。"
+ },
"removalNotice": {
"single": "プラグイン「{{name}}」は組織によって削除され、このデバイス上のローカルコピーとデータはクリーンアップされました。",
"multiple_one": "{{count}} 件のプラグインが組織によって削除され、このデバイス上のローカルコピーとデータはクリーンアップされました。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 89ff555a45..f94e4643c4 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3240,6 +3240,14 @@
"unavailable": "플러그인 마켓을 일시적으로 사용할 수 없습니다. 설치된 플러그인은 계속 사용할 수 있습니다.",
"authenticationRequired": "플러그인 마켓을 보려면 Cindy에 로그인하세요.",
"notConfigured": "이 환경에는 플러그인 마켓이 구성되지 않았습니다. 설치된 플러그인은 계속 사용할 수 있습니다.",
+ "upgradeNotice": {
+ "single": "조직 플러그인 ‘{{name}}’을(를) 자동으로 업데이트했습니다.",
+ "multiple_one": "조직 플러그인 {{count}}개를 자동으로 업데이트했습니다.",
+ "multiple_other": "조직 플러그인 {{count}}개를 자동으로 업데이트했습니다.",
+ "singleWithPermissions": "조직 플러그인 ‘{{name}}’을(를) 자동으로 업데이트했습니다. 새 권한: {{permissions}}",
+ "multipleWithPermissions_one": "조직 플러그인 {{count}}개를 자동으로 업데이트했습니다. 새 권한이 추가되었습니다.",
+ "multipleWithPermissions_other": "조직 플러그인 {{count}}개를 자동으로 업데이트했습니다. 일부 플러그인에 새 권한이 추가되었습니다."
+ },
"removalNotice": {
"single": "플러그인 “{{name}}”: 조직에서 제거했으며 이 기기의 로컬 사본과 데이터도 정리했습니다.",
"multiple_one": "{{count}}개의 플러그인이 조직에서 제거되었습니다. 이 기기의 로컬 사본과 데이터가 정리되었습니다.",
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 81c505df22..5b0e01d1a3 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3240,6 +3240,14 @@
"unavailable": "插件市场暂时不可用;已安装插件仍可正常管理和使用。",
"authenticationRequired": "登录 Cindy 后才能查看插件市场。",
"notConfigured": "当前环境未配置插件市场;已安装插件仍可正常管理和使用。",
+ "upgradeNotice": {
+ "single": "已自动更新企业插件“{{name}}”",
+ "multiple_one": "已自动更新 {{count}} 个企业插件",
+ "multiple_other": "已自动更新 {{count}} 个企业插件",
+ "singleWithPermissions": "已自动更新企业插件“{{name}}”,新增权限:{{permissions}}",
+ "multipleWithPermissions_one": "已自动更新 {{count}} 个企业插件,其中有插件新增了权限",
+ "multipleWithPermissions_other": "已自动更新 {{count}} 个企业插件,其中有插件新增了权限"
+ },
"removalNotice": {
"single": "插件“{{name}}”已被组织移除,本机副本与数据已清理",
"multiple_one": "{{count}} 个插件已被组织移除,本机副本与数据已清理",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index ac2ee90730..01ac69b753 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1518,6 +1518,10 @@ interface ElectronAPI {
import('../shared/pluginMarket').PluginRemovalUserNotice | null
>;
onRemovalNoticeAvailable: (callback: () => void) => () => void;
+ consumeUpgradeNotice: () => Promise<
+ import('../shared/pluginMarket').PluginUpgradeUserNotice | null
+ >;
+ onUpgradeNoticeAvailable: (callback: () => void) => () => void;
listSources: () => Promise<import('../shared/pluginMarket').MarketSourceSummary[]>;
pickLocalSource: (
defaultPath?: string,
diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.ts
index 34bfafd8fe..e6ec89e3a6 100644
--- a/apps/desktop/src/shared/pluginMarket.ts
+++ b/apps/desktop/src/shared/pluginMarket.ts
@@ -47,6 +47,22 @@ export interface PluginRemovalUserNotice {
name: string | null;
}
+export interface PluginUpgradePermissionNotice {
+ /** Shared permission item identity; Renderer resolves labelKey through i18n. */
+ key: string;
+ labelKey: string;
+ labelArgs?: Record<string, string>;
+}
+
+export interface PluginUpgradeUserNotice {
+ count: number;
+ name: string | null;
+ /** Added permissions for the sole upgraded plugin; null for multi-plugin batches. */
+ permissions: PluginUpgradePermissionNotice[] | null;
+ /** Whether any upgrade in the aggregate added permissions. */
+ hasPermissionExpansion: boolean;
+}
+
/** 详情携带安装前展示给用户的 manifest;官方来自 release,自定义来自本地发现。 */
export interface PluginMarketDetail extends PluginMarketItem {
manifest: GhostManifest;